<?php



namespace Blobt\Luxcore\scene;

use Blobt\Luxcore\scene\lights\Emission;
use Blobt\Luxcore\scene\lights\env\HdrImage;
use Blobt\Luxcore\scene\materials\Disney;
use Blobt\Luxcore\scene\materials\Matte;
use Blobt\Luxcore\scene\objects\Objects;
use Blobt\Luxcore\scene\render\Batch;
use Blobt\Luxcore\scene\render\effect\BackgroundImg;
use Blobt\Luxcore\scene\render\effect\CammaCorrection;
use Blobt\Luxcore\scene\render\effect\NoiseReducerOIDN;
use Blobt\Luxcore\scene\render\effect\Pretreatment;
use Blobt\Luxcore\scene\render\effect\Synthesis;
use Blobt\Luxcore\scene\render\effect\ToneMapLinear;
use Blobt\Luxcore\scene\render\FileSaver;
use Blobt\Luxcore\scene\render\Film;
use Blobt\Luxcore\scene\render\Filter;
use Blobt\Luxcore\scene\render\HybridBackforWard;
use Blobt\Luxcore\scene\render\Image;
use Blobt\Luxcore\scene\render\LightStrategy;
use Blobt\Luxcore\scene\render\Native;
use Blobt\Luxcore\scene\render\OpenCL;
use Blobt\Luxcore\scene\render\Path;
use Blobt\Luxcore\scene\render\RenderEngine;
use Blobt\Luxcore\scene\render\Sampler;
use Blobt\Luxcore\scene\texture\mapping\Mapping;
use Blobt\Luxcore\scene\texture\procedural\ImageMap;
use Blobt\Luxcore\utils\MatHelper;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

include dirname(dirname(__FILE__)) . "/vendor/autoload.php";

const OPEN = true | 1;
const CLOSE = false | 0;
/**
 * 标准材质长宽
 */
const MAT_STANDARD_SIZE = 1000;
const UNIT_CONVERSION_MM_TO_M = 0.001;




$client = new Client();
$response  =  $client->get("deep3d.backend-api.dev.com/test/render-task");
$resContents = $response->getBody()->getContents();
$result = json_decode($resContents,false);
$taskData = $result->data;
$taskScene = $taskData->scene;
$taskModel = $taskScene->model;
$taskCamera = $taskScene->camera;




/**
 * 创建 Luxcore 材质
 */
function createLuxcoreMat($matOriginal, $textureScaleU, $textureScaleV, $cacheFileDir, $scene){
    switch($matOriginal->renderType){
        case 1:
            return MatHelper::createMatOfDisney($matOriginal, $textureScaleU, $textureScaleV, $cacheFileDir, $scene);
        case 2:
            return MatHelper::createMatOfGlass($matOriginal, $textureScaleU, $textureScaleV, $cacheFileDir, $scene);
        case 3:
            return MatHelper::createMatOfTranslucent($matOriginal, $textureScaleU, $textureScaleV, $cacheFileDir, $scene);
        case 4:
            return;
    }
}




// 创建一个场景;
$scene = new Scene();
$sceneTemplatePath = dirname(dirname(__FILE__)) . "/sceneTemplate";


// 一、创建光场:
// 1、创建 面片光001
$material = new Matte();
$material->setBaseColor('0 0 0');
$material->setTransparencyShadow('1 1 1');
$material->setEmission('1 1 1');
$scene->registerMaterial($material);
$obj = new Objects();
$obj->ply = './ply/FaceLight001.ply';
$obj->setMaterial($material);
$scene->registerObjects($obj);

// 2、创建 面片光002
$material = new Matte();
$material->setBaseColor('0 0 0');
$material->setTransparencyShadow('1 1 1');
$material->setEmission('0 0 0');
$material->emissionCfg = new Emission([
    'gain' => "30 30 30",
]);
$scene->registerMaterial($material);
$obj = new Objects();
$obj->ply = './ply/FaceLight002.ply';
$obj->setMaterial($material);
$scene->registerObjects($obj);

// 3、创建 面片光003
$material = new Matte();
$material->setBaseColor('0 0 0');
$material->setTransparencyShadow('1 1 1');
$material->setEmission('1 1 1');
$material->emissionCfg = new Emission([
    'gain' => "50 50 50",
]);
$scene->registerMaterial($material);
$obj = new Objects();
$obj->ply = './ply/FaceLight003.ply';
$obj->setMaterial($material);
$scene->registerObjects($obj);

// 4、创建 面片光004
$material = new Matte();
$material->setBaseColor('0 0 0');
$material->setTransparencyShadow('1 1 1');
$material->setEmission('0 0 0');
$material->emissionCfg = new Emission([
    'gain' => "4 4 4",
]);
$scene->registerMaterial($material);
$obj = new Objects();
$obj->ply = './ply/FaceLight004.ply';
$obj->setMaterial($material);
$scene->registerObjects($obj);

// 5、创建 面片光005
$material = new Matte();
$material->setBaseColor('0 0 0');
$material->setTransparencyShadow('1 1 1');
$material->setEmission('1 1 1');
$material->emissionCfg = new Emission([
    'gain' => "10 10 10",
]);
$scene->registerMaterial($material);
$obj = new Objects();
$obj->ply = './ply/FaceLight005.ply';
$obj->setMaterial($material);
$scene->registerObjects($obj);

// 6、创建 面片光006
$material = new Matte();
$material->setBaseColor('0 0 0');
$material->setTransparencyShadow('1 1 1');
$material->setEmission('1 1 1');
$material->emissionCfg = new Emission([
    'gain' => "8 8 8",
    'mapfile' => "./map/SD-037.exr",
    'gamma' => 1,
    'storage' => "float"                         
]);
$scene->registerMaterial($material);
$obj = new Objects();
$obj->ply = './ply/FaceLight006.ply';
$obj->setMaterial($material);
$scene->registerObjects($obj);

// 7、创建 面片光000
$material = new Matte();
$material->setBaseColor('0 0 0');
$material->setTransparencyShadow('1 1 1');
$material->setEmission('1 1 1');
$material->emissionCfg = new Emission([
    'gain' => "3.3 3.3 3.3",
]);
$scene->registerMaterial($material);
$obj = new Objects();
$obj->ply = './ply/FaceLight000.ply';
$obj->setMaterial($material);
$scene->registerObjects($obj);

// 8、创建环境光
$light = new HdrImage([
    'gain' => "1.25 1.25 1.25",
    'transformation' => "0.1736481 -0.9848078 0 0 -0.9848078 -0.1736481 0 0 0 0 1 0 0 0 0 1",
    'file' => "./map/env.png",
    'gamma' => 1,
    'storage' => "byte"                          
]);
$light->id = 0;
$scene->registerLight($light);

// 9、创建地面模型
$mapping = new Mapping();
$mapping->useUVMapping2d(0, "0", "0.4 -0.966", "0.3 0.983");
$texture = new ImageMap([
    'file' => "./map/方形阴影遮照.png",            
    'gain' => 0.6,                               
    'gamma' => 1,                                
]);
$texture->mapping = $mapping;
$scene->registerTexture($texture);
$material = new Disney([
    'shadowcatcherEnable' => OPEN,               
    'photongiEnable' => CLOSE                    
]);
$material->setBaseColor('1 1 1');
$material->setTransparencyFront($texture);
$material->setTransparencyBack($texture);
$scene->registerMaterial($material);
$obj = new Objects();
$obj->ply = './ply/ground.ply';
$obj->setMaterial($material);
$scene->registerObjects($obj);


// 二、添加要渲染的模型
foreach($taskModel->childsParams as $childParams){
    // 如果某个模型节点不可见,则不添加到场景渲染
    if($childParams->isVisible !== 1){
        continue;
    }

    $cacheFileDir = $sceneTemplatePath.'/cacheFiles';
    $material = null;
    $matOriginal = (function ($childParams){
        if(is_object($childParams->customMat)){
            return $childParams->customMat;
        }else if(is_object($childParams->fixedMat)){
            return $childParams->fixedMat;
        }else if(is_object($childParams->defaultMat)){
            return $childParams->defaultMat;
        }
    })($childParams);
    
    if(is_object($matOriginal)){
        $textureScaleU = $taskModel->uvScale*(MAT_STANDARD_SIZE/$matOriginal->width);
        $textureScaleV = $taskModel->uvScale*(MAT_STANDARD_SIZE/$matOriginal->height)*-1;
        $material = createLuxcoreMat($matOriginal, $textureScaleU, $textureScaleV, $cacheFileDir, $scene);
    }else{
        $material = new Disney();
        $material->setBaseColor('1 1 1');
    }
    $scene->registerMaterial($material);

    $plyFileSavaPath = $cacheFileDir.'/'.basename($childParams->childPlyFile);
    $plyFileHandle = fopen($plyFileSavaPath, "w");
    (new Client())->get($childParams->childPlyFile, [RequestOptions::SINK => $plyFileHandle]);
    $obj = new Objects();
    $obj->ply = $plyFileSavaPath;
    $obj->setMaterial($material);
    $scene->registerObjects($obj);
}


// 三、创建相机
$position = $taskCamera->position;
$position->x = $position->x * UNIT_CONVERSION_MM_TO_M;
$position->y = $position->y * UNIT_CONVERSION_MM_TO_M;
$position->z = $position->z * UNIT_CONVERSION_MM_TO_M;
$target = $taskCamera->target;
$target->x = $target->x * UNIT_CONVERSION_MM_TO_M;
$target->y = $target->y * UNIT_CONVERSION_MM_TO_M;
$target->z = $target->z * UNIT_CONVERSION_MM_TO_M;
$upVector = $taskCamera->upVector;
$camera = new camera\Perspective(                         
    [
        'autovolumeEnable' => 0,
        'lookatOrig' => "{$position->x} {$position->y} {$position->z}",
        'lookatTarget' => "{$target->x} {$target->y} {$target->z}",
        'up' => "{$upVector->x} {$upVector->y} {$upVector->z}",
        'screenwindow' => "-1 1 -1 1",
        'autofocusEnable' => 0,
        'fieldofview' => $taskCamera->fov,
        'cliphither' => 0.1,
    ]
);
$camera->bokeh->blades = 0;
$scene->registerCamera($camera);


// 四、设置渲染参数
// gpu 渲染
$render = '';
$renderEngine = new RenderEngine();
$render .= $renderEngine;

$openCL = new OpenCL();
// $openCL->cpuUse = OpenCL::CLOSE;
// $openCL->nativeThreadsCount = 0;
$render .= $openCL;

$lightStrategy = new LightStrategy();
$render .= $lightStrategy;

$hybridBackforWard = new HybridBackforWard();
$hybridBackforWard->partition = 1;
$path = new Path([],null,$hybridBackforWard);
$render .= $path;

$sampler = new Sampler();
$render .= $sampler;

$filesaver = new FileSaver();
$render .= $filesaver;

$batch = new Batch();
$batch->haltspp = 4000;
// $batch->halttime = 2000;
$render .= $batch;

$sceneCfg = new render\Scene();
$render .= $sceneCfg;


// // cpu 渲染
// $render = '';
// $renderEngine = new RenderEngine();
// $renderEngine->type = RenderEngine::TYPE_PATHCPU;
// $render .= $renderEngine;

// $native = new Native();
// $render .= $native;

// $lightStrategy = new LightStrategy();
// $render .= $lightStrategy;
    
// $hybridBackforWard = new HybridBackforWard();
// $hybridBackforWard->partition = 0.8;
// $path = new Path([],null,$hybridBackforWard);
// $render .= $path;

// $sampler = new Sampler();
// $render .= $sampler;

// $filesaver = new FileSaver();
// $filesaver->renderengineType = FileSaver::TYPE_PATHCPU;
// $render .= $filesaver;

// $batch = new Batch();
// $batch->haltspp = 4000;
// // $batch->halttime = 2000;
// $render .= $batch;

// $sceneCfg = new render\Scene();
// $render .= $sceneCfg;


// 图像输出设置
$imageOutDir = $sceneTemplatePath.'/imageOut';
$film = new Film();

$filter = new Filter();
$filter->type = Filter::TYPE_GAUSSIAN;
$filter->gaussianAlpha = 1;
$filter->width = 1;

$film->filter = $filter;
$film->width = 4096;
$film->heigth = 4096;

$img = new Image();
$img->effect = [new Pretreatment(),new ToneMapLinear(),new CammaCorrection()];
$film->addImage($img, $imageOutDir);

$film->addImage(new Image(['type' => Image::TYPE_OBJECT_ID]), $imageOutDir);
$film->addImage(new Image(['type' => Image::TYPE_RGBA]), $imageOutDir);

$img = new Image();
// $img->effect[] = new NoiseReducerOIDN();
$img->effect[] = new Pretreatment();
$img->effect[] = new ToneMapLinear();
$img->effect[] = new Synthesis();
$img->effect[] = new BackgroundImg(           
    [
        'file' => "./map/纯白242.png"
    ]
);
$img->effect[] = new CammaCorrection();
$film->addImage($img, $imageOutDir);
$render .= $film;


// 五、输出场景文件 scene.scn,及渲染文件 render.cfg
$cfgPath = $sceneTemplatePath . "/render.cfg";
$scenePath = $sceneTemplatePath . "/scene.scn";
$logPath = $sceneTemplatePath . "/log/render.log";

echo $scene;
$handle = fopen( $scenePath,'w+');
fwrite($handle,$scene);
fclose($handle);

echo $render ;
$handle = fopen( $cfgPath,'w+');
fwrite($handle,$render);
fclose($handle);




// 六、启动渲染器
$cmd = "luxcoreconsole -o " . $cfgPath . " -f " . $scenePath . " 1>" . $logPath . " 2>&1";
echo "\n".$cmd."\n";
$output;
$returnVar;
exec($cmd,$output,$returnVar);

if( $returnVar == 127 ){
    throw new \Exception("Please install the luxcorerender bin file in the system directory correctly,Or add to the system environment variable");
}

?>