From a2aa1b491abe26464b54c9ab25e493cac1ad4616 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Wed, 29 Nov 2023 14:26:44 +0800 Subject: [PATCH 001/106] transform --- ui/zenoedit/viewportinteraction/transform.cpp | 6 +++--- zeno/src/nodes/prim/TransformPrimitive.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 222ed3faa5..1c27190da7 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -305,7 +305,7 @@ void FakeTransformer::createNewTransformNode(NodeLocation& node_location, auto out_sock = node_sync.getPrimSockName(node_location); auto new_node_location = node_sync.generateNewNode(node_location, - "TransformPrimitive", + "PrimitiveTransform", out_sock, "prim"); @@ -430,7 +430,7 @@ void FakeTransformer::endTransform(bool moved) { auto& node_sync = NodeSyncMgr::GetInstance(); auto prim_node_location = node_sync.searchNodeOfPrim(obj_name); auto& prim_node = prim_node_location->node; - if (node_sync.checkNodeType(prim_node, "TransformPrimitive") && + if (node_sync.checkNodeType(prim_node, "PrimitiveTransform") && // prim comes from a exist TransformPrimitive node node_sync.checkNodeInputHasValue(prim_node, "translation") && node_sync.checkNodeInputHasValue(prim_node, "quatRotation") && @@ -440,7 +440,7 @@ void FakeTransformer::endTransform(bool moved) { else { // prim comes from another type node auto linked_transform_node = - node_sync.checkNodeLinkedSpecificNode(prim_node, "TransformPrimitive"); + node_sync.checkNodeLinkedSpecificNode(prim_node, "PrimitiveTransform"); if (linked_transform_node.has_value()) // prim links to a exist TransformPrimitive node syncToTransformNode(linked_transform_node.value(), obj_name); diff --git a/zeno/src/nodes/prim/TransformPrimitive.cpp b/zeno/src/nodes/prim/TransformPrimitive.cpp index d3ae3d3848..26e488d13b 100644 --- a/zeno/src/nodes/prim/TransformPrimitive.cpp +++ b/zeno/src/nodes/prim/TransformPrimitive.cpp @@ -190,7 +190,7 @@ ZENDEFNODE(TransformPrimitive, { {"enum " + EulerAngle::RotationOrderListString(), "EulerRotationOrder", "ZYX"}, {"enum " + EulerAngle::MeasureListString(), "EulerAngleMeasure", EulerAngle::MeasureDefaultString()} }, - {"primitive"}, + {"deprecated"}, }); // euler rot order: roll-pitch-yaw From 79bfea611f7231afa3617dc5763c24247c79cdea Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Fri, 1 Dec 2023 17:54:17 +0800 Subject: [PATCH 002/106] add comment --- ui/zenoedit/viewportinteraction/transform.cpp | 5 +++-- ui/zenoedit/viewportinteraction/transform.h | 15 ++++++++++----- zeno/src/nodes/prim/TransformPrimitive.cpp | 3 ++- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 1c27190da7..361243e848 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -74,6 +74,7 @@ void FakeTransformer::addObject(const std::string& name) { user_data.setLiterial("_rotate", rotate); zeno::vec3f scale = {1, 1, 1}; user_data.setLiterial("_scale", scale); + user_data.set2("_pivot", "bboxCenter"); } auto m = zeno::vec_to_other(bmax); auto n = zeno::vec_to_other(bmin); @@ -675,7 +676,7 @@ void FakeTransformer::doTransform() { auto scale = zeno::vec_to_other(user_data.getLiterial("_scale")); // inv last transform - auto pre_translate_matrix = glm::translate(translate + m_last_trans); + auto pre_translate_matrix = glm::translate(translate + m_last_trans - m_pivot); auto pre_quaternion = glm::quat(rotate[3], rotate[0], rotate[1], rotate[2]); auto last_quaternion = glm::quat(m_last_rotate[3], m_last_rotate[0], m_last_rotate[1], m_last_rotate[2]); auto pre_rotate_matrix = glm::toMat4(pre_quaternion); @@ -684,7 +685,7 @@ void FakeTransformer::doTransform() { auto inv_pre_transform = glm::inverse(pre_transform_matrix); // do this transform - auto translate_matrix = glm::translate(translate + m_trans); + auto translate_matrix = glm::translate(translate + m_trans - m_pivot); auto cur_quaternion = glm::quat(m_rotate[3], m_rotate[0], m_rotate[1], m_rotate[2]); auto rotate_matrix = glm::toMat4(cur_quaternion) * pre_rotate_matrix; auto scale_matrix = glm::scale(scale * m_scale); diff --git a/ui/zenoedit/viewportinteraction/transform.h b/ui/zenoedit/viewportinteraction/transform.h index b5cb237146..13915ca32a 100644 --- a/ui/zenoedit/viewportinteraction/transform.h +++ b/ui/zenoedit/viewportinteraction/transform.h @@ -24,7 +24,7 @@ enum { }; class FakeTransformer { -public: +public: FakeTransformer(ViewportWidget* viewport); void addObject(const std::string& name); void addObject(const std::unordered_set& names); @@ -48,12 +48,15 @@ class FakeTransformer { glm::vec3 getCenter() const; void clear(); -private: - zenovis::Scene* scene() const; +private: + zenovis::Scene* scene() const; zenovis::Session* session() const; + // 计算translate并调用doTransform void translate(glm::vec3 start, glm::vec3 end, glm::vec3 axis); + // 计算scale并调用doTransform void scale(float scale_size, vec3i axis); + // 计算rotate并调用doTransform void rotate(glm::vec3 start_vec, glm::vec3 end_vec, glm::vec3 axis); void createNewTransformNode(NodeLocation& node_location, @@ -61,6 +64,7 @@ class FakeTransformer { void syncToTransformNode(NodeLocation& node_location, const std::string& obj_name); + // 把FakeTransform上的SRT应用到primitive上 void doTransform(); static glm::vec3 QVec3ToGLMVec3(QVector3D QVec3) { @@ -101,6 +105,7 @@ class FakeTransformer { glm::vec3 m_objects_center; + glm::vec3 m_pivot; glm::vec3 m_trans; glm::vec4 m_rotate; glm::vec3 m_scale; @@ -118,8 +123,8 @@ class FakeTransformer { int m_operation_mode; int m_coord_sys; float m_handler_scale; - std::shared_ptr m_handler; - ViewportWidget* m_viewport; + std::shared_ptr m_handler; + ViewportWidget* m_viewport; }; } diff --git a/zeno/src/nodes/prim/TransformPrimitive.cpp b/zeno/src/nodes/prim/TransformPrimitive.cpp index 26e488d13b..149aa5560c 100644 --- a/zeno/src/nodes/prim/TransformPrimitive.cpp +++ b/zeno/src/nodes/prim/TransformPrimitive.cpp @@ -309,6 +309,7 @@ struct PrimitiveTransform : zeno::INode { vec4f rotate = {myQuat.x, myQuat.y, myQuat.z, myQuat.w}; user_data.setLiterial("_rotate", rotate); user_data.setLiterial("_scale", scaling); + user_data.set2("_pivot", pivotType); //auto oMat = std::make_shared(); //oMat->m = matrix; set_output("outPrim", std::move(outprim)); @@ -318,7 +319,7 @@ struct PrimitiveTransform : zeno::INode { ZENDEFNODE(PrimitiveTransform, { { {"PrimitiveObject", "prim"}, - {"enum world bboxCenter", "pivot", "world"}, + {"enum world bboxCenter", "pivot", "bboxCenter"}, {"vec3f", "translation", "0,0,0"}, {"vec3f", "eulerXYZ", "0,0,0"}, {"vec4f", "quatRotation", "0,0,0,1"}, From cafd070ff60c84c667ccfd6f338524d6692c5516 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 4 Dec 2023 14:23:00 +0800 Subject: [PATCH 003/106] origin pos nrm --- ui/zenoedit/viewportinteraction/transform.cpp | 8 ++++++++ zeno/src/nodes/prim/TransformPrimitive.cpp | 2 ++ 2 files changed, 10 insertions(+) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 361243e848..65c8cc303b 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -75,6 +75,14 @@ void FakeTransformer::addObject(const std::string& name) { zeno::vec3f scale = {1, 1, 1}; user_data.setLiterial("_scale", scale); user_data.set2("_pivot", "bboxCenter"); + if (object->has_attr("pos") && !object->has_attr("_origin_pos")) { + auto &pos = object->attr("pos"); + object->verts.add_attr("_origin_pos") = pos; + } + if (object->has_attr("nrm") && !object->has_attr("_origin_nrm")) { + auto &nrm = object->attr("nrm"); + object->verts.add_attr("_origin_nrm") = nrm; + } } auto m = zeno::vec_to_other(bmax); auto n = zeno::vec_to_other(bmin); diff --git a/zeno/src/nodes/prim/TransformPrimitive.cpp b/zeno/src/nodes/prim/TransformPrimitive.cpp index 149aa5560c..1088b4b032 100644 --- a/zeno/src/nodes/prim/TransformPrimitive.cpp +++ b/zeno/src/nodes/prim/TransformPrimitive.cpp @@ -286,6 +286,7 @@ struct PrimitiveTransform : zeno::INode { if (prim->has_attr("pos")) { auto &pos = outprim->attr("pos"); + outprim->verts.add_attr("_origin_pos") = pos; #pragma omp parallel for for (int i = 0; i < pos.size(); i++) { auto p = zeno::vec_to_other(pos[i]); @@ -296,6 +297,7 @@ struct PrimitiveTransform : zeno::INode { if (prim->has_attr("nrm")) { auto &nrm = outprim->attr("nrm"); + outprim->verts.add_attr("_origin_nrm") = nrm; #pragma omp parallel for for (int i = 0; i < nrm.size(); i++) { auto n = zeno::vec_to_other(nrm[i]); From bd70cc2902caba5b25c25c32e3e6507ac6c9ddd4 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Fri, 8 Dec 2023 16:29:23 +0800 Subject: [PATCH 004/106] ShaderVecExtract --- zeno/src/nodes/mtl/ShaderExtractVec.cpp | 2 +- zeno/src/nodes/mtl/ShaderUtils.cpp | 45 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/zeno/src/nodes/mtl/ShaderExtractVec.cpp b/zeno/src/nodes/mtl/ShaderExtractVec.cpp index 6af2496235..1829a7b6d6 100644 --- a/zeno/src/nodes/mtl/ShaderExtractVec.cpp +++ b/zeno/src/nodes/mtl/ShaderExtractVec.cpp @@ -47,7 +47,7 @@ ZENDEFNODE(ShaderExtractVec, { {"float", "w"}, }, {}, - {"shader"}, + {"deprecated"}, }); diff --git a/zeno/src/nodes/mtl/ShaderUtils.cpp b/zeno/src/nodes/mtl/ShaderUtils.cpp index ec4e937691..144c3c2938 100644 --- a/zeno/src/nodes/mtl/ShaderUtils.cpp +++ b/zeno/src/nodes/mtl/ShaderUtils.cpp @@ -4,6 +4,7 @@ #include #include "zeno/types/PrimitiveObject.h" #include "zeno/types/UserData.h" +#include "zeno/utils/format.h" namespace zeno { @@ -95,6 +96,50 @@ ZENDEFNODE(ShaderVecConvert, { {"shader"}, }); +struct ShaderVecExtract : ShaderNodeClone { + int ty{}; + + virtual int determineType(EmissionPass *em) override { + auto _type = get_param("type"); + em->determineType(get_input("in").get()); + if (_type == "xyz" || _type == "xyz(srgb)") { + ty = 3; + } + else { + ty = 1; + } + return ty; + } + + virtual void emitCode(EmissionPass *em) override { + std::string exp = em->determineExpr(get_input("in").get()); + auto _type = get_param("type"); + if (_type == "xyz") { + em->emitCode(em->funcName("convertTo3(" + exp + ")")); + } + else if (_type == "xyz(srgb)") { + em->emitCode(em->funcName("pow(convertTo3(" + exp + "), 2.2f)")); + } + else if (_type == "1-w"){ + em->emitCode(zeno::format("(1-{}.w)", exp)); + } + else { + em->emitCode(exp + "." + _type); + } + } +}; + +ZENDEFNODE(ShaderVecExtract, { + { + {"in"}, + }, + {"out"}, + { + {"enum x y z w xyz 1-w xyz(srgb)", "type", "xyz"}, + }, + {"shader"}, +}); + struct ShaderNormalMap : ShaderNodeClone { virtual int determineType(EmissionPass *em) override { auto in1 = get_input("normalTexel"); From 75ec0f768139d34178d6f5c4530f73a7c30cd7da Mon Sep 17 00:00:00 2001 From: seeeagull Date: Fri, 8 Dec 2023 17:33:42 +0800 Subject: [PATCH 005/106] enable marking edge --- projects/Geometry/quadmesh.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/projects/Geometry/quadmesh.cpp b/projects/Geometry/quadmesh.cpp index c379e9e590..4de1aff6fa 100644 --- a/projects/Geometry/quadmesh.cpp +++ b/projects/Geometry/quadmesh.cpp @@ -46,6 +46,8 @@ struct QuadMesh : INode { marked_lines.insert(std::make_pair(lines[i][0], lines[i][1])); } } + if (marked_lines.size() > 0) + boundary = true; int scale_constraints = 0; scale_constraints += scale > 0 ? 1 : 0; @@ -58,7 +60,7 @@ struct QuadMesh : INode { } int argc = 1; - char* argv[10]; + char* argv[20]; argv[0] = (char*)malloc(sizeof("./InstantMeshes\0")); strcpy(argv[0], "./InstantMeshes\0"); if (crease > 0) { From 36c8cf74e87bd715fa0e3806f846a5dd148624c9 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Sat, 9 Dec 2023 18:20:17 +0800 Subject: [PATCH 006/106] fix-abc-write --- projects/Alembic/ReadAlembic.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index 8852f0acd9..6101f61c6a 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -802,6 +802,11 @@ struct AlembicSplitByName: INode { else { new_prim->polys.resize(0); } + new_prim->userData().del("faceset_count"); + for (auto j = 0; j < faceset_count; j++) { + new_prim->userData().del(zeno::format("faceset_{:04}", j)); + } + new_prim->userData().set2("_abc_faceset", name); dict->lut[name] = std::move(new_prim); } set_output("dict", dict); From d705a6a36b609c031bae937b8874ad5a9f2a978e Mon Sep 17 00:00:00 2001 From: littlemine Date: Sat, 9 Dec 2023 23:44:42 +0800 Subject: [PATCH 007/106] fix primmerge loopuv --- zeno/src/nodes/neo/PrimMerge.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zeno/src/nodes/neo/PrimMerge.cpp b/zeno/src/nodes/neo/PrimMerge.cpp index 19f880d7f8..643617c762 100644 --- a/zeno/src/nodes/neo/PrimMerge.cpp +++ b/zeno/src/nodes/neo/PrimMerge.cpp @@ -407,7 +407,7 @@ ZENO_API std::shared_ptr primMerge(std::vectoruvs.values; size_t n = std::min(arr.size(), prim->uvs.size()); for (size_t i = 0; i < n; i++) { - outarr[base + i] = base + arr[i]; + outarr[base + i] = arr[i]; } } else { auto &outarr = outprim->uvs.attr(key); From 0f918678855ccbcb9b02b1ba62e77f8aea68c79e Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Sun, 10 Dec 2023 11:50:03 +0800 Subject: [PATCH 008/106] camera centered rendering --- zeno/src/nodes/StringNodes.cpp | 54 ++++++++++ zenovis/include/zenovis/Camera.h | 2 +- zenovis/xinxinoptix/DeflMatShader.cu | 12 ++- zenovis/xinxinoptix/DisneyBSDF.h | 16 +-- zenovis/xinxinoptix/Light.h | 4 +- zenovis/xinxinoptix/PTKernel.cu | 6 +- zenovis/xinxinoptix/TraceStuff.h | 7 +- zenovis/xinxinoptix/optixPathTracer.cpp | 138 +++++++++++++++++++++++- 8 files changed, 220 insertions(+), 19 deletions(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 591a97c5ad..e2fc418a96 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -248,6 +248,60 @@ ZENDEFNODE(StringRegexMatch, { {"string"}, }); + +struct StringSplitAndMerge: zeno::INode{ + + std::vector split(const std::string& s, std::string seperator) + { + std::vector output; + + std::string::size_type prev_pos = 0, pos = 0; + + while((pos = s.find(seperator, pos)) != std::string::npos) + { + std::string substring( s.substr(prev_pos, pos-prev_pos) ); + + output.push_back(substring); + + prev_pos = ++pos; + } + + output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word + + return output; + } + virtual void apply() override { + auto str = get_input2("str"); + auto schar = get_input2("schar"); + auto merge = get_input2("merge"); + + auto &strings = split(str, schar); + auto &merges = split(merge, ","); + std::string outputstr = ""; + for(auto idx:merges) + { + outputstr += strings[std::atoi(idx.c_str())]; + } + + set_output2("output", outputstr); + } +}; + +ZENDEFNODE(StringSplitAndMerge, { + { + {"string", "str", ""}, + {"string", "schar", "_"}, + {"string", "merge", "0"}, + }, + { + {"string", "output"} + }, + {}, + {"string"}, +}); + + + struct FormatString : zeno::INode { virtual void apply() override { auto formatStr = get_input2("str"); diff --git a/zenovis/include/zenovis/Camera.h b/zenovis/include/zenovis/Camera.h index bf6bdba355..92cb8de8f7 100644 --- a/zenovis/include/zenovis/Camera.h +++ b/zenovis/include/zenovis/Camera.h @@ -20,7 +20,7 @@ struct Camera { float m_far = 20000.0f; float m_fov = 45.f; - float m_aperture = 11.0f; + float m_aperture = 0.0f; float focalPlaneDistance = 2.0f; float m_dof = -1.f; float m_safe_frames = 0; diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index 45249da79f..f1b91025c7 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -186,6 +186,7 @@ static __inline__ __device__ bool isBadVector(const float3& vector) { extern "C" __global__ void __anyhit__shadow_cutout() { + const OptixTraversableHandle gas = optixGetGASTraversableHandle(); const uint sbtGASIndex = optixGetSbtGASIndex(); const uint primIdx = optixGetPrimitiveIndex(); @@ -199,6 +200,7 @@ extern "C" __global__ void __anyhit__shadow_cutout() RadiancePRD* prd = getPRD(); MatInput attrs{}; + bool sphere_external_ray = false; #if (_SPHERE_) @@ -329,6 +331,7 @@ extern "C" __global__ void __anyhit__shadow_cutout() auto sssParam = mats.sssParam; auto scatterStep = mats.scatterStep; + if(params.simpleRender==true) opacity = 0; //opacity = clamp(opacity, 0.0f, 0.99f); @@ -432,7 +435,7 @@ extern "C" __global__ void __closesthit__radiance() const uint primIdx = optixGetPrimitiveIndex(); const float3 ray_orig = optixGetWorldRayOrigin(); - const float3 ray_dir = optixGetWorldRayDirection(); + const float3 ray_dir = normalize(optixGetWorldRayDirection()); float3 P = ray_orig + optixGetRayTmax() * ray_dir; HitGroupData* rt_data = (HitGroupData*)optixGetSbtDataPointer(); @@ -491,11 +494,11 @@ extern "C" __global__ void __closesthit__radiance() attrs.pos = P; float3 N_Local = normalize( cross( normalize(v1-v0), normalize(v2-v1) ) ); // this value has precision issue for big float - float3 N_World = optixTransformNormalFromObjectToWorldSpace(N_Local); + float3 N_World = normalize(optixTransformNormalFromObjectToWorldSpace(N_Local)); if (isBadVector(N_World)) { - N_World = DisneyBSDF::SampleScatterDirection(prd->seed); + N_World = normalize(DisneyBSDF::SampleScatterDirection(prd->seed)); N_World = faceforward( N_World, -ray_dir, N_World ); } prd->geometryNormal = N_World; @@ -650,6 +653,7 @@ extern "C" __global__ void __closesthit__radiance() prd->passed = false; if(mats.opacity>0.99f) { + if (prd->curMatIdx > 0) { vec3 sigma_t, ss_alpha; //vec3 sigma_t, ss_alpha; @@ -662,6 +666,7 @@ extern "C" __global__ void __closesthit__radiance() } prd->attenuation2 = prd->attenuation; prd->passed = true; + prd->adepth++; //prd->samplePdf = 0.0f; prd->radiance = make_float3(0.0f); //prd->origin = P + 1e-5 * ray_dir; @@ -686,6 +691,7 @@ extern "C" __global__ void __closesthit__radiance() } prd->attenuation2 = prd->attenuation; prd->passed = true; + prd->adepth++; //prd->samplePdf = 0.0f; //you shall pass! prd->radiance = make_float3(0.0f); diff --git a/zenovis/xinxinoptix/DisneyBSDF.h b/zenovis/xinxinoptix/DisneyBSDF.h index df5a8c951a..3566e43357 100644 --- a/zenovis/xinxinoptix/DisneyBSDF.h +++ b/zenovis/xinxinoptix/DisneyBSDF.h @@ -671,10 +671,10 @@ namespace DisneyBSDF{ tbn.inverse_transform(wi); wi = normalize(wi); -// if(dot(wi, N2)<0) -// { -// wi = normalize(wi - 1.01f * dot(wi, N2) * N2); -// } + if(dot(wi, N2)<0) + { + wi = normalize(wi - 1.01f * dot(wi, N2) * N2); + } }else if(r3 _FLT_EPL_ && lsr.PDF > _FLT_EPL_) { - + shadow_prd.depth = 0; traceOcclusion(params.handle, shadingP, lsr.dir, 0, lsr.dist, &shadow_prd); light_attenuation = shadow_prd.shadowAttanuation; @@ -460,7 +460,7 @@ void DirectLighting(RadiancePRD *prd, RadiancePRD& shadow_prd, const float3& sha if (envpdf < __FLT_DENORM_MIN__) { return; } - + shadow_prd.depth = 0; //LP = rtgems::offset_ray(LP, sun_dir); traceOcclusion(params.handle, LP, sun_dir, 1e-5f, // tmin diff --git a/zenovis/xinxinoptix/PTKernel.cu b/zenovis/xinxinoptix/PTKernel.cu index 8642e78f3d..3b3e1be421 100644 --- a/zenovis/xinxinoptix/PTKernel.cu +++ b/zenovis/xinxinoptix/PTKernel.cu @@ -154,11 +154,13 @@ extern "C" __global__ void __raygen__rg() terminal_point = camera_transform * terminal_point; eye_shake = camera_transform * eye_shake; - float3 ray_origin = cam.eye + eye_shake; + float3 ray_origin = eye_shake; float3 ray_direction = terminal_point - eye_shake; ray_direction = normalize(ray_direction); RadiancePRD prd; + prd.adepth = 0; + prd.camPos = ray_origin; prd.emission = make_float3(0.f); prd.radiance = make_float3(0.f); prd.attenuation = make_float3(1.f); @@ -245,7 +247,7 @@ extern "C" __global__ void __raygen__rg() prd.done = true; } - if( prd.done || params.simpleRender==true){ + if( prd.done || params.simpleRender==true || prd.adepth>64){ break; } diff --git a/zenovis/xinxinoptix/TraceStuff.h b/zenovis/xinxinoptix/TraceStuff.h index 38f87e1922..bbb2378bda 100644 --- a/zenovis/xinxinoptix/TraceStuff.h +++ b/zenovis/xinxinoptix/TraceStuff.h @@ -55,6 +55,7 @@ struct RadiancePRD float3 attenuation2; float3 origin; float3 direction; + float3 camPos; float minSpecRough; bool passed; float prob; @@ -81,6 +82,7 @@ struct RadiancePRD int curMatIdx; float samplePdf; bool fromDiff; + unsigned char adepth; __forceinline__ float rndf() { return rnd(this->seed); @@ -123,7 +125,10 @@ struct RadiancePRD void offsetRay(float3& P, const float3& new_dir) { bool forward = dot(geometryNormal, new_dir) > 0; - P = rtgems::offset_ray(P, forward? geometryNormal:-geometryNormal); + auto dir = forward? geometryNormal:-geometryNormal; + auto offset = rtgems::offset_ray(P, dir); + float l = length( offset - P ); + P = l>1e-4? offset : (P + 1e-4 * dir); } void offsetUpdateRay(float3& P, float3 new_dir) { diff --git a/zenovis/xinxinoptix/optixPathTracer.cpp b/zenovis/xinxinoptix/optixPathTracer.cpp index 59b23dfdf4..37189fe5cc 100644 --- a/zenovis/xinxinoptix/optixPathTracer.cpp +++ b/zenovis/xinxinoptix/optixPathTracer.cpp @@ -426,7 +426,131 @@ static void initLaunchParams( PathTracerState& state ) state.params.subframe_index = 0u; } +static void updateRootIAS() +{ + timer.tick(); + auto campos = state.params.cam.eye; + const float mat3r4c[12] = {1,0,0,-campos.x, 0,1,0,-campos.y, 0,0,1,-campos.z}; + std::vector optix_instances{}; + uint sbt_offset = 0u; + { + if (state.meshHandleIAS != 0u) { + OptixInstance inst{}; + + inst.flags = OPTIX_INSTANCE_FLAG_NONE; + inst.sbtOffset = 0; + inst.instanceId = 0; + inst.visibilityMask = DefaultMatMask; + inst.traversableHandle = state.meshHandleIAS; + + memcpy(inst.transform, mat3r4c, sizeof(float) * 12); + optix_instances.push_back( inst ); + } + } + + auto optix_instance_idx = optix_instances.size()-1; + + if (sphereHandleXAS != 0u) { + OptixInstance opinstance {}; + ++optix_instance_idx; + sbt_offset = 0u; + + opinstance.flags = OPTIX_INSTANCE_FLAG_NONE; + opinstance.instanceId = optix_instance_idx; + opinstance.sbtOffset = sbt_offset; + opinstance.visibilityMask = DefaultMatMask; + opinstance.traversableHandle = sphereHandleXAS; + memcpy(opinstance.transform, mat3r4c, sizeof(float) * 12); + optix_instances.push_back( opinstance ); + } + + // process volume + for ( uint i=0; ihandle; + getOptixTransform( *(list_volume[i]), optix_instance.transform ); // transform as stored in Grid + + optix_instances.push_back( optix_instance ); + } + + uint32_t MAX_INSTANCE_ID; + optixDeviceContextGetProperty( state.context, + OPTIX_DEVICE_PROPERTY_LIMIT_MAX_INSTANCE_ID, &MAX_INSTANCE_ID, sizeof(MAX_INSTANCE_ID)); + state.params.maxInstanceID = MAX_INSTANCE_ID; + + //process light + if (lightsWrapper.lightTrianglesGas != 0) + { + ++optix_instance_idx; + OptixInstance opinstance {}; + + auto combinedID = std::string("Light") + ":" + std::to_string(ShaderMaker::Mesh); + auto shader_index = OptixUtil::matIDtoShaderIndex[combinedID]; + + opinstance.flags = OPTIX_INSTANCE_FLAG_NONE; + opinstance.instanceId = MAX_INSTANCE_ID-2; + opinstance.sbtOffset = shader_index * RAY_TYPE_COUNT; + opinstance.visibilityMask = LightMatMask; + opinstance.traversableHandle = lightsWrapper.lightTrianglesGas; + memcpy(opinstance.transform, mat3r4c, sizeof(float) * 12); + + optix_instances.push_back( opinstance ); + } + + if (lightsWrapper.lightPlanesGas != 0) + { + ++optix_instance_idx; + OptixInstance opinstance {}; + + auto combinedID = std::string("Light") + ":" + std::to_string(ShaderMaker::Mesh); + auto shader_index = OptixUtil::matIDtoShaderIndex[combinedID]; + + opinstance.flags = OPTIX_INSTANCE_FLAG_NONE; + opinstance.instanceId = MAX_INSTANCE_ID-1; + opinstance.sbtOffset = shader_index * RAY_TYPE_COUNT; + opinstance.visibilityMask = LightMatMask; + opinstance.traversableHandle = lightsWrapper.lightPlanesGas; + memcpy(opinstance.transform, mat3r4c, sizeof(float) * 12); + + optix_instances.push_back( opinstance ); + } + + if (lightsWrapper.lightSpheresGas != 0) + { + ++optix_instance_idx; + OptixInstance opinstance {}; + + auto combinedID = std::string("Light") + ":" + std::to_string(ShaderMaker::Sphere); + auto shader_index = OptixUtil::matIDtoShaderIndex[combinedID]; + + opinstance.flags = OPTIX_INSTANCE_FLAG_NONE; + opinstance.instanceId = MAX_INSTANCE_ID; + opinstance.sbtOffset = shader_index * RAY_TYPE_COUNT; + opinstance.visibilityMask = LightMatMask; + opinstance.traversableHandle = lightsWrapper.lightSpheresGas; + memcpy(opinstance.transform, mat3r4c, sizeof(float) * 12); + + optix_instances.push_back( opinstance ); + } + + OptixAccelBuildOptions accel_options{}; + accel_options.operation = OPTIX_BUILD_OPERATION_BUILD; + accel_options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION | OPTIX_BUILD_FLAG_ALLOW_RANDOM_VERTEX_ACCESS | OPTIX_BUILD_FLAG_ALLOW_RANDOM_INSTANCE_ACCESS; + + buildIAS(state.context, accel_options, optix_instances, state.rootBufferIAS, state.rootHandleIAS); + + timer.tock("update Root IAS"); + state.params.handle = state.rootHandleIAS; +} static void handleCameraUpdate( Params& params ) { if( !camera_changed ) @@ -437,7 +561,11 @@ static void handleCameraUpdate( Params& params ) //params.vp2 = cam_vp2; //params.vp3 = cam_vp3; //params.vp4 = cam_vp4; + camera.setAspectRatio( static_cast( params.windowSpace.x ) / static_cast( params.windowSpace.y ) ); + CUDA_SYNC_CHECK(); + updateRootIAS(); + CUDA_SYNC_CHECK(); //params.eye = camera.eye(); //camera.UVWFrame( params.U, params.V, params.W ); } @@ -506,6 +634,8 @@ static void updateState( sutil::CUDAOutputBuffer& output_buffer, Params& if( camera_changed || resize_dirty ) params.subframe_index = 0; + + handleCameraUpdate( params ); handleResize( output_buffer, params ); @@ -750,6 +880,7 @@ static size_t g_staticAndDynamicVertNum = 0; static void buildMeshIAS(PathTracerState& state, int rayTypeCount, std::vector> m_meshes) { std::cout<<"IAS begin"< optix_instances{}; uint sbt_offset = 0u; { @@ -1066,6 +1197,8 @@ void buildRootIAS() state.params.handle = state.rootHandleIAS; } + + static void buildMeshAccel( PathTracerState& state ) { // @@ -3541,6 +3674,7 @@ static void save_exr(float3* ptr, int w, int h, std::string path) { } } void optixrender(int fbo, int samples, bool denoise, bool simpleRender) { + bool imageRendered = false; samples = zeno::envconfig::getInt("SAMPLES", samples); // 张心欣老爷请添加环境变量:export ZENO_SAMPLES=256 From 34f286b53e03fbdba2b28ed56bac2bf2664f1916 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 00:27:21 +0800 Subject: [PATCH 009/106] polys-loops-attr-read --- projects/Alembic/ReadAlembic.cpp | 83 +++++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index 6101f61c6a..a4f49acf26 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -80,6 +80,18 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp attr[i] = { data[ 3 * i], data[3 * i + 1], data[3 * i + 2]}; } } + else if (prim->loops.size() == data.size()) { + auto &attr = prim->loops.add_attr(p.getName()); + for (auto i = 0; i < prim->loops.size(); i++) { + attr[i] = data[i]; + } + } + else if (prim->polys.size() == data.size()) { + auto &attr = prim->polys.add_attr(p.getName()); + for (auto i = 0; i < prim->polys.size(); i++) { + attr[i] = data[i]; + } + } else { if (!read_done) { log_error("[alembic] can not load attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); @@ -105,9 +117,21 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp attr[i] = data[i]; } } + else if (prim->loops.size() == data.size()) { + auto &attr = prim->loops.add_attr(p.getName()); + for (auto i = 0; i < prim->loops.size(); i++) { + attr[i] = data[i]; + } + } + else if (prim->polys.size() == data.size()) { + auto &attr = prim->polys.add_attr(p.getName()); + for (auto i = 0; i < prim->polys.size(); i++) { + attr[i] = data[i]; + } + } else { if (!read_done) { - log_error("[alembic] can not load attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + log_error("[alembic] can not load int attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); } } } @@ -124,6 +148,25 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp attr[i] = {v[0], v[1], v[2]}; } } + else if (prim->loops.size() == samp.getVals()->size()) { + auto &attr = prim->loops.add_attr(p.getName()); + for (auto i = 0; i < prim->loops.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else if (prim->polys.size() == samp.getVals()->size()) { + auto &attr = prim->polys.add_attr(p.getName()); + for (auto i = 0; i < prim->polys.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else { + if (!read_done) { + log_error("[alembic] can not load vec3f attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + } + } } else if (IN3fGeomParam::matches(p)) { if (!read_done) { @@ -138,6 +181,25 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp attr[i] = {v[0], v[1], v[2]}; } } + else if (prim->loops.size() == samp.getVals()->size()) { + auto &attr = prim->loops.add_attr(p.getName()); + for (auto i = 0; i < prim->loops.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else if (prim->polys.size() == samp.getVals()->size()) { + auto &attr = prim->polys.add_attr(p.getName()); + for (auto i = 0; i < prim->polys.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else { + if (!read_done) { + log_error("[alembic] can not load N3f attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + } + } } else if (IC3fGeomParam::matches(p)) { if (!read_done) { @@ -152,6 +214,25 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp attr[i] = {v[0], v[1], v[2]}; } } + else if (prim->loops.size() == samp.getVals()->size()) { + auto &attr = prim->loops.add_attr(p.getName()); + for (auto i = 0; i < prim->loops.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else if (prim->polys.size() == samp.getVals()->size()) { + auto &attr = prim->polys.add_attr(p.getName()); + for (auto i = 0; i < prim->polys.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else { + if (!read_done) { + log_error("[alembic] can not load C3f attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + } + } } else { if (!read_done) { From aed23bd6ab7fabd90b0457fe38980398b9c60f43 Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Mon, 11 Dec 2023 00:32:32 +0800 Subject: [PATCH 010/106] preset meterial subgraphs --- ui/zenoedit/acceptor/transferacceptor.cpp | 2 +- ui/zenoedit/acceptor/transferacceptor.h | 2 +- ui/zenoedit/dialog/zforksubgrapdlg.h | 22 +++ ui/zenoedit/dialog/zforksubgraphdlg.cpp | 79 ++++++++++ ui/zenoedit/dock/docktabcontent.cpp | 14 ++ ui/zenoedit/dock/docktabcontent.h | 1 + ui/zenoedit/nodesview/zenographseditor.cpp | 18 ++- .../nodesview/zsubnetlistitemdelegate.cpp | 13 +- .../nodesview/zsubnetlistitemdelegate.h | 1 + ui/zenoedit/nodesys/zenonode.cpp | 17 +++ ui/zenoedit/nodesys/zenosearchbar.cpp | 7 +- ui/zenoedit/panel/zenospreadsheet.cpp | 124 +++++++++++++++- ui/zenoedit/panel/zenospreadsheet.h | 7 +- ui/zenoedit/settings/zenosettingsmanager.cpp | 9 ++ ui/zenoedit/settings/zenosettingsmanager.h | 1 + ui/zenoedit/settings/zsettings.h | 1 + ui/zenoedit/viewport/cameracontrol.cpp | 28 +++- ui/zenoedit/zenomainwindow.cpp | 18 ++- ui/zenoedit/zenomainwindow.h | 2 +- ui/zenoio/acceptor/iacceptor.h | 2 +- ui/zenoio/reader/zsgreader.cpp | 5 +- ui/zenoio/writer/zsgwriter.cpp | 3 + ui/zenomodel/include/igraphsmodel.h | 8 +- ui/zenomodel/include/modelrole.h | 9 ++ ui/zenomodel/src/graphsmodel.cpp | 137 +++++++++++++++++- ui/zenomodel/src/graphsmodel.h | 7 +- ui/zenomodel/src/modelacceptor.cpp | 3 +- ui/zenomodel/src/modelacceptor.h | 2 +- ui/zenomodel/src/nodeparammodel.cpp | 5 + ui/zenomodel/src/subgraphmodel.cpp | 33 +++++ ui/zenomodel/src/subgraphmodel.h | 7 + ui/zenoui/comctrl/gv/zgraphicsnetlabel.cpp | 5 + 32 files changed, 563 insertions(+), 29 deletions(-) create mode 100644 ui/zenoedit/dialog/zforksubgrapdlg.h create mode 100644 ui/zenoedit/dialog/zforksubgraphdlg.cpp diff --git a/ui/zenoedit/acceptor/transferacceptor.cpp b/ui/zenoedit/acceptor/transferacceptor.cpp index 280a4a9014..880e6d1196 100644 --- a/ui/zenoedit/acceptor/transferacceptor.cpp +++ b/ui/zenoedit/acceptor/transferacceptor.cpp @@ -20,7 +20,7 @@ bool TransferAcceptor::setLegacyDescs(const rapidjson::Value& graphObj, const NO return false; } -void TransferAcceptor::BeginSubgraph(const QString &name) +void TransferAcceptor::BeginSubgraph(const QString &name, int type) { //no cache, for data consistency. m_currSubgraph = name; diff --git a/ui/zenoedit/acceptor/transferacceptor.h b/ui/zenoedit/acceptor/transferacceptor.h index 4d8655ab07..932cf0d43b 100644 --- a/ui/zenoedit/acceptor/transferacceptor.h +++ b/ui/zenoedit/acceptor/transferacceptor.h @@ -10,7 +10,7 @@ class TransferAcceptor : public IAcceptor //IAcceptor bool setLegacyDescs(const rapidjson::Value &graphObj, const NODE_DESCS &legacyDescs) override; - void BeginSubgraph(const QString &name) override; + void BeginSubgraph(const QString &name, int type) override; void EndSubgraph() override; void EndGraphs() override; bool setCurrentSubGraph(IGraphsModel *pModel, const QModelIndex &subgIdx) override; diff --git a/ui/zenoedit/dialog/zforksubgrapdlg.h b/ui/zenoedit/dialog/zforksubgrapdlg.h new file mode 100644 index 0000000000..f44c30e152 --- /dev/null +++ b/ui/zenoedit/dialog/zforksubgrapdlg.h @@ -0,0 +1,22 @@ +#ifndef __ZFORKSUBGRAPHDLG_H__ +#define __ZFORKSUBGRAPHDLG_H__ + +#include +#include "zenoui/comctrl/dialog/zframelessdialog.h" + +class ZForkSubgraphDlg : public ZFramelessDialog +{ + Q_OBJECT +public: + ZForkSubgraphDlg(const QMap & subgs, QWidget* parent = nullptr); +signals: + +private: + void initUi(); +private: + QString m_version; + QTableWidget* m_pTableWidget; + QMap m_subgsMap; +}; + +#endif \ No newline at end of file diff --git a/ui/zenoedit/dialog/zforksubgraphdlg.cpp b/ui/zenoedit/dialog/zforksubgraphdlg.cpp new file mode 100644 index 0000000000..5da0ec327e --- /dev/null +++ b/ui/zenoedit/dialog/zforksubgraphdlg.cpp @@ -0,0 +1,79 @@ +#include "zforksubgrapdlg.h" +#include +#include +#include "zenoapplication.h" +#include +#include + +ZForkSubgraphDlg::ZForkSubgraphDlg(const QMap& subgs, QWidget* parent) + : ZFramelessDialog(parent) + , m_subgsMap(subgs) +{ + initUi(); + QString path = ":/icons/zeno-logo.png"; + this->setTitleIcon(QIcon(path)); + this->setTitleText(tr("Fork Subgraphs")); + resize(ZenoStyle::dpiScaledSize(QSize(500, 600))); +} + +void ZForkSubgraphDlg::initUi() +{ + const QStringList& subgraphs = m_subgsMap.keys(); + QWidget* pWidget = new QWidget(this); + QVBoxLayout* pLayout = new QVBoxLayout(pWidget); + m_pTableWidget = new QTableWidget(this); + m_pTableWidget->verticalHeader()->setVisible(false); + m_pTableWidget->setProperty("cssClass", "select_subgraph"); + m_pTableWidget->setColumnCount(3); + QStringList labels = { tr("Subgraph"), tr("Name"), tr("Mtlid") }; + m_pTableWidget->setHorizontalHeaderLabels(labels); + m_pTableWidget->setShowGrid(false); + m_pTableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); + m_pTableWidget->setEditTriggers(QAbstractItemView::DoubleClicked); + m_pTableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); + m_pTableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); + for (const auto& subgraph : subgraphs) + { + int row = m_pTableWidget->rowCount(); + m_pTableWidget->insertRow(row); + QTableWidgetItem* pItem = new QTableWidgetItem(m_subgsMap[subgraph]); + pItem->setFlags(pItem->flags() & ~Qt::ItemIsEditable); + m_pTableWidget->setItem(row, 0, pItem); + + QTableWidgetItem* pNameItem = new QTableWidgetItem(subgraph); + m_pTableWidget->setItem(row, 1, pNameItem); + + QTableWidgetItem* pMatItem = new QTableWidgetItem(subgraph); + m_pTableWidget->setItem(row, 2, pMatItem); + + } + pLayout->addWidget(m_pTableWidget); + QHBoxLayout* pHLayout = new QHBoxLayout(this); + QPushButton* pOkBtn = new QPushButton(tr("Ok"), this); + QPushButton* pCancelBtn = new QPushButton(tr("Cancel"), this); + int width = ZenoStyle::dpiScaled(80); + pOkBtn->setFixedWidth(width); + pCancelBtn->setFixedWidth(width); + pHLayout->addStretch(); + pHLayout->addWidget(pOkBtn); + pHLayout->addWidget(pCancelBtn); + pLayout->addLayout(pHLayout); + this->setMainWidget(pWidget); + + connect(pOkBtn, &QPushButton::clicked, this, [=]() { + for (int row = 0; row < m_pTableWidget->rowCount(); row++) + { + QString subgName = m_pTableWidget->item(row, 0)->data(Qt::DisplayRole).toString(); + QString name = m_pTableWidget->item(row, 1)->data(Qt::DisplayRole).toString(); + QString mtlid = m_pTableWidget->item(row, 2)->data(Qt::DisplayRole).toString(); + IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + const QModelIndex& index = pGraphsModel->forkMaterial(pGraphsModel->index(subgName), name, mtlid, m_subgsMap.key(subgName)); + if (!index.isValid()) + { + QMessageBox::warning(this, tr("warring"), tr("fork preset subgraph '%1' failed.").arg(subgName)); + } + } + accept(); + }); + connect(pCancelBtn, &QPushButton::clicked, this, &ZForkSubgraphDlg::reject); +} \ No newline at end of file diff --git a/ui/zenoedit/dock/docktabcontent.cpp b/ui/zenoedit/dock/docktabcontent.cpp index 723342a4cf..520664d55f 100644 --- a/ui/zenoedit/dock/docktabcontent.cpp +++ b/ui/zenoedit/dock/docktabcontent.cpp @@ -382,6 +382,10 @@ void DockContent_Editor::initToolbar(QHBoxLayout* pToolLayout) cbZoom->setFixedSize(ZenoStyle::dpiScaled(60), ZenoStyle::dpiScaled(20)); cbZoom->view()->setFixedWidth(ZenoStyle::dpiScaled(85)); + cbSubgType = new ZComboBox(this); + cbSubgType->addItems({ tr("Normal"), tr("Material"), tr("Preset")}); + cbSubgType->setFixedSize(ZenoStyle::dpiScaled(80), ZenoStyle::dpiScaled(20)); + pToolLayout->addWidget(pListView); pToolLayout->addWidget(pTreeView); @@ -404,6 +408,7 @@ void DockContent_Editor::initToolbar(QHBoxLayout* pToolLayout) pToolLayout->addStretch(4); + pToolLayout->addWidget(cbSubgType); pToolLayout->addWidget(cbZoom); pToolLayout->addWidget(pSearchBtn); pToolLayout->addWidget(pSettings); @@ -625,6 +630,10 @@ void DockContent_Editor::initConnections() pLinkLineShape->setChecked(ZenoSettingsManager::GetInstance().getValue(name).toBool()); pLinkLineShape->setToolTip(pLinkLineShape->isChecked() ? tr("Straight Link") : tr("Curve Link")); } + else if (name == zsSubgraphType) + { + cbSubgType->setCurrentIndex(ZenoSettingsManager::GetInstance().getValue(name).toInt()); + } }); connect(&ZenoSettingsManager::GetInstance(), &ZenoSettingsManager::valueChanged, this, [=](QString key) { @@ -642,6 +651,11 @@ void DockContent_Editor::initConnections() m_btnKill->setVisible(true); } }); + + connect(cbSubgType, &ZComboBox::currentTextChanged, this, [=]() { + int type = cbSubgType->currentIndex(); + ZenoSettingsManager::GetInstance().setValue(zsSubgraphType, type); + }); } ZenoGraphsEditor* DockContent_Editor::getEditor() const diff --git a/ui/zenoedit/dock/docktabcontent.h b/ui/zenoedit/dock/docktabcontent.h index 56819e4c94..87a56dc18f 100644 --- a/ui/zenoedit/dock/docktabcontent.h +++ b/ui/zenoedit/dock/docktabcontent.h @@ -122,6 +122,7 @@ class DockContent_Editor : public DockToolbarWidget ZTextIconButton* m_btnKill; QComboBox* cbZoom; + ZComboBox* cbSubgType; }; class DockContent_View : public DockToolbarWidget diff --git a/ui/zenoedit/nodesview/zenographseditor.cpp b/ui/zenoedit/nodesview/zenographseditor.cpp index bb4cbf1bcf..9f7b03ce8b 100644 --- a/ui/zenoedit/nodesview/zenographseditor.cpp +++ b/ui/zenoedit/nodesview/zenographseditor.cpp @@ -159,7 +159,7 @@ void ZenoGraphsEditor::resetModel(IGraphsModel* pModel) m_ui->subnetList->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(m_ui->subnetTree->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ZenoGraphsEditor::onTreeItemSelectionChanged); - SubListSortProxyModel* proxyModel = new SubListSortProxyModel(this); + SubListSortProxyModel* proxyModel = new SubListSortProxyModel(this); proxyModel->setSourceModel(pModel); proxyModel->setDynamicSortFilter(true); m_ui->subnetList->setModel(proxyModel); @@ -184,8 +184,15 @@ void ZenoGraphsEditor::resetModel(IGraphsModel* pModel) connect(pModel, SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)), this, SLOT(onSubGraphsToRemove(const QModelIndex&, int, int))); connect(pModel, SIGNAL(modelReset()), this, SLOT(onModelReset())); connect(pModel, SIGNAL(graphRenamed(const QString&, const QString&)), this, SLOT(onSubGraphRename(const QString&, const QString&))); - - activateTab("main"); + connect(&ZenoSettingsManager::GetInstance(), &ZenoSettingsManager::valueChanged, this, [=](QString zsName) { + if (zsName == zsSubgraphType) + { + proxyModel->invalidate(); + int type = ZenoSettingsManager::GetInstance().getValue(zsName).toInt(); + m_ui->label->setText(type == SUBGRAPH_TYPE::SUBGRAPH_NOR ? tr("Subnet") : type == SUBGRAPH_TYPE::SUBGRAPH_METERIAL ? tr("Material Subnet") : tr("Preset Subnet")); + } + }); + activateTab("main"); } void ZenoGraphsEditor::onModelCleared() @@ -346,12 +353,14 @@ void ZenoGraphsEditor::onSubnetOptionClicked() QAction* pSubnetMap = new QAction(tr("subnet map")); QAction* pImpFromFile = new QAction(tr("import from local file")); QAction* pImpFromSys = new QAction(tr("import system subnet")); + QAction* pImpFromPreset = new QAction(tr("import preset subnet")); pOptionsMenu->addAction(pNewSubg); pOptionsMenu->addAction(pSubnetMap); pOptionsMenu->addSeparator(); pOptionsMenu->addAction(pImpFromFile); pOptionsMenu->addAction(pImpFromSys); + pOptionsMenu->addAction(pImpFromPreset); connect(pNewSubg, &QAction::triggered, this, &ZenoGraphsEditor::onNewSubgraph); connect(pSubnetMap, &QAction::triggered, this, [=]() { @@ -363,6 +372,9 @@ void ZenoGraphsEditor::onSubnetOptionClicked() connect(pImpFromSys, &QAction::triggered, this, [=]() { }); + connect(pImpFromPreset, &QAction::triggered, this, [=]() { + m_mainWin->importGraph(true); + }); pOptionsMenu->exec(QCursor::pos()); pOptionsMenu->deleteLater(); diff --git a/ui/zenoedit/nodesview/zsubnetlistitemdelegate.cpp b/ui/zenoedit/nodesview/zsubnetlistitemdelegate.cpp index 7ed898fcc5..c7e16aeb29 100644 --- a/ui/zenoedit/nodesview/zsubnetlistitemdelegate.cpp +++ b/ui/zenoedit/nodesview/zsubnetlistitemdelegate.cpp @@ -8,6 +8,7 @@ #include #include "zenoapplication.h" #include "zenomainwindow.h" +#include "settings/zenosettingsmanager.h" SubgEditValidator::SubgEditValidator(QObject* parent) { @@ -281,4 +282,14 @@ bool SubListSortProxyModel::lessThan(const QModelIndex& source_left, const QMode if (source_left.data().toString().compare(source_right.data().toString(), Qt::CaseInsensitive) < 0) return true; return false; -} \ No newline at end of file +} + +bool SubListSortProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const +{ + const QModelIndex& index = sourceModel()->index(source_row, 0, source_parent); + if (!index.isValid()) + return false; + int value = index.data(ROLE_SUBGRAPH_TYPE).toInt(); + int type = ZenoSettingsManager::GetInstance().getValue(zsSubgraphType).toInt(); + return type == value ? true : false; +} diff --git a/ui/zenoedit/nodesview/zsubnetlistitemdelegate.h b/ui/zenoedit/nodesview/zsubnetlistitemdelegate.h index 8bedadb139..aefe5e234e 100644 --- a/ui/zenoedit/nodesview/zsubnetlistitemdelegate.h +++ b/ui/zenoedit/nodesview/zsubnetlistitemdelegate.h @@ -58,6 +58,7 @@ class SubListSortProxyModel :public QSortFilterProxyModel explicit SubListSortProxyModel(QObject* parent = nullptr); protected: bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; }; #endif diff --git a/ui/zenoedit/nodesys/zenonode.cpp b/ui/zenoedit/nodesys/zenonode.cpp index 90e413db9e..0fb419e4f8 100644 --- a/ui/zenoedit/nodesys/zenonode.cpp +++ b/ui/zenoedit/nodesys/zenonode.cpp @@ -1608,6 +1608,23 @@ void ZenoNode::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) nodeMenu->exec(QCursor::pos()); nodeMenu->deleteLater(); } + else if (m_index.data(ROLE_OBJNAME).toString() == "BindMaterial") + { + QAction* newSubGraph = new QAction(tr("Create Material Subgraph")); + connect(newSubGraph, &QAction::triggered, this, [=]() { + NodeParamModel* pNodeParams = QVariantPtr::asPtr(m_index.data(ROLE_NODE_PARAMS)); + ZASSERT_EXIT(pNodeParams); + const auto& paramIdx = pNodeParams->getParam(PARAM_INPUT, "mtlid"); + ZASSERT_EXIT(paramIdx.isValid()); + QString mtlid = paramIdx.data(ROLE_PARAM_VALUE).toString(); + if (!pGraphsModel->newMaterialSubgraph(mtlid, this->pos() + QPointF(800, 0))) + QMessageBox::warning(nullptr, tr("Info"), tr("Create material subgraph '%1' failed.").arg(mtlid)); + }); + QMenu *nodeMenu = new QMenu; + nodeMenu->addAction(newSubGraph); + nodeMenu->exec(QCursor::pos()); + nodeMenu->deleteLater(); + } else { NODE_CATES cates = pGraphsModel->getCates(); diff --git a/ui/zenoedit/nodesys/zenosearchbar.cpp b/ui/zenoedit/nodesys/zenosearchbar.cpp index 41d3129c56..edb1c4ffa2 100644 --- a/ui/zenoedit/nodesys/zenosearchbar.cpp +++ b/ui/zenoedit/nodesys/zenosearchbar.cpp @@ -86,7 +86,8 @@ void ZenoSearchBar::onSearchExec(const QString& content) void ZenoSearchBar::onSearchForward() { - m_idx = qMin(m_idx + 1, m_results.size() - 1); + if (++m_idx == m_results.size()) + m_idx = 0; if (!m_results.isEmpty() && m_idx < m_results.size()) { SEARCH_RECORD rec = _getRecord(); @@ -96,7 +97,9 @@ void ZenoSearchBar::onSearchForward() void ZenoSearchBar::onSearchBackward() { - m_idx = qMax(0, m_idx - 1); + if (--m_idx < 0) + m_idx = m_results.size() - 1; + if (!m_results.isEmpty() && m_idx < m_results.size()) { SEARCH_RECORD rec = _getRecord(); diff --git a/ui/zenoedit/panel/zenospreadsheet.cpp b/ui/zenoedit/panel/zenospreadsheet.cpp index ba64972a01..6aa23b485d 100644 --- a/ui/zenoedit/panel/zenospreadsheet.cpp +++ b/ui/zenoedit/panel/zenospreadsheet.cpp @@ -13,7 +13,9 @@ #include "zenomainwindow.h" #include "viewport/viewportwidget.h" #include "viewport/displaywidget.h" - +#include "dialog/zforksubgrapdlg.h" +#include "nodesview/zenographseditor.h" +#include "settings/zenosettingsmanager.h" ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { dataModel = new PrimAttrTableModel(); @@ -57,11 +59,12 @@ ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { auto sortModel = new QSortFilterProxyModel(this); sortModel->setSourceModel(dataModel); - QTableView *prim_attr_view = new QTableView(); + prim_attr_view = new QTableView(); prim_attr_view->setAlternatingRowColors(true); prim_attr_view->setSortingEnabled(true); prim_attr_view->setProperty("cssClass", "proppanel"); prim_attr_view->setModel(sortModel); + prim_attr_view->installEventFilter(this); pMainLayout->addWidget(prim_attr_view); // pStatusBar->setAlignment(Qt::AlignRight); @@ -107,10 +110,36 @@ ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { // do not select all when clicked cornerBtn->disconnect(); // reset sort order - connect(cornerBtn, &QAbstractButton::clicked, this, [sortModel, prim_attr_view]() { + connect(cornerBtn, &QAbstractButton::clicked, this, [&]() { sortModel->sort(-1); prim_attr_view->horizontalHeader()->setSortIndicator(-1, Qt::SortOrder::AscendingOrder); }); + + connect(prim_attr_view, &QTableView::doubleClicked, this, [=](const QModelIndex& index) { + int type = ZenoSettingsManager::GetInstance().getValue(zsSubgraphType).toInt(); + QString label = prim_attr_view->model()->headerData(index.row(), Qt::Vertical).toString(); + if (type == SUBGRAPH_METERIAL && label.contains("Material", Qt::CaseInsensitive)) + { + QString mtlid = index.data(Qt::DisplayRole).toString(); + IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + if (pGraphsModel) + { + for (const auto& subgIdx : pGraphsModel->subgraphsIndice(SUBGRAPH_METERIAL)) + { + if (subgIdx.data(ROLE_MTLID).toString() == mtlid) + { + QString subgraph_name = subgIdx.data(ROLE_OBJNAME).toString(); + ZenoMainWindow* pWin = zenoApp->getMainWindow(); + if (pWin) { + ZenoGraphsEditor* pEditor = pWin->getAnyEditor(); + if (pEditor) + pEditor->activateTab(subgraph_name, "", ""); + } + } + } + } + } + }); } void ZenoSpreadsheet::clear() { @@ -167,3 +196,92 @@ void ZenoSpreadsheet::setPrim(std::string primid) { } } + +bool ZenoSpreadsheet::eventFilter(QObject* watched, QEvent* event) +{ + if (watched == prim_attr_view && event->type() == QEvent::ContextMenu) + { + QStringList matLst; + if (QItemSelectionModel* pSelectionModel = prim_attr_view->selectionModel()) + { + const QModelIndexList& lst = pSelectionModel->selectedRows(); + for (auto index : lst) + { + int row = index.row(); + QString label = prim_attr_view->model()->headerData(row, Qt::Vertical).toString(); + if (label.contains("Material", Qt::CaseInsensitive)) + { + QString mtlid = index.data(Qt::DisplayRole).toString(); + matLst << mtlid; + } + } + } + if (!matLst.isEmpty()) + { + QMenu* pMenu = new QMenu; + QAction* newSubGraph = new QAction(tr("Create Material Subgraph")); + pMenu->addAction(newSubGraph); + QAction* newMatSubGraph = new QAction(tr("Fork Preset Material Subgraphs")); + pMenu->addAction(newMatSubGraph); + QMenu* pPresetMenu = new QMenu(tr("Preset Material Subgraph"), pMenu); + pMenu->addMenu(pPresetMenu); + IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + for (const auto& subgIdx : pGraphsModel->subgraphsIndice(SUBGRAPH_PRESET)) + { + QString name = subgIdx.data(ROLE_OBJNAME).toString(); + QAction* pAction = new QAction(name); + pPresetMenu->addAction(pAction); + connect(pAction, &QAction::triggered, this, [=]() { + QMap map; + for (const auto& mat : matLst) + { + map[mat] = pAction->text(); + } + + ZForkSubgraphDlg dlg(map, this); + dlg.exec(); + }); + } + + connect(newSubGraph, &QAction::triggered, this, [=]() { + for (const auto& mtlid : matLst) + { + if (!pGraphsModel->newMaterialSubgraph(mtlid, QPointF(800, 0))) + QMessageBox::warning(nullptr, tr("Info"), tr("Create material subgraph '%1' failed.").arg(mtlid)); + } + }); + connect(newMatSubGraph, &QAction::triggered, this, [=]() { + QMap map; + for (const auto& mtlid : matLst) + { + if (mtlid.contains("Cloth", Qt::CaseInsensitive)) + { + map[mtlid] = "ClothTypeMat"; + } + else if (mtlid.contains("Hair", Qt::CaseInsensitive) || mtlid.contains("Eyelash", Qt::CaseInsensitive)) + { + map[mtlid] = "OpacityTypeMat"; + } + else if (mtlid.contains("Arm", Qt::CaseInsensitive) || mtlid.contains("Torso", Qt::CaseInsensitive) + || mtlid.contains("Eyeball", Qt::CaseInsensitive)|| mtlid.contains("Head", Qt::CaseInsensitive) + || mtlid.contains("Leg", Qt::CaseInsensitive) || mtlid.contains("Teeth", Qt::CaseInsensitive) + || mtlid.contains("Tongue", Qt::CaseInsensitive)) + { + map[mtlid] = "SkinTypeMat"; + } + else if (mtlid.contains("EyeAO", Qt::CaseInsensitive) || mtlid.contains("Tearline", Qt::CaseInsensitive)) + { + map[mtlid] = "TransmitTypeMat"; + } + } + ZForkSubgraphDlg dlg(map, this); + dlg.exec(); + }); + + pMenu->exec(QCursor::pos()); + pMenu->deleteLater(); + } + } + return QWidget::eventFilter(watched, event); +} + diff --git a/ui/zenoedit/panel/zenospreadsheet.h b/ui/zenoedit/panel/zenospreadsheet.h index b74bf6080c..e3d999f681 100644 --- a/ui/zenoedit/panel/zenospreadsheet.h +++ b/ui/zenoedit/panel/zenospreadsheet.h @@ -8,21 +8,24 @@ #include #include "PrimAttrTableModel.h" - class ZenoSpreadsheet : public QWidget { Q_OBJECT QLabel* pStatusBar = new QLabel(); QLabel* pPrimName = new QLabel(); - public: ZenoSpreadsheet(QWidget* parent = nullptr); PrimAttrTableModel *dataModel = nullptr; void clear(); void setPrim(std::string primid); +protected: + bool eventFilter(QObject* watched, QEvent* event) override; +private: + QTableView* prim_attr_view; }; + #endif //ZENO_ZENOSPREADSHEET_H diff --git a/ui/zenoedit/settings/zenosettingsmanager.cpp b/ui/zenoedit/settings/zenosettingsmanager.cpp index 3c50b02498..41aeadcabd 100644 --- a/ui/zenoedit/settings/zenosettingsmanager.cpp +++ b/ui/zenoedit/settings/zenosettingsmanager.cpp @@ -19,10 +19,17 @@ ZenoSettingsManager::ZenoSettingsManager(QObject *parent) : setValue(zsShowGrid, true); } initShortCutInfos(); + m_settings[zsSubgraphType] = 0; } bool ZenoSettingsManager::setValue(const QString& name, const QVariant& value) { + if (zsSubgraphType == name) + { + m_settings[name] = value; + emit valueChanged(name); + return true; + } QSettings settings(zsCompanyName, zsEditor); QVariant oldValue = settings.value(name); if (oldValue != value) @@ -41,6 +48,8 @@ QVariant ZenoSettingsManager::getValue(const QString& zsName) const return QVariant::fromValue(m_shortCutInfos); else if (zsName == zsShortCutStyle) return m_shortCutStyle; + else if (zsName == zsSubgraphType) + return m_settings[zsName]; QSettings settings(zsCompanyName, zsEditor); QVariant val = settings.value(zsName); diff --git a/ui/zenoedit/settings/zenosettingsmanager.h b/ui/zenoedit/settings/zenosettingsmanager.h index aa10d7067f..bbc8764ca4 100644 --- a/ui/zenoedit/settings/zenosettingsmanager.h +++ b/ui/zenoedit/settings/zenosettingsmanager.h @@ -45,6 +45,7 @@ class ZenoSettingsManager : public QObject ZenoSettingsManager(QObject *parent = nullptr); QVector m_shortCutInfos; int m_shortCutStyle; + QHash m_settings; }; diff --git a/ui/zenoedit/settings/zsettings.h b/ui/zenoedit/settings/zsettings.h index 5780e279f1..6eb192a09d 100644 --- a/ui/zenoedit/settings/zsettings.h +++ b/ui/zenoedit/settings/zsettings.h @@ -18,6 +18,7 @@ const char* const zsCacheDir= "zencachedir"; const char* const zsCacheNum = "zencachenum"; const char* const zsCacheAutoClean = "zencache-autoclean"; const char* const zsEnableShiftChangeFOV = "viewport-EnableShiftChangeFOV"; +const char* const zsSubgraphType = "SubgraphType"; //short cut const char *const ShortCut_Save = "Save"; diff --git a/ui/zenoedit/viewport/cameracontrol.cpp b/ui/zenoedit/viewport/cameracontrol.cpp index 46355c58b0..d68f931eb8 100644 --- a/ui/zenoedit/viewport/cameracontrol.cpp +++ b/ui/zenoedit/viewport/cameracontrol.cpp @@ -419,15 +419,37 @@ void CameraControl::fakeMouseDoubleClickEvent(QMouseEvent *event) auto picked_prim = m_picker->just_pick_prim(pos.x(), pos.y()); if (!picked_prim.empty()) { auto primList = scene->objectsMan->pairs(); + QString mtlid; for (auto const &[key, ptr]: primList) { if (picked_prim == key) { auto &ud = ptr->userData(); + mtlid = QString::fromStdString(ud.get2("mtlid", "")); std::cout<<"selected MatId: "<("mtlid", "Default")<<"\n"; } } - auto obj_node_location = zeno::NodeSyncMgr::GetInstance().searchNodeOfPrim(picked_prim); - auto subgraph_name = obj_node_location->subgraph.data(ROLE_OBJNAME).toString(); - auto obj_node_name = obj_node_location->node.data(ROLE_OBJID).toString(); + + QString subgraph_name; + QString obj_node_name; + int type = ZenoSettingsManager::GetInstance().getValue(zsSubgraphType).toInt(); + if (type == SUBGRAPH_TYPE::SUBGRAPH_METERIAL && !mtlid.isEmpty()) + { + auto graphsMgm = zenoApp->graphsManagment(); + IGraphsModel* pModel = graphsMgm->currentModel(); + + const auto& lst = pModel->subgraphsIndice(SUBGRAPH_METERIAL); + for (const auto& index : lst) + { + if (index.data(ROLE_MTLID).toString() == mtlid) + subgraph_name = index.data(ROLE_OBJNAME).toString(); + } + } + if (subgraph_name.isEmpty()) + { + auto obj_node_location = zeno::NodeSyncMgr::GetInstance().searchNodeOfPrim(picked_prim); + subgraph_name = obj_node_location->subgraph.data(ROLE_OBJNAME).toString(); + obj_node_name = obj_node_location->node.data(ROLE_OBJID).toString(); + } + ZenoMainWindow *pWin = zenoApp->getMainWindow(); if (pWin) { ZenoGraphsEditor *pEditor = pWin->getAnyEditor(); diff --git a/ui/zenoedit/zenomainwindow.cpp b/ui/zenoedit/zenomainwindow.cpp index c79b5c507a..4b5b080f85 100644 --- a/ui/zenoedit/zenomainwindow.cpp +++ b/ui/zenoedit/zenomainwindow.cpp @@ -1515,7 +1515,7 @@ void ZenoMainWindow::onCheckUpdate() #endif } -void ZenoMainWindow::importGraph() { +void ZenoMainWindow::importGraph(bool bPreset) { QString filePath = getOpenFileByDialog(); if (filePath.isEmpty()) return; @@ -1585,6 +1585,22 @@ void ZenoMainWindow::importGraph() { } if (!subgraphNames.isEmpty()) pGraphs->importSubGraphs(filePath, subgraphNames); + if (bPreset) + { + for (const auto& name : subgraphNames) + { + QModelIndex index = pGraphs->currentModel()->index(name); + if (index.isValid()) + { + pGraphs->currentModel()->setData(index, SUBGRAPH_PRESET, ROLE_SUBGRAPH_TYPE); + } + } + ZenoSettingsManager::GetInstance().setValue(zsSubgraphType, SUBGRAPH_PRESET); + } + else + { + ZenoSettingsManager::GetInstance().setValue(zsSubgraphType, SUBGRAPH_NOR); + } } static bool saveContent(const QString &strContent, QString filePath) { diff --git a/ui/zenoedit/zenomainwindow.h b/ui/zenoedit/zenomainwindow.h index dd419d5d2d..8148e6b8fb 100644 --- a/ui/zenoedit/zenomainwindow.h +++ b/ui/zenoedit/zenomainwindow.h @@ -151,7 +151,7 @@ public slots: void onMenuActionTriggered(bool bTriggered); void onSplitDock(bool); void onCloseDock(); - void importGraph(); + void importGraph(bool bPreset = false); void exportGraph(); void onNodesSelected(const QModelIndex& subgIdx, const QModelIndexList& nodes, bool select); void onPrimitiveSelected(const std::unordered_set& primids); diff --git a/ui/zenoio/acceptor/iacceptor.h b/ui/zenoio/acceptor/iacceptor.h index 04bd7a31d6..a2c3214f38 100644 --- a/ui/zenoio/acceptor/iacceptor.h +++ b/ui/zenoio/acceptor/iacceptor.h @@ -12,7 +12,7 @@ class IAcceptor { public: virtual bool setLegacyDescs(const rapidjson::Value& graphObj, const NODE_DESCS &legacyDescs) = 0; - virtual void BeginSubgraph(const QString& name) = 0; + virtual void BeginSubgraph(const QString& name, int type) = 0; virtual void EndSubgraph() = 0; virtual void EndGraphs() = 0; virtual bool setCurrentSubGraph(IGraphsModel* pModel, const QModelIndex& subgIdx) = 0; diff --git a/ui/zenoio/reader/zsgreader.cpp b/ui/zenoio/reader/zsgreader.cpp index 17e75e12b6..28056f36cb 100644 --- a/ui/zenoio/reader/zsgreader.cpp +++ b/ui/zenoio/reader/zsgreader.cpp @@ -185,7 +185,10 @@ bool ZsgReader::_parseSubGraph(const QString& name, const rapidjson::Value& subg return false; //todo: should consider descript info. some info of outsock without connection show in descript info. - pAcceptor->BeginSubgraph(name); + int type = SUBGRAPH_TYPE::SUBGRAPH_NOR; + if (subgraph.HasMember("type")) + type = subgraph["type"].GetInt(); + pAcceptor->BeginSubgraph(name, type); const auto& nodes = subgraph["nodes"]; if (nodes.IsNull()) diff --git a/ui/zenoio/writer/zsgwriter.cpp b/ui/zenoio/writer/zsgwriter.cpp index c73df4dca4..5e9b5eab6f 100644 --- a/ui/zenoio/writer/zsgwriter.cpp +++ b/ui/zenoio/writer/zsgwriter.cpp @@ -157,6 +157,9 @@ void ZsgWriter::_dumpSubGraph(IGraphsModel* pModel, const QModelIndex& subgIdx, return; { + int type = subgIdx.data(ROLE_SUBGRAPH_TYPE).toInt(); + writer.Key("type"); + writer.Int(type); writer.Key("nodes"); JsonObjBatch _batch(writer); diff --git a/ui/zenomodel/include/igraphsmodel.h b/ui/zenomodel/include/igraphsmodel.h index 3fa4737868..3ce6312731 100644 --- a/ui/zenomodel/include/igraphsmodel.h +++ b/ui/zenomodel/include/igraphsmodel.h @@ -56,7 +56,7 @@ class IGraphsModel : public QAbstractItemModel fork subnet node indexed by subnetNodeIdx under subgIdx. */ virtual QModelIndex fork(const QModelIndex& subgIdx, const QModelIndex& subnetNodeIdx) = 0; - + virtual QModelIndex forkMaterial(const QModelIndex& subnetNodeIdx, const QString& subgName, const QString& mtlid, const QString& mtlid_old) = 0; virtual void updateParamInfo(const QString& id, PARAM_UPDATE_INFO info, const QModelIndex& subGpIdx, bool enableTransaction = false) = 0; virtual void updateSocketDefl(const QString& id, PARAM_UPDATE_INFO info, const QModelIndex& subGpIdx, bool enableTransaction = false) = 0; @@ -75,18 +75,20 @@ class IGraphsModel : public QAbstractItemModel virtual void undo() = 0; virtual void redo() = 0; virtual void switchSubGraph(const QString& graphName) {} - virtual void newSubgraph(const QString& graphName) = 0; + virtual void newSubgraph(const QString& graphName, SUBGRAPH_TYPE type = SUBGRAPH_TYPE::SUBGRAPH_NOR) = 0; + virtual bool newMaterialSubgraph(const QString& graphName, const QPointF& pos) = 0; virtual void initMainGraph() = 0; virtual void renameSubGraph(const QString& oldName, const QString& newName) = 0; virtual bool isDirty() const = 0; virtual NODE_CATES getCates() = 0; virtual QModelIndexList searchInSubgraph(const QString& objName, const QModelIndex& idx) = 0; virtual QModelIndexList subgraphsIndice() const = 0; + virtual QModelIndexList subgraphsIndice(SUBGRAPH_TYPE type) const = 0; virtual QList search( const QString& content, int searchType, int searchOpts, - QVector vec = QVector()) = 0; + QVector vec = QVector()) const = 0; virtual void removeGraph(int idx) = 0; virtual QString fileName() const = 0; virtual QString filePath() const = 0; diff --git a/ui/zenomodel/include/modelrole.h b/ui/zenomodel/include/modelrole.h index f4f0748051..b29083206f 100644 --- a/ui/zenomodel/include/modelrole.h +++ b/ui/zenomodel/include/modelrole.h @@ -72,6 +72,9 @@ enum MODEL_ROLE ROLE_KEYFRAMES, ROLE_VPARAM_COMMAND, + + ROLE_SUBGRAPH_TYPE, + ROLE_MTLID }; enum LOG_ROLE @@ -85,4 +88,10 @@ enum LOG_ROLE ROLE_RANGE_LEN }; +enum SUBGRAPH_TYPE +{ + SUBGRAPH_NOR = 0, + SUBGRAPH_METERIAL, + SUBGRAPH_PRESET +}; #endif diff --git a/ui/zenomodel/src/graphsmodel.cpp b/ui/zenomodel/src/graphsmodel.cpp index b6514a6f03..a552a57f64 100644 --- a/ui/zenomodel/src/graphsmodel.cpp +++ b/ui/zenomodel/src/graphsmodel.cpp @@ -85,9 +85,10 @@ void GraphsModel::initMainGraph() SubGraphModel* subGraphModel = new SubGraphModel(this); subGraphModel->setName("main"); appendSubGraph(subGraphModel); + m_selection->setCurrentIndex(index(rowCount() - 1, 0), QItemSelectionModel::Current); } -void GraphsModel::newSubgraph(const QString &graphName) +void GraphsModel::newSubgraph(const QString &graphName, SUBGRAPH_TYPE type) { if (graphName.compare("main", Qt::CaseInsensitive) == 0) { @@ -112,12 +113,59 @@ void GraphsModel::newSubgraph(const QString &graphName) { SubGraphModel *subGraphModel = new SubGraphModel(this); subGraphModel->setName(graphName); + subGraphModel->setType(type); appendSubGraph(subGraphModel); m_selection->setCurrentIndex(index(rowCount() - 1, 0), QItemSelectionModel::Current); markDirty(); } } +bool GraphsModel::newMaterialSubgraph(const QString& graphName, const QPointF& pos) +{ + if (subGraph(graphName)) + { + zeno::log_warn("subgraph '{}' is existed.", graphName.toStdString()); + return false; + } + beginTransaction("extract a new graph"); + + int currentRow = m_selection->currentIndex().row(); + //first, new the target subgraph + newSubgraph(graphName, SUBGRAPH_TYPE::SUBGRAPH_METERIAL); + QModelIndex subgIdx = index(graphName); + + //add shader node + const QString& ident = NodesMgr::createNewNode(this, subgIdx, "ShaderFinalize", QPointF()); + auto nodeIdx = nodeIndex(ident); + //set mtlid value + NodeParamModel* nodeParams = QVariantPtr::asPtr(nodeIdx.data(ROLE_NODE_PARAMS)); + ZASSERT_EXIT(nodeParams, false); + QModelIndex paramIdx = nodeParams->getParam(PARAM_INPUT, "mtlid"); + ModelSetData(paramIdx, graphName, ROLE_PARAM_VALUE); + //add suboutput + const QString& outputIdent = NodesMgr::createNewNode(this, subgIdx, "SubOutput", QPointF(600, 0)); + auto outputIdx = nodeIndex(outputIdent); + NodeParamModel* outputNodeParams = QVariantPtr::asPtr(outputIdx.data(ROLE_NODE_PARAMS)); + ZASSERT_EXIT(outputNodeParams, false); + //add link + EdgeInfo link; + const auto &inParam = nodeParams->getParam(PARAM_OUTPUT, "mtl"); + const auto& outParam = outputNodeParams->getParam(PARAM_INPUT, "port"); + link.inSockPath = outParam.data(ROLE_OBJPATH).toString(); + link.outSockPath = inParam.data(ROLE_OBJPATH).toString(); + addLink(subgIdx, link, false); + //add material subgraph node + QModelIndex currentSubIdx = index(currentRow, 0); + const QString& subIdent = NodesMgr::createNewNode(this, currentSubIdx, graphName, pos); + auto subgNodeIdx = nodeIndex(subIdent); + QVariant newValue = OPT_VIEW; + ModelSetData(subgNodeIdx, newValue, ROLE_OPTIONS); + endTransaction(); + emit dataChanged(subgIdx, subgIdx); + m_selection->setCurrentIndex(currentSubIdx, QItemSelectionModel::Current); + return true; +} + void GraphsModel::renameSubGraph(const QString& oldName, const QString& newName) { if (oldName == newName || oldName.compare("main", Qt::CaseInsensitive) == 0) @@ -341,6 +389,21 @@ QVariant GraphsModel::data(const QModelIndex& index, int role) const const QString& subgName = m_row2Key[index.row()]; return subgName; } + case ROLE_SUBGRAPH_TYPE: + { + const QString& subgName = m_row2Key[index.row()]; + if (SubGraphModel* pSubgModel = subGraph(subgName)) + { + return pSubgModel->type(); + } + } + case ROLE_MTLID: + { + if (SubGraphModel* pSubgModel = subGraph(m_row2Key[index.row()]) ) + { + return pSubgModel->mtlid(); + } + } } return QVariant(); } @@ -375,6 +438,22 @@ bool GraphsModel::setData(const QModelIndex& index, const QVariant& value, int r } } } + else if (role == ROLE_SUBGRAPH_TYPE) + { + const QString& name = data(index, Qt::DisplayRole).toString(); + if (SubGraphModel* pModel = subGraph(name)) + { + pModel->setType((SUBGRAPH_TYPE)value.toInt()); + } + } + else if (role == ROLE_MTLID) + { + const QString& name = data(index, Qt::DisplayRole).toString(); + if (SubGraphModel* pModel = subGraph(name)) + { + pModel->setMtlid(value.toString()); + } + } return false; } @@ -774,9 +853,49 @@ QModelIndex GraphsModel::fork(const QModelIndex& subgIdx, const QModelIndex &sub pCurrentModel->appendItem(subnetData, false); QModelIndex newForkNodeIdx = pCurrentModel->index(subnetData[ROLE_OBJID].toString()); + m_selection->setCurrentIndex(subgIdx, QItemSelectionModel::Current); return newForkNodeIdx; } +QModelIndex GraphsModel::forkMaterial(const QModelIndex& subnetNodeIdx, const QString& subgName, const QString& mtlid, const QString& mtlid_old) +{ + if (subGraph(subgName)) + return QModelIndex(); + if (!subnetNodeIdx.isValid()) + return QModelIndex(); + QModelIndex index = fork(m_selection->currentIndex(), subnetNodeIdx); + ModelSetData(index, OPT_VIEW, ROLE_OPTIONS); + + QString name = index.data(ROLE_OBJNAME).toString(); + setData(this->index(name), subgName, Qt::EditRole); + subGraph(subgName)->setType(SUBGRAPH_METERIAL); + if (SubGraphModel* pSubgModel = subGraph(subgName)) + { + QVector vec; + vec << pSubgModel; + QList resLst = search("ShaderFinalize", SEARCH_NODECLS, SEARCH_MATCH_EXACTLY, vec); + if (resLst.size() == 1) + { + SEARCH_RESULT result = resLst.first(); + auto paramIdx = pSubgModel->nodeParamIndex(result.targetIdx, PARAM_INPUT, "mtlid"); + ModelSetData(paramIdx, mtlid, ROLE_PARAM_VALUE); + } + vec.clear(); + vec << currentGraph(); + resLst = search(mtlid_old, SEARCH_ARGS, SEARCH_MATCH_EXACTLY, vec); + for (const auto& res : resLst) + { + QPointF pos = res.targetIdx.data(ROLE_OBJPOS).toPointF(); + ModelSetData(index, pos + QPointF(800, 0), ROLE_OBJPOS); + auto paramIdx = currentGraph()->nodeParamIndex(res.targetIdx, PARAM_INPUT, "mtlid"); + ModelSetData(paramIdx, mtlid, ROLE_PARAM_VALUE); + } + } + QModelIndex subgIdx = this->index(subgName); + emit dataChanged(subgIdx, subgIdx); + return index; +} + NODE_DATA GraphsModel::_fork(const QString& forkSubgName) { SubGraphModel* pModel = subGraph(forkSubgName); @@ -856,6 +975,7 @@ NODE_DATA GraphsModel::_fork(const QString& forkSubgName) const QString& forkName = uniqueSubgraph(forkSubgName); SubGraphModel* pForkModel = new SubGraphModel(this); pForkModel->setName(forkName); + pForkModel->setType(pModel->type()); appendSubGraph(pForkModel); NODES_DATA newNodes; @@ -1899,6 +2019,19 @@ QModelIndexList GraphsModel::subgraphsIndice() const return persistentIndexList(); } +QModelIndexList GraphsModel::subgraphsIndice(SUBGRAPH_TYPE type) const +{ + QModelIndexList lst; + for (const auto& model : m_subGraphs) + { + if (model->type() == type) + { + lst << index(model->name()); + } + } + return lst; +} + LinkModel* GraphsModel::linkModel(const QModelIndex& subgIdx) const { const QString &subgName = subgIdx.data(ROLE_OBJNAME).toString(); @@ -2190,7 +2323,7 @@ void GraphsModel::onSubIOAddRemove(SubGraphModel* pSubModel, const QModelIndex& } } -QList GraphsModel::search(const QString& content, int searchType, int searchOpts, QVector vec) +QList GraphsModel::search(const QString& content, int searchType, int searchOpts, QVector vec) const { QList results; if (content.isEmpty()) diff --git a/ui/zenomodel/src/graphsmodel.h b/ui/zenomodel/src/graphsmodel.h index 37acc24352..cece0ea4d1 100644 --- a/ui/zenomodel/src/graphsmodel.h +++ b/ui/zenomodel/src/graphsmodel.h @@ -32,7 +32,8 @@ class GraphsModel : public IGraphsModel SubGraphModel *subGraph(int idx) const; SubGraphModel *currentGraph(); void switchSubGraph(const QString& graphName) override; - void newSubgraph(const QString& graphName) override; + void newSubgraph(const QString& graphName, SUBGRAPH_TYPE type = SUBGRAPH_TYPE::SUBGRAPH_NOR) override; + bool newMaterialSubgraph(const QString& graphName, const QPointF& pos) override; void initMainGraph() override; void renameSubGraph(const QString& oldName, const QString& newName) override; QItemSelectionModel* selectionModel() const; @@ -43,6 +44,7 @@ class GraphsModel : public IGraphsModel //NODE_DESC void appendSubGraph(SubGraphModel* pGraph); QModelIndex fork(const QModelIndex& subgIdx, const QModelIndex& subnetNodeIdx) override; + QModelIndex forkMaterial(const QModelIndex& subnetNodeIdx, const QString&subgName, const QString& mtlid, const QString& mtlid_old) override; void removeGraph(int idx) override; bool isDirty() const override; void markDirty() override; @@ -110,6 +112,7 @@ class GraphsModel : public IGraphsModel void redo() override; QModelIndexList searchInSubgraph(const QString& objName, const QModelIndex& subgIdx) override; QModelIndexList subgraphsIndice() const override; + QModelIndexList subgraphsIndice(SUBGRAPH_TYPE type) const; LinkModel* linkModel(const QModelIndex& subgIdx) const override; LinkModel* legacyLinks(const QModelIndex& subgIdx) const override; QModelIndex getSubgraphIndex(const QModelIndex& linkIdx); @@ -118,7 +121,7 @@ class GraphsModel : public IGraphsModel const QString &content, int searchType, int searchOpts, - QVector vec = QVector()) override; + QVector vec = QVector()) const override; void collaspe(const QModelIndex& subgIdx) override; void expand(const QModelIndex& subgIdx) override; diff --git a/ui/zenomodel/src/modelacceptor.cpp b/ui/zenomodel/src/modelacceptor.cpp index a00326e14c..a0b8b64a2a 100644 --- a/ui/zenomodel/src/modelacceptor.cpp +++ b/ui/zenomodel/src/modelacceptor.cpp @@ -111,7 +111,7 @@ void ModelAcceptor::setUserDataInfo(const USERDATA_SETTING& info) m_userdatInfo = info; } -void ModelAcceptor::BeginSubgraph(const QString& name) +void ModelAcceptor::BeginSubgraph(const QString& name, int type) { if (m_bImport && name == "main") { @@ -136,6 +136,7 @@ void ModelAcceptor::BeginSubgraph(const QString& name) { pSubModel = new SubGraphModel(m_pModel); pSubModel->setName(name); + pSubModel->setType((SUBGRAPH_TYPE)type); m_pModel->appendSubGraph(pSubModel); } m_currentGraph = pSubModel; diff --git a/ui/zenomodel/src/modelacceptor.h b/ui/zenomodel/src/modelacceptor.h index 2eb2ba36db..b44274ae67 100644 --- a/ui/zenomodel/src/modelacceptor.h +++ b/ui/zenomodel/src/modelacceptor.h @@ -15,7 +15,7 @@ class ModelAcceptor : public IAcceptor //IAcceptor bool setLegacyDescs(const rapidjson::Value& graphObj, const NODE_DESCS& nodesParams) override; - void BeginSubgraph(const QString& name) override; + void BeginSubgraph(const QString& name, int type) override; bool setCurrentSubGraph(IGraphsModel* pModel, const QModelIndex& subgIdx) override; void EndSubgraph() override; void EndGraphs() override; diff --git a/ui/zenomodel/src/nodeparammodel.cpp b/ui/zenomodel/src/nodeparammodel.cpp index dffe5917ae..4fe719565b 100644 --- a/ui/zenomodel/src/nodeparammodel.cpp +++ b/ui/zenomodel/src/nodeparammodel.cpp @@ -1266,6 +1266,11 @@ void NodeParamModel::onSubIOEdited(const QVariant& oldValue, const VParamItem* p } } } + else if (nodeName == "ShaderFinalize" && pItem->m_name == "mtlid") + { + QModelIndex subgIdx = m_nodeIdx.data(ROLE_SUBGRAPH_IDX).toModelIndex(); + m_pGraphsModel->setData(subgIdx, pItem->data(ROLE_PARAM_VALUE), ROLE_MTLID); + } } void NodeParamModel::onLinkAdded(VParamItem* pItem) diff --git a/ui/zenomodel/src/subgraphmodel.cpp b/ui/zenomodel/src/subgraphmodel.cpp index b735ad3ff6..d1df94d5ce 100644 --- a/ui/zenomodel/src/subgraphmodel.cpp +++ b/ui/zenomodel/src/subgraphmodel.cpp @@ -14,6 +14,7 @@ SubGraphModel::SubGraphModel(GraphsModel* pGraphsModel, QObject *parent) : QAbstractItemModel(pGraphsModel) , m_pGraphsModel(pGraphsModel) , m_stack(new QUndoStack(this)) + , m_type(SUBGRAPH_TYPE::SUBGRAPH_NOR) { connect(this, &QAbstractItemModel::dataChanged, m_pGraphsModel, &GraphsModel::on_subg_dataChanged); connect(this, &QAbstractItemModel::rowsAboutToBeInserted, m_pGraphsModel, &GraphsModel::on_subg_rowsAboutToBeInserted); @@ -34,6 +35,7 @@ SubGraphModel::SubGraphModel(const SubGraphModel &rhs) , m_rect(rhs.m_rect) , m_name(rhs.m_name) , m_nodes(rhs.m_nodes) + , m_type(SUBGRAPH_TYPE::SUBGRAPH_NOR) { } @@ -888,6 +890,37 @@ QString SubGraphModel::name() const return m_name; } +SUBGRAPH_TYPE SubGraphModel::type() const +{ + return m_type; +} +void SubGraphModel::setType(SUBGRAPH_TYPE type) +{ + m_type = type; +} + +void SubGraphModel::setMtlid(const QString& mtlid) +{ + m_mtlid = mtlid; +} + +QString SubGraphModel::mtlid() +{ + if (m_type == SUBGRAPH_METERIAL && m_mtlid.isEmpty()) + { + QVector vec; + vec << this; + QList resLst = m_pGraphsModel->search("ShaderFinalize", SEARCH_NODECLS, SEARCH_MATCH_EXACTLY, vec); + if (resLst.size() == 1) + { + SEARCH_RESULT result = resLst.first(); + auto paramIdx = nodeParamIndex(result.targetIdx, PARAM_INPUT, "mtlid"); + if (paramIdx.isValid()) + m_mtlid = paramIdx.data(ROLE_PARAM_VALUE).toString(); + } + } + return m_mtlid; +} void SubGraphModel::replaceSubGraphNode(const QString& oldName, const QString& newName) { auto iter = m_name2identLst.find(oldName); diff --git a/ui/zenomodel/src/subgraphmodel.h b/ui/zenomodel/src/subgraphmodel.h index 71fc4f7262..f89c8b037b 100644 --- a/ui/zenomodel/src/subgraphmodel.h +++ b/ui/zenomodel/src/subgraphmodel.h @@ -106,6 +106,11 @@ class SubGraphModel : public QAbstractItemModel QString name() const; void setName(const QString& name); + SUBGRAPH_TYPE type() const; + void setType(SUBGRAPH_TYPE type); + void setMtlid(const QString& mtlid); + QString mtlid(); + void replaceSubGraphNode(const QString& oldName, const QString& newName); void setViewRect(const QRectF& rc); QRectF viewRect() const { return m_rect; } @@ -140,6 +145,8 @@ public slots: void _uniqueView(const QModelIndex& index, bool bInSocket, bool bOutSocket, QModelIndexList& viewLst); QString m_name; + SUBGRAPH_TYPE m_type; + QString m_mtlid; QHash m_key2Row; QHash m_row2Key; QHash m_nodes; diff --git a/ui/zenoui/comctrl/gv/zgraphicsnetlabel.cpp b/ui/zenoui/comctrl/gv/zgraphicsnetlabel.cpp index dc17200488..d1029e28b6 100644 --- a/ui/zenoui/comctrl/gv/zgraphicsnetlabel.cpp +++ b/ui/zenoui/comctrl/gv/zgraphicsnetlabel.cpp @@ -56,6 +56,11 @@ void ZGraphicsNetLabel::SetTextInteraction(bool on, bool selectAll) void ZGraphicsNetLabel::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { +#ifdef ZENO_NODESVIEW_OPTIM + if (editor_factor < 0.1) { + return; + } +#endif QStyleOptionGraphicsItem myOption(*option); myOption.state &= ~QStyle::State_Selected; myOption.state &= ~QStyle::State_HasFocus; From f281c016a97f9ea49c9a4dd80c90b382dd2e2af0 Mon Sep 17 00:00:00 2001 From: Lu Shuliang Date: Mon, 11 Dec 2023 00:57:35 +0800 Subject: [PATCH 011/106] better PrimAttr float2int and int2float --- zeno/src/nodes/neo/PrimAttrOps.cpp | 134 ++++++++++++++++++++++------- 1 file changed, 105 insertions(+), 29 deletions(-) diff --git a/zeno/src/nodes/neo/PrimAttrOps.cpp b/zeno/src/nodes/neo/PrimAttrOps.cpp index 3474663b00..5b9d81573d 100644 --- a/zeno/src/nodes/neo/PrimAttrOps.cpp +++ b/zeno/src/nodes/neo/PrimAttrOps.cpp @@ -73,20 +73,56 @@ struct PrimFloatAttrToInt : INode { auto prim = get_input("prim"); auto attr = get_input2("attr"); auto attrOut = get_input2("attrOut"); - auto &inArr = prim->verts.attr(attr); - auto factor = get_input2("divisor"); - if (attrOut == attr) { - std::vector outArr(inArr.size()); - parallel_for(inArr.size(), [&] (size_t i) { - outArr[i] = std::rint(inArr[i] * factor); - }); - prim->verts.attrs.erase(attrOut); - prim->verts.add_attr(attrOut) = std::move(outArr); - } else { - auto &outArr = prim->verts.add_attr(attrOut); - parallel_for(inArr.size(), [&] (size_t i) { - outArr[i] = std::rint(inArr[i] * factor); - }); + if(prim->verts.has_attr(attr)){ + auto &inArr = prim->verts.attr(attr); + auto factor = get_input2("divisor"); + if (attrOut == attr) { + std::vector outArr(inArr.size()); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = std::rint(inArr[i] * factor); + }); + prim->verts.attrs.erase(attrOut); + prim->verts.add_attr(attrOut) = std::move(outArr); + } else { + auto &outArr = prim->verts.add_attr(attrOut); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = std::rint(inArr[i] * factor); + }); + } + } + if(prim->tris.has_attr(attr)){ + auto &inArr = prim->tris.attr(attr); + auto factor = get_input2("divisor"); + if (attrOut == attr) { + std::vector outArr(inArr.size()); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = std::rint(inArr[i] * factor); + }); + prim->tris.attrs.erase(attrOut); + prim->tris.add_attr(attrOut) = std::move(outArr); + } else { + auto &outArr = prim->tris.add_attr(attrOut); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = std::rint(inArr[i] * factor); + }); + } + } + if(prim->polys.has_attr(attr)){ + auto &inArr = prim->polys.attr(attr); + auto factor = get_input2("divisor"); + if (attrOut == attr) { + std::vector outArr(inArr.size()); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = std::rint(inArr[i] * factor); + }); + prim->polys.attrs.erase(attrOut); + prim->polys.add_attr(attrOut) = std::move(outArr); + } else { + auto &outArr = prim->polys.add_attr(attrOut); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = std::rint(inArr[i] * factor); + }); + } } set_output("prim", std::move(prim)); } @@ -112,21 +148,61 @@ struct PrimIntAttrToFloat : INode { auto prim = get_input("prim"); auto attr = get_input2("attr"); auto attrOut = get_input2("attrOut"); - auto &inArr = prim->verts.attr(attr); - auto factor = get_input2("divisor"); - if (factor) factor = 1.0f / factor; - if (attrOut == attr) { - std::vector outArr(inArr.size()); - parallel_for(inArr.size(), [&] (size_t i) { - outArr[i] = float(inArr[i]) * factor; - }); - prim->verts.attrs.erase(attrOut); - prim->verts.add_attr(attrOut) = std::move(outArr); - } else { - auto &outArr = prim->verts.add_attr(attrOut); - parallel_for(inArr.size(), [&] (size_t i) { - outArr[i] = float(inArr[i]) * factor; - }); + + + if(prim->verts.has_attr(attr)){ + auto &inArr = prim->verts.attr(attr); + auto factor = get_input2("divisor"); + if (factor) factor = 1.0f / factor; + if (attrOut == attr) { + std::vector outArr(inArr.size()); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = float(inArr[i]) * factor; + }); + prim->verts.attrs.erase(attrOut); + prim->verts.add_attr(attrOut) = std::move(outArr); + } else { + auto &outArr = prim->verts.add_attr(attrOut); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = float(inArr[i]) * factor; + }); + } + } + if(prim->tris.has_attr(attr)){ + auto &inArr = prim->tris.attr(attr); + auto factor = get_input2("divisor"); + if (factor) factor = 1.0f / factor; + if (attrOut == attr) { + std::vector outArr(inArr.size()); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = float(inArr[i]) * factor; + }); + prim->tris.attrs.erase(attrOut); + prim->tris.add_attr(attrOut) = std::move(outArr); + } else { + auto &outArr = prim->tris.add_attr(attrOut); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = float(inArr[i]) * factor; + }); + } + } + if(prim->polys.has_attr(attr)){ + auto &inArr = prim->polys.attr(attr); + auto factor = get_input2("divisor"); + if (factor) factor = 1.0f / factor; + if (attrOut == attr) { + std::vector outArr(inArr.size()); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = float(inArr[i]) * factor; + }); + prim->polys.attrs.erase(attrOut); + prim->polys.add_attr(attrOut) = std::move(outArr); + } else { + auto &outArr = prim->polys.add_attr(attrOut); + parallel_for(inArr.size(), [&] (size_t i) { + outArr[i] = float(inArr[i]) * factor; + }); + } } set_output("prim", std::move(prim)); } From 2634f82998af239cf316b3394df7a76fbd9b97e1 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 04:00:42 +0800 Subject: [PATCH 012/106] write abc polys tris loops attr --- projects/Alembic/ReadAlembic.cpp | 20 +++-- projects/Alembic/WriteAlembic.cpp | 124 ++++++++++++++++++++++++++++-- 2 files changed, 131 insertions(+), 13 deletions(-) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index a4f49acf26..43d9b85a9d 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -80,21 +80,27 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp attr[i] = { data[ 3 * i], data[3 * i + 1], data[3 * i + 2]}; } } - else if (prim->loops.size() == data.size()) { - auto &attr = prim->loops.add_attr(p.getName()); - for (auto i = 0; i < prim->loops.size(); i++) { - attr[i] = data[i]; - } - } else if (prim->polys.size() == data.size()) { auto &attr = prim->polys.add_attr(p.getName()); for (auto i = 0; i < prim->polys.size(); i++) { attr[i] = data[i]; } } + else if (prim->polys.size() * 3 == data.size()) { + auto &attr = prim->polys.add_attr(p.getName()); + for (auto i = 0; i < prim->verts.size(); i++) { + attr[i] = { data[ 3 * i], data[3 * i + 1], data[3 * i + 2]}; + } + } + else if (prim->loops.size() == data.size()) { + auto &attr = prim->loops.add_attr(p.getName()); + for (auto i = 0; i < prim->loops.size(); i++) { + attr[i] = data[i]; + } + } else { if (!read_done) { - log_error("[alembic] can not load attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + log_error("[alembic] can not load float attr {}: {}. Check if link to Points channel when exported from Houdini.", p.getName(), data.size()); } } } diff --git a/projects/Alembic/WriteAlembic.cpp b/projects/Alembic/WriteAlembic.cpp index 7a72aed38b..83772c8e51 100644 --- a/projects/Alembic/WriteAlembic.cpp +++ b/projects/Alembic/WriteAlembic.cpp @@ -13,6 +13,7 @@ #include "zeno/utils/format.h" #include "zeno/utils/string.h" #include "zeno/types/ListObject.h" +#include "zeno/utils/log.h" #include #include @@ -203,10 +204,10 @@ ZENDEFNODE(WriteAlembic, { }); template -void write_attrs(std::map &attrs, std::string path, std::shared_ptr prim, T1& schema, T2& samp) { +void write_attrs(std::map &attrs, std::string path, std::shared_ptr prim, T1& schema, T2& samp) { OCompoundProperty arbAttrs = schema.getArbGeomParams(); prim->verts.foreach_attr([&](auto const &key, auto &arr) { - if (key == "v" || key == "nrm" || key == "faceset") { + if (key == "v" || key == "nrm") { return; } std::string full_key = path + '/' + key; @@ -223,16 +224,127 @@ void write_attrs(std::map &attrs, std::string path v[i * 3 + 2] = arr[i][2]; } samp.setVals(v); - attrs[full_key].set(samp); + std::any_cast(attrs[full_key]).set(samp); } else if constexpr (std::is_same_v) { if (attrs.count(full_key) == 0) { attrs[full_key] = OFloatGeomParam(arbAttrs.getPtr(), key, false, kVaryingScope, 1); } auto samp = OFloatGeomParam::Sample(); samp.setVals(arr); - attrs[full_key].set(samp); + std::any_cast(attrs[full_key]).set(samp); + } else if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OInt32GeomParam (arbAttrs.getPtr(), key, false, kVaryingScope, 1); + } + auto samp = OInt32GeomParam::Sample(); + samp.setVals(arr); + std::any_cast(attrs[full_key]).set(samp); } }); + if (prim->loops.size() > 0) { + prim->loops.foreach_attr([&](auto const &key, auto &arr) { + std::string full_key = path + '/' + key; + using T = std::decay_t; + if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OFloatGeomParam(arbAttrs.getPtr(), key, false, kFacevaryingScope, 3); + } + auto samp = OFloatGeomParam::Sample(); + std::vector v(arr.size() * 3); + for (auto i = 0; i < arr.size(); i++) { + v[i * 3 + 0] = arr[i][0]; + v[i * 3 + 1] = arr[i][1]; + v[i * 3 + 2] = arr[i][2]; + } + samp.setVals(v); + std::any_cast(attrs[full_key]).set(samp); + } else if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OFloatGeomParam(arbAttrs.getPtr(), key, false, kFacevaryingScope, 1); + } + auto samp = OFloatGeomParam::Sample(); + samp.setVals(arr); + std::any_cast(attrs[full_key]).set(samp); + } else if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OInt32GeomParam (arbAttrs.getPtr(), key, false, kFacevaryingScope, 1); + } + auto samp = OInt32GeomParam::Sample(); + samp.setVals(arr); + std::any_cast(attrs[full_key]).set(samp); + } + }); + } + if (prim->polys.size() > 0) { + prim->polys.foreach_attr([&](auto const &key, auto &arr) { + std::string full_key = path + '/' + key; + using T = std::decay_t; + if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OFloatGeomParam(arbAttrs.getPtr(), key, false, kUniformScope, 3); + } + auto samp = OFloatGeomParam::Sample(); + std::vector v(arr.size() * 3); + for (auto i = 0; i < arr.size(); i++) { + v[i * 3 + 0] = arr[i][0]; + v[i * 3 + 1] = arr[i][1]; + v[i * 3 + 2] = arr[i][2]; + } + samp.setVals(v); + std::any_cast(attrs[full_key]).set(samp); + } else if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OFloatGeomParam(arbAttrs.getPtr(), key, false, kUniformScope, 1); + } + auto samp = OFloatGeomParam::Sample(); + samp.setVals(arr); + std::any_cast(attrs[full_key]).set(samp); + } else if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OInt32GeomParam (arbAttrs.getPtr(), key, false, kUniformScope, 1); + } + auto samp = OInt32GeomParam::Sample(); + samp.setVals(arr); + std::any_cast(attrs[full_key]).set(samp); + } + }); + } + if (prim->tris.size() > 0) { + prim->tris.foreach_attr([&](auto const &key, auto &arr) { + zeno::log_info("{} {}", key, int(arr.size())); + std::string full_key = path + '/' + key; + using T = std::decay_t; + if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OFloatGeomParam(arbAttrs.getPtr(), key, false, kUniformScope, 3); + } + auto samp = OFloatGeomParam::Sample(); + std::vector v(arr.size() * 3); + for (auto i = 0; i < arr.size(); i++) { + v[i * 3 + 0] = arr[i][0]; + v[i * 3 + 1] = arr[i][1]; + v[i * 3 + 2] = arr[i][2]; + } + samp.setVals(v); + std::any_cast(attrs[full_key]).set(samp); + } else if constexpr (std::is_same_v) { + zeno::log_info("std::is_same_v"); + if (attrs.count(full_key) == 0) { + attrs[full_key] = OFloatGeomParam(arbAttrs.getPtr(), key, false, kUniformScope, 1); + } + auto samp = OFloatGeomParam::Sample(); + samp.setVals(arr); + std::any_cast(attrs[full_key]).set(samp); + } else if constexpr (std::is_same_v) { + if (attrs.count(full_key) == 0) { + attrs[full_key] = OInt32GeomParam (arbAttrs.getPtr(), key, false, kUniformScope, 1); + } + auto samp = OInt32GeomParam::Sample(); + samp.setVals(arr); + std::any_cast(attrs[full_key]).set(samp); + } + }); + } } void write_user_data(std::map &user_attrs, std::string path, std::shared_ptr prim, OCompoundProperty& user) { auto &ud = prim->userData(); @@ -308,7 +420,7 @@ struct WriteAlembic2 : INode { OPolyMesh meshyObj; OPoints pointsObj; std::string usedPath; - std::map attrs; + std::map attrs; std::map user_attrs; virtual void apply() override { @@ -557,7 +669,7 @@ struct WriteAlembicPrims : INode { std::string usedPath; std::map meshyObjs; std::map pointsObjs; - std::map attrs; + std::map attrs; std::map user_attrs; virtual void apply() override { From bad8e60daba5e1ec0f12bdc44ba818c5542e74bb Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 04:39:08 +0800 Subject: [PATCH 013/106] fix --- projects/Alembic/WriteAlembic.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/projects/Alembic/WriteAlembic.cpp b/projects/Alembic/WriteAlembic.cpp index 83772c8e51..ecd53dffd3 100644 --- a/projects/Alembic/WriteAlembic.cpp +++ b/projects/Alembic/WriteAlembic.cpp @@ -206,7 +206,7 @@ ZENDEFNODE(WriteAlembic, { template void write_attrs(std::map &attrs, std::string path, std::shared_ptr prim, T1& schema, T2& samp) { OCompoundProperty arbAttrs = schema.getArbGeomParams(); - prim->verts.foreach_attr([&](auto const &key, auto &arr) { + prim->verts.foreach_attr>([&](auto const &key, auto &arr) { if (key == "v" || key == "nrm") { return; } @@ -242,7 +242,7 @@ void write_attrs(std::map &attrs, std::string path, std:: } }); if (prim->loops.size() > 0) { - prim->loops.foreach_attr([&](auto const &key, auto &arr) { + prim->loops.foreach_attr>([&](auto const &key, auto &arr) { std::string full_key = path + '/' + key; using T = std::decay_t; if constexpr (std::is_same_v) { @@ -276,7 +276,7 @@ void write_attrs(std::map &attrs, std::string path, std:: }); } if (prim->polys.size() > 0) { - prim->polys.foreach_attr([&](auto const &key, auto &arr) { + prim->polys.foreach_attr>([&](auto const &key, auto &arr) { std::string full_key = path + '/' + key; using T = std::decay_t; if constexpr (std::is_same_v) { @@ -310,7 +310,7 @@ void write_attrs(std::map &attrs, std::string path, std:: }); } if (prim->tris.size() > 0) { - prim->tris.foreach_attr([&](auto const &key, auto &arr) { + prim->tris.foreach_attr>([&](auto const &key, auto &arr) { zeno::log_info("{} {}", key, int(arr.size())); std::string full_key = path + '/' + key; using T = std::decay_t; From 79fb7863f8631bb8e2e8a53b947a2f4eda67e2cf Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Mon, 11 Dec 2023 11:40:05 +0800 Subject: [PATCH 014/106] fix bug about preset material subgraphs --- ui/zenoedit/dialog/zforksubgraphdlg.cpp | 25 +++++++++++++++++++++---- ui/zenomodel/src/graphsmodel.cpp | 18 ++++++++++-------- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/ui/zenoedit/dialog/zforksubgraphdlg.cpp b/ui/zenoedit/dialog/zforksubgraphdlg.cpp index 5da0ec327e..52ff19dc5e 100644 --- a/ui/zenoedit/dialog/zforksubgraphdlg.cpp +++ b/ui/zenoedit/dialog/zforksubgraphdlg.cpp @@ -45,6 +45,7 @@ void ZForkSubgraphDlg::initUi() QTableWidgetItem* pMatItem = new QTableWidgetItem(subgraph); m_pTableWidget->setItem(row, 2, pMatItem); + pMatItem->setData(Qt::UserRole, subgraph); } pLayout->addWidget(m_pTableWidget); @@ -61,16 +62,32 @@ void ZForkSubgraphDlg::initUi() this->setMainWidget(pWidget); connect(pOkBtn, &QPushButton::clicked, this, [=]() { - for (int row = 0; row < m_pTableWidget->rowCount(); row++) + int count = m_pTableWidget->rowCount(); + int rowNum = qSqrt(count); + int colunmNum = count / (rowNum > 0 ? rowNum : 1); + QPointF pos; + for (int row = 0; row < count; row++) { QString subgName = m_pTableWidget->item(row, 0)->data(Qt::DisplayRole).toString(); QString name = m_pTableWidget->item(row, 1)->data(Qt::DisplayRole).toString(); QString mtlid = m_pTableWidget->item(row, 2)->data(Qt::DisplayRole).toString(); - IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); - const QModelIndex& index = pGraphsModel->forkMaterial(pGraphsModel->index(subgName), name, mtlid, m_subgsMap.key(subgName)); + QString old_mtlid = m_pTableWidget->item(row, 2)->data(Qt::UserRole).toString(); + IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + const QModelIndex& index = pGraphsModel->forkMaterial(pGraphsModel->index(subgName), name, mtlid, old_mtlid); if (!index.isValid()) { - QMessageBox::warning(this, tr("warring"), tr("fork preset subgraph '%1' failed.").arg(subgName)); + QMessageBox::warning(this, tr("warring"), tr("fork preset subgraph '%1' failed.").arg(name)); + } + if (row > 0) + { + int currC = row / rowNum; + int currR = row % rowNum; + QPointF newPos(pos.x() + currC * 600, pos.y() + currR * 600); + pGraphsModel->ModelSetData(index, newPos, ROLE_OBJPOS); + } + else + { + pos = index.data(ROLE_OBJPOS).toPointF(); } } accept(); diff --git a/ui/zenomodel/src/graphsmodel.cpp b/ui/zenomodel/src/graphsmodel.cpp index a552a57f64..4114b6c2b3 100644 --- a/ui/zenomodel/src/graphsmodel.cpp +++ b/ui/zenomodel/src/graphsmodel.cpp @@ -880,15 +880,17 @@ QModelIndex GraphsModel::forkMaterial(const QModelIndex& subnetNodeIdx, const QS auto paramIdx = pSubgModel->nodeParamIndex(result.targetIdx, PARAM_INPUT, "mtlid"); ModelSetData(paramIdx, mtlid, ROLE_PARAM_VALUE); } - vec.clear(); - vec << currentGraph(); - resLst = search(mtlid_old, SEARCH_ARGS, SEARCH_MATCH_EXACTLY, vec); - for (const auto& res : resLst) + //update mtlid of BindMeterial node + if (mtlid != mtlid_old) { - QPointF pos = res.targetIdx.data(ROLE_OBJPOS).toPointF(); - ModelSetData(index, pos + QPointF(800, 0), ROLE_OBJPOS); - auto paramIdx = currentGraph()->nodeParamIndex(res.targetIdx, PARAM_INPUT, "mtlid"); - ModelSetData(paramIdx, mtlid, ROLE_PARAM_VALUE); + vec.clear(); + vec << currentGraph(); + resLst = search(mtlid_old, SEARCH_ARGS, SEARCH_MATCH_EXACTLY, vec); + for (const auto& res : resLst) + { + auto paramIdx = currentGraph()->nodeParamIndex(res.targetIdx, PARAM_INPUT, "mtlid"); + ModelSetData(paramIdx, mtlid, ROLE_PARAM_VALUE); + } } } QModelIndex subgIdx = this->index(subgName); From f7f04b4ccef33a485fb79c7eb1ce751eb78251bc Mon Sep 17 00:00:00 2001 From: teachmain Date: Mon, 11 Dec 2023 13:43:17 +0800 Subject: [PATCH 015/106] update SmartTexture2D --- zeno/src/nodes/mtl/ShaderTexture.cpp | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/zeno/src/nodes/mtl/ShaderTexture.cpp b/zeno/src/nodes/mtl/ShaderTexture.cpp index fef215abfb..d377434c07 100644 --- a/zeno/src/nodes/mtl/ShaderTexture.cpp +++ b/zeno/src/nodes/mtl/ShaderTexture.cpp @@ -185,8 +185,33 @@ struct SmartTexture2D : ShaderNodeClone virtual void emitCode(EmissionPass *em) override { auto texId = em->tex2Ds.size(); auto tex = std::make_shared(); + auto texture_path = get_input2("path"); + if(!std::filesystem::exists(texture_path)){ + zeno::log_warn("texture file not found!"); + auto type = get_input2("type"); + auto number = get_input2("value"); + if (type == "float" || type == "R") + em->emitCode(zeno::format("{}",number[0])); + else if (type == "G") + em->emitCode(zeno::format("{}",number[1])); + else if (type == "B") + em->emitCode(zeno::format("{}",number[2])); + else if (type == "A") + em->emitCode(zeno::format("{}",number[3])); + else if (type == "vec2") + em->emitCode(zeno::format("vec2({},{})",number[0],number[1])); + else if (type == "vec3") + em->emitCode(zeno::format("vec3({},{},{})",number[0],number[1],number[2])); + else if (type == "vec4") + em->emitCode(zeno::format("vec3({},{},{},{})",number[0],number[1],number[2],number[4])); + else + throw zeno::Exception("ShaderTexture2D got bad type: " + type); + + return; + + } - tex->path = get_input2("path"); + tex->path = texture_path; if (has_input("heatmap")) { if (tex->path.empty()) { std::srand(std::time(0)); @@ -294,6 +319,7 @@ ZENDEFNODE(SmartTexture2D, { {(std::string) "enum " + SmartTexture2D::texFiltering, "magFilter", "LINEAR"}, {"coord"}, {"vec2f", "uvtiling", "1,1"}, + {"vec4f", "value", "0,0,0,0"}, {"enum float vec2 vec3 vec4 R G B A", "type", "vec3"}, {"enum raw srgb normal_map", "post_process", "raw"} }, From 18a64a4b13442571e69eeed34a1be53cdba1c405 Mon Sep 17 00:00:00 2001 From: littlemine Date: Mon, 11 Dec 2023 13:44:20 +0800 Subject: [PATCH 016/106] mark verts explicitly, rematch boundary uv --- projects/CUDA/utils/Primitives.cpp | 31 +++++++++++ projects/CUDA/zpc | 2 +- projects/ZenoFX/pnbvhw.cpp | 89 ++++++++++++++++++++++++++++++ 3 files changed, 121 insertions(+), 1 deletion(-) diff --git a/projects/CUDA/utils/Primitives.cpp b/projects/CUDA/utils/Primitives.cpp index c96d0a83a7..bb3beae1c6 100644 --- a/projects/CUDA/utils/Primitives.cpp +++ b/projects/CUDA/utils/Primitives.cpp @@ -1123,6 +1123,37 @@ ZENDEFNODE(PrimitiveUnfuse, { {"zs_geom"}, }); +struct MarkSelectedVerts : INode { + void apply() override { + auto prim = get_input("prim"); + auto tagStr = get_input2("selection_tag"); + auto markedLines = get_input("marked_lines"); + + auto &tags = prim->add_attr(tagStr); + using namespace zs; + auto pol = omp_exec(); + + std::fill(std::begin(tags), std::end(tags), 0.f); + const auto &lines = markedLines->lines.values; + pol(range(lines), [&tags](auto line) { + tags[line[0]] = 1.f; + tags[line[1]] = 1.f; + }); + set_output("prim", prim); + } +}; +ZENDEFNODE(MarkSelectedVerts, { + + {{"PrimitiveObject", "prim"}, + {"string", "selection_tag", "selected"}, + {"PrimitiveObject", "marked_lines"}}, + { + {"PrimitiveObject", "prim"}, + }, + {}, + {"zs_geom"}, + }); + struct ComputeAverageEdgeLength : INode { void apply() override { using namespace zs; diff --git a/projects/CUDA/zpc b/projects/CUDA/zpc index 04dede0afb..2cc395e980 160000 --- a/projects/CUDA/zpc +++ b/projects/CUDA/zpc @@ -1 +1 @@ -Subproject commit 04dede0afbc3daf74f7ea31113c096b3b7466ed9 +Subproject commit 2cc395e980c311bc2ef04322c915124127237810 diff --git a/projects/ZenoFX/pnbvhw.cpp b/projects/ZenoFX/pnbvhw.cpp index de59fbf26c..dc8726d585 100644 --- a/projects/ZenoFX/pnbvhw.cpp +++ b/projects/ZenoFX/pnbvhw.cpp @@ -532,6 +532,95 @@ ZENDEFNODE(QueryNearestPrimitiveWithUV, { {"zenofx"}, }); +struct RematchBestPrimitiveUV : zeno::INode { + virtual void apply() override { + using namespace zeno; + + auto lbvh = get_input("lbvh"); + if (lbvh->eleCategory != LBvh::element_e::tri) + throw std::runtime_error("lbvh used for RematchBestPrimitiveUV can only be built from triangle mesh"); + + using Ti = typename LBvh::Ti; + + auto prim = get_input("prim"); + auto tagStr = get_input2("selection_tag"); + auto &tags = prim->add_attr(tagStr); + { + if (!(prim->verts.has_attr("uv") && prim->polys.size() > 1)) + throw std::runtime_error("the input primitive is not a loop-based surface mesh with vertex uv!"); + + const auto &pos = prim->verts.values; + auto &uvs = prim->attr("uv"); + const auto &polys = prim->polys.values; + const auto &loops = prim->loops.values; + + /// @note in spatial distance + // auto threshold = get_input2("threshold"); + + auto bvhPrim = lbvh->primPtr.lock(); + if (!bvhPrim->verts.has_attr("uv")) + throw std::runtime_error("missing vertex property [uv] in the bvh-associated prim!"); + const auto &refUvs = bvhPrim->verts.attr("uv"); + const auto &refTris = bvhPrim->tris.values; + +#if 1 + std::vector targetVertUvs(pos.size()); +#if defined(_OPENMP) +#pragma omp parallel for schedule(guided, 4) +#endif + for (Ti ei = 0; ei < polys.size(); ++ei) { + auto poly = polys[ei]; + Ti st = poly[0]; + Ti ed = st + poly[1]; + vec3f uv{0, 0, 0}; + int cnt = 0; + for (; st != ed; ++st) { + auto i = loops[st]; + if (tags[i] < 0.5f) { + uv += uvs[i]; + cnt++; + } + } + uv /= cnt; + for (st = poly[0]; st != ed; ++st) { + auto i = loops[st]; + targetVertUvs[i] = uv; + } + } + +#if defined(_OPENMP) +#pragma omp parallel for schedule(guided, 4) +#endif + for (Ti i = 0; i < pos.size(); ++i) { + if (tags[i] > 0.5f) { + auto dist = std::numeric_limits::max(); + auto uvDist2 = std::numeric_limits::max(); + Ti id = -1; + zeno::vec3f uv = targetVertUvs[i]; + auto w = lbvh->find_nearest_with_uv(pos[i], uv, id, dist, uvDist2); + if (id != -1) { + auto refTri = refTris[id]; + uvs[i] = (refUvs[refTri[0]] * w[0] + refUvs[refTri[1]] * w[1] + refUvs[refTri[2]] * w[2]); // update new uv closer to target uv + } + } + } + #endif + } + + set_output("prim", prim); + } +}; + +ZENDEFNODE(RematchBestPrimitiveUV, { + {{"PrimitiveObject", "prim"}, {"LBvh", "lbvh"}, + {"float", "threshold", "0.001"}, + {"string", "selection_tag", "selected"} + }, + {{"PrimitiveObject", "prim"}}, + {}, + {"zenofx"}, + }); + struct QueryNearestPrimitiveWithinGroup : zeno::INode { From a37ab6bf8c95ecdd9515d45d6cdd5539fa73af20 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Mon, 11 Dec 2023 14:35:25 +0800 Subject: [PATCH 017/106] fix local pos bug --- projects/CUDA/utils/Tracing.cu | 2 +- zenovis/xinxinoptix/DeflMatShader.cu | 2 +- zenovis/xinxinoptix/PTKernel.cu | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/projects/CUDA/utils/Tracing.cu b/projects/CUDA/utils/Tracing.cu index 9dcaa07234..bc6c2d2559 100644 --- a/projects/CUDA/utils/Tracing.cu +++ b/projects/CUDA/utils/Tracing.cu @@ -151,7 +151,7 @@ constexpr float int_scale() { return 256.0f; } constexpr float float_scale() { - return 1.0f / 65536.0f; + return 1.0f / 32768.0f; } // Normal points outward for rays exiting the surface, else is flipped. diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index f1b91025c7..d4b7086e69 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -491,7 +491,7 @@ extern "C" __global__ void __closesthit__radiance() auto P_Local = interp(barys, v0, v1, v2); P = optixTransformPointFromObjectToWorldSpace(P_Local); // this value has precision issue for big float - attrs.pos = P; + attrs.pos = P + prd->camPos; float3 N_Local = normalize( cross( normalize(v1-v0), normalize(v2-v1) ) ); // this value has precision issue for big float float3 N_World = normalize(optixTransformNormalFromObjectToWorldSpace(N_Local)); diff --git a/zenovis/xinxinoptix/PTKernel.cu b/zenovis/xinxinoptix/PTKernel.cu index 3b3e1be421..480afcbd28 100644 --- a/zenovis/xinxinoptix/PTKernel.cu +++ b/zenovis/xinxinoptix/PTKernel.cu @@ -160,7 +160,7 @@ extern "C" __global__ void __raygen__rg() RadiancePRD prd; prd.adepth = 0; - prd.camPos = ray_origin; + prd.camPos = cam.eye; prd.emission = make_float3(0.f); prd.radiance = make_float3(0.f); prd.attenuation = make_float3(1.f); From c0607f0189b89b4fb42577660c04ca21bd10fbf9 Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Mon, 11 Dec 2023 15:05:43 +0800 Subject: [PATCH 018/106] preset regularTypeMat and carPaintTypeMat --- ui/zenoedit/panel/zenospreadsheet.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ui/zenoedit/panel/zenospreadsheet.cpp b/ui/zenoedit/panel/zenospreadsheet.cpp index 6aa23b485d..6983e0fcc2 100644 --- a/ui/zenoedit/panel/zenospreadsheet.cpp +++ b/ui/zenoedit/panel/zenospreadsheet.cpp @@ -273,6 +273,14 @@ bool ZenoSpreadsheet::eventFilter(QObject* watched, QEvent* event) { map[mtlid] = "TransmitTypeMat"; } + else if (mtlid.contains("Paint", Qt::CaseInsensitive)) + { + map[mtlid] = "CarPaintTypeMat"; + } + else + { + map[mtlid] = "RegularTypeMat"; + } } ZForkSubgraphDlg dlg(map, this); dlg.exec(); From ee256120a57bba2ba427c4d8976f9a9274635edc Mon Sep 17 00:00:00 2001 From: YingQ Date: Mon, 11 Dec 2023 15:27:07 +0800 Subject: [PATCH 019/106] fixhfremap --- zeno/src/nodes/prim/WBErode.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/zeno/src/nodes/prim/WBErode.cpp b/zeno/src/nodes/prim/WBErode.cpp index eded0fc387..4459610f92 100644 --- a/zeno/src/nodes/prim/WBErode.cpp +++ b/zeno/src/nodes/prim/WBErode.cpp @@ -2630,7 +2630,7 @@ struct HF_remap : INode { auto terrain = get_input("prim"); auto remapLayer = get_input2("remap layer"); if (!terrain->verts.has_attr(remapLayer)) { - zeno::log_error("Node [HF_maskByFeature], no such data layer named '{}'.", + zeno::log_error("Node [HF_remap], no such data layer named '{}'.", remapLayer); } auto& var = terrain->verts.attr(remapLayer); @@ -2674,6 +2674,9 @@ struct HF_remap : INode { var[i] = curve->eval(var[i]); var[i] = fit(var[i], 0, 1, outMin, outMax); } + if (remapLayer == "height"){ + terrain->verts.attr("pos")[i][1] = var[i]; + } } set_output("prim", get_input("prim")); From f6e4ee6694504b452b5ad176291b3e96da52e054 Mon Sep 17 00:00:00 2001 From: YingQ Date: Mon, 11 Dec 2023 15:27:24 +0800 Subject: [PATCH 020/106] trim string --- zeno/src/nodes/StringNodes.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 591a97c5ad..3cf3940f82 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -375,23 +375,37 @@ ZENDEFNODE(StringToNumber, {{ "string", }}); +std::string& trim(std::string &s) +{ + if (s.empty()) + { + return s; + } + s.erase(0,s.find_first_not_of(" \f\n\r\t\v")); + s.erase(s.find_last_not_of(" \f\n\r\t\v") + 1); + return s; +} + struct StringToList : zeno::INode { virtual void apply() override { auto stringlist = get_input2("string"); auto list = std::make_shared(); auto separator = get_input2("Separator"); + auto trimoption = get_input2("Trim"); std::vector strings; size_t pos = 0; size_t posbegin = 0; std::string word; while ((pos = stringlist.find(separator, pos)) != std::string::npos) { word = stringlist.substr(posbegin, pos-posbegin); + if(trimoption) trim(word); strings.push_back(word); pos += separator.length(); posbegin = pos; } if (posbegin < stringlist.length()) { //push last word word = stringlist.substr(posbegin); + if(trimoption) trim(word); strings.push_back(word); } for(const auto &string : strings) { @@ -405,8 +419,9 @@ struct StringToList : zeno::INode { ZENDEFNODE(StringToList, { { - {"string", "string", ""}, + {"multiline_string", "string", ""}, {"string", "Separator", ""}, + {"bool", "Trim", "false"}, }, {{"list"}, }, From 55da698e02bea5801863a78eda4ca463f160a454 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 15:34:36 +0800 Subject: [PATCH 021/106] PrimsFilterInUserdata --- projects/Alembic/ReadAlembic.cpp | 52 ++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index 43d9b85a9d..5c379d5179 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -18,6 +18,7 @@ #include #include #include +#include using namespace Alembic::AbcGeom; @@ -949,6 +950,57 @@ ZENDEFNODE(CopyPosAndNrmByIndex, { {"alembic"}, }); +struct PrimsFilterInUserdata: INode { + void apply() override { + auto prims = get_input("list")->get(); + auto filter_str = get_input2("filters"); + std::vector filters = zeno::split_str(filter_str); + std::vector filters_; + auto out_list = std::make_shared(); + + for (auto &s: filters) { + if (s.length() > 0) { + filters_.push_back(s); + } + } + + auto name = get_input2("name"); + auto contain = get_input2("contain"); + for (auto p: prims) { + auto &ud = p->userData(); + bool this_contain = false; + if (ud.has(name)) { + this_contain = std::count(filters_.begin(), filters_.end(), ud.get2(name)) > 0; + } + else if (ud.has(name)) { + this_contain = std::count(filters_.begin(), filters_.end(), std::to_string(ud.get2(name))) > 0; + } + else if (ud.has(name)) { + this_contain = std::count(filters_.begin(), filters_.end(), std::to_string(ud.get2(name))) > 0; + } + bool insert = (contain && this_contain) || (!contain && !this_contain); + if (insert) { + out_list->arr.push_back(p); + } + } + set_output("out", out_list); + } +}; + +ZENDEFNODE(PrimsFilterInUserdata, { + { + {"list", "list"}, + {"string", "name", ""}, + {"string", "filters"}, + {"bool", "contain", "1"}, + }, + { + {"out"}, + }, + {}, + {"alembic"}, +}); + } // namespace zeno From 010df0045c2e33b6002fa3e88e42d283e8243550 Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Mon, 11 Dec 2023 15:48:57 +0800 Subject: [PATCH 022/106] material subgraph only show single tab --- ui/zenoedit/nodesview/zenographseditor.cpp | 36 +++++++++++++++++++++- ui/zenoedit/nodesview/zenographseditor.h | 1 + ui/zenoedit/panel/zenospreadsheet.cpp | 4 +-- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/ui/zenoedit/nodesview/zenographseditor.cpp b/ui/zenoedit/nodesview/zenographseditor.cpp index 9f7b03ce8b..56e842e53d 100644 --- a/ui/zenoedit/nodesview/zenographseditor.cpp +++ b/ui/zenoedit/nodesview/zenographseditor.cpp @@ -122,6 +122,12 @@ void ZenoGraphsEditor::initSignals() connect(m_ui->graphsViewTab, &QTabWidget::tabCloseRequested, this, [=](int index) { m_ui->graphsViewTab->removeTab(index); }); + connect(m_ui->graphsViewTab, &QTabWidget::currentChanged, this, [=](int index) { + if (m_ui->graphsViewTab->tabText(index).compare("main", Qt::CaseInsensitive) == 0) + { + ZenoSettingsManager::GetInstance().setValue(zsSubgraphType, SUBGRAPH_NOR); + } + }); connect(m_ui->searchEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onSearchEdited(const QString&))); connect(m_ui->searchResView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(onSearchItemClicked(const QModelIndex&))); @@ -190,6 +196,8 @@ void ZenoGraphsEditor::resetModel(IGraphsModel* pModel) proxyModel->invalidate(); int type = ZenoSettingsManager::GetInstance().getValue(zsName).toInt(); m_ui->label->setText(type == SUBGRAPH_TYPE::SUBGRAPH_NOR ? tr("Subnet") : type == SUBGRAPH_TYPE::SUBGRAPH_METERIAL ? tr("Material Subnet") : tr("Preset Subnet")); + if (type != SUBGRAPH_METERIAL) + closeMaterialTab(); } }); activateTab("main"); @@ -469,6 +477,25 @@ int ZenoGraphsEditor::tabIndexOfName(const QString& subGraphName) return -1; } +void ZenoGraphsEditor::closeMaterialTab() +{ + for (int i = 0; i < m_ui->graphsViewTab->count(); i++) + { + QString subGraphName = m_ui->graphsViewTab->tabText(i); + auto graphsMgm = zenoApp->graphsManagment(); + IGraphsModel* pModel = graphsMgm->currentModel(); + ZASSERT_EXIT(pModel); + if (pModel->index(subGraphName).isValid()) + { + if (pModel->index(subGraphName).data(ROLE_SUBGRAPH_TYPE).toInt() == SUBGRAPH_METERIAL) + { + m_ui->graphsViewTab->removeTab(i); + break; + } + } + } +} + void ZenoGraphsEditor::onListItemActivated(const QModelIndex& index) { const QString& subgraphName = index.data().toString(); @@ -525,11 +552,18 @@ void ZenoGraphsEditor::activateTab(const QString& subGraphName, const QString& p if (!pModel->index(subGraphName).isValid()) return; - + if (subGraphName.compare("main", Qt::CaseInsensitive) == 0) + { + closeMaterialTab(); + } int idx = tabIndexOfName(subGraphName); if (idx == -1) { const QModelIndex& subgIdx = pModel->index(subGraphName); + if (subgIdx.data(ROLE_SUBGRAPH_TYPE).toInt() == SUBGRAPH_METERIAL) + { + closeMaterialTab(); + } ZenoSubGraphScene* pScene = qobject_cast(graphsMgm->gvScene(subgIdx)); if (!pScene) diff --git a/ui/zenoedit/nodesview/zenographseditor.h b/ui/zenoedit/nodesview/zenographseditor.h index b6005c9be3..1b0279ad38 100644 --- a/ui/zenoedit/nodesview/zenographseditor.h +++ b/ui/zenoedit/nodesview/zenographseditor.h @@ -72,6 +72,7 @@ private slots: void toggleViewForSelected(bool bOn); int tabIndexOfName(const QString& subGraphName); void markSubgError(const QStringList &lst); + void closeMaterialTab(); ZenoMainWindow* m_mainWin; Ui::GraphsEditor* m_ui; diff --git a/ui/zenoedit/panel/zenospreadsheet.cpp b/ui/zenoedit/panel/zenospreadsheet.cpp index 6983e0fcc2..a408b17a32 100644 --- a/ui/zenoedit/panel/zenospreadsheet.cpp +++ b/ui/zenoedit/panel/zenospreadsheet.cpp @@ -116,9 +116,8 @@ ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { }); connect(prim_attr_view, &QTableView::doubleClicked, this, [=](const QModelIndex& index) { - int type = ZenoSettingsManager::GetInstance().getValue(zsSubgraphType).toInt(); QString label = prim_attr_view->model()->headerData(index.row(), Qt::Vertical).toString(); - if (type == SUBGRAPH_METERIAL && label.contains("Material", Qt::CaseInsensitive)) + if (label.contains("Material", Qt::CaseInsensitive)) { QString mtlid = index.data(Qt::DisplayRole).toString(); IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); @@ -131,6 +130,7 @@ ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { QString subgraph_name = subgIdx.data(ROLE_OBJNAME).toString(); ZenoMainWindow* pWin = zenoApp->getMainWindow(); if (pWin) { + ZenoSettingsManager::GetInstance().setValue(zsSubgraphType, SUBGRAPH_METERIAL); ZenoGraphsEditor* pEditor = pWin->getAnyEditor(); if (pEditor) pEditor->activateTab(subgraph_name, "", ""); From 35afa0647b82cfbebdd3b067768f1b672113c7e9 Mon Sep 17 00:00:00 2001 From: miyanyan <1138989048@qq.com> Date: Mon, 11 Dec 2023 16:44:22 +0800 Subject: [PATCH 023/106] [fix] ZenoSpreadsheet: lambda Dangling references --- ui/zenoedit/panel/zenospreadsheet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/zenoedit/panel/zenospreadsheet.cpp b/ui/zenoedit/panel/zenospreadsheet.cpp index a408b17a32..a133bc4ec7 100644 --- a/ui/zenoedit/panel/zenospreadsheet.cpp +++ b/ui/zenoedit/panel/zenospreadsheet.cpp @@ -110,7 +110,7 @@ ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { // do not select all when clicked cornerBtn->disconnect(); // reset sort order - connect(cornerBtn, &QAbstractButton::clicked, this, [&]() { + connect(cornerBtn, &QAbstractButton::clicked, this, [&, sortModel]() { sortModel->sort(-1); prim_attr_view->horizontalHeader()->setSortIndicator(-1, Qt::SortOrder::AscendingOrder); }); From 144932876616e1a34a47c29bb769199e37b5c703 Mon Sep 17 00:00:00 2001 From: miyanyan <1138989048@qq.com> Date: Mon, 11 Dec 2023 17:27:06 +0800 Subject: [PATCH 024/106] ZenoSpreadsheet: add enable sort checkbox --- ui/zenoedit/panel/zenospreadsheet.cpp | 14 ++++++++++++-- ui/zenoedit/panel/zenospreadsheet.h | 1 + ui/zenoedit/res/stylesheet/checkbox.qss | 6 ++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/ui/zenoedit/panel/zenospreadsheet.cpp b/ui/zenoedit/panel/zenospreadsheet.cpp index a133bc4ec7..71dad56c71 100644 --- a/ui/zenoedit/panel/zenospreadsheet.cpp +++ b/ui/zenoedit/panel/zenospreadsheet.cpp @@ -40,6 +40,11 @@ ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { pPrimName->setProperty("cssClass", "proppanel"); pTitleLayout->addWidget(pPrimName); + m_checkSortingEnabled = new QCheckBox(this); + m_checkSortingEnabled->setProperty("cssClass", "proppanel"); + m_checkSortingEnabled->setText(tr("enable sort")); + pTitleLayout->addWidget(m_checkSortingEnabled); + ZComboBox* pMode = new ZComboBox(); pMode->addItem("Vertex"); @@ -61,7 +66,7 @@ ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { prim_attr_view = new QTableView(); prim_attr_view->setAlternatingRowColors(true); - prim_attr_view->setSortingEnabled(true); + prim_attr_view->setSortingEnabled(false); prim_attr_view->setProperty("cssClass", "proppanel"); prim_attr_view->setModel(sortModel); prim_attr_view->installEventFilter(this); @@ -101,10 +106,15 @@ ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { prim_attr_view->setSortingEnabled(false); } else { - prim_attr_view->setSortingEnabled(true); + prim_attr_view->setSortingEnabled(m_checkSortingEnabled->checkState()); } }); + // enable sort + connect(m_checkSortingEnabled, &QCheckBox::stateChanged, this, [this](int state) { + prim_attr_view->setSortingEnabled(state != Qt::CheckState::Unchecked); + }); + // corner button of tableview auto cornerBtn = prim_attr_view->findChild(); // do not select all when clicked diff --git a/ui/zenoedit/panel/zenospreadsheet.h b/ui/zenoedit/panel/zenospreadsheet.h index e3d999f681..d397534a0c 100644 --- a/ui/zenoedit/panel/zenospreadsheet.h +++ b/ui/zenoedit/panel/zenospreadsheet.h @@ -23,6 +23,7 @@ class ZenoSpreadsheet : public QWidget { bool eventFilter(QObject* watched, QEvent* event) override; private: QTableView* prim_attr_view; + QCheckBox* m_checkSortingEnabled; }; diff --git a/ui/zenoedit/res/stylesheet/checkbox.qss b/ui/zenoedit/res/stylesheet/checkbox.qss index dc69672030..8162cbe98c 100644 --- a/ui/zenoedit/res/stylesheet/checkbox.qss +++ b/ui/zenoedit/res/stylesheet/checkbox.qss @@ -60,4 +60,10 @@ QCheckBox[cssClass = "AlwaysCheckBox"]::indicator:checked QCheckBox[cssClass = "AlwaysCheckBox"]::indicator:unchecked { image: url(:/icons/always_checkbox.svg); +} + +QCheckBox[cssClass = "proppanel"] { + font-size: 9pt; + font-weight: bold; + color: rgba(255, 255, 255, 0.7); } \ No newline at end of file From 8d01f54db7d203fd91173f6afca255a86440ef59 Mon Sep 17 00:00:00 2001 From: littlemine Date: Mon, 11 Dec 2023 17:29:22 +0800 Subject: [PATCH 025/106] fix build typo --- zeno/src/nodes/StringNodes.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index ff6cda96d6..41fa2d0f56 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -275,8 +275,8 @@ struct StringSplitAndMerge: zeno::INode{ auto schar = get_input2("schar"); auto merge = get_input2("merge"); - auto &strings = split(str, schar); - auto &merges = split(merge, ","); + const auto &strings = split(str, schar); + const auto &merges = split(merge, ","); std::string outputstr = ""; for(auto idx:merges) { From 874baa9c699316e67161e2eadd18e7d48362eba8 Mon Sep 17 00:00:00 2001 From: littlemine Date: Mon, 11 Dec 2023 17:29:56 +0800 Subject: [PATCH 026/106] enhance primfuse --- projects/CUDA/utils/Primitives.cpp | 159 ++++++++++++++++++++++------- 1 file changed, 120 insertions(+), 39 deletions(-) diff --git a/projects/CUDA/utils/Primitives.cpp b/projects/CUDA/utils/Primitives.cpp index bb3beae1c6..7750d243e2 100644 --- a/projects/CUDA/utils/Primitives.cpp +++ b/projects/CUDA/utils/Primitives.cpp @@ -765,6 +765,21 @@ ZENDEFNODE(PrimitiveReorder, }); struct PrimitiveFuse : INode { + std::set separate_string_by(const std::string &tags, const std::string &sep) { + std::set res; + using Ti = RM_CVREF_T(std::string::npos); + Ti st = tags.find_first_not_of(sep, 0); + for (auto ed = tags.find_first_of(sep, st + 1); ed != std::string::npos; ed = tags.find_first_of(sep, st + 1)) { + res.insert(tags.substr(st, ed - st)); + st = tags.find_first_not_of(sep, ed); + if (st == std::string::npos) + break; + } + if (st != std::string::npos && st < tags.size()) { + res.insert(tags.substr(st)); + } + return res; + } virtual void apply() override { auto prim = get_input("prim"); @@ -776,6 +791,8 @@ struct PrimitiveFuse : INode { auto &verts = prim->verts; const auto &pos = verts.values; + auto preservedAttribs_ = get_input2("preserved_vert_attribs"); + std::set preservedAttribs = separate_string_by(preservedAttribs_, " :;,."); /// @brief establish vert proximity topo RM_CVREF_T(prim->verts) newVerts; @@ -875,32 +892,56 @@ struct PrimitiveFuse : INode { if (hasTris) { auto &eles = prim->tris; - // add custom tris attributes - verts.foreach_attr([&](auto const &key, auto const &arr) { + auto promoteVertAttribToTri = [&](auto const &key, auto const &arr) { using T = std::decay_t; eles.add_attr(key + "0"); eles.add_attr(key + "1"); eles.add_attr(key + "2"); - }); - pol(enumerate(eles.values), [&fas, &verts, &eles](int ei, auto &tri) mutable { - for (auto &[key, vertArr] : verts.attrs) { - auto const &k = key; - match( - [&k, &eles, &tri, ei](auto &vertArr) - -> std::enable_if_t::value> { - using T = RM_CVREF_T(vertArr[0]); - eles.attr(k + "0")[ei] = vertArr[tri[0]]; - eles.attr(k + "1")[ei] = vertArr[tri[1]]; - eles.attr(k + "2")[ei] = vertArr[tri[2]]; - }, - [](...) {})(vertArr); + }; + // add custom tris attributes + if (preservedAttribs.size() > 0) { + for (const auto &attribTag : preservedAttribs) { + if (verts.has_attr(attribTag)) + match([&](const auto &arr) { promoteVertAttribToTri(attribTag, arr); })(verts.attr(attribTag)); + } + } else { + verts.foreach_attr(promoteVertAttribToTri); + } + pol(enumerate(eles.values), [&fas, &verts, &eles, &preservedAttribs](int ei, auto &tri) mutable { + if (preservedAttribs.size() > 0) { + for (const auto &attribTag : preservedAttribs) { + if (verts.has_attr(attribTag)) + match( + [&k = attribTag, &eles, &tri, ei](auto &vertArr) + -> std::enable_if_t< + variant_contains::value> { + using T = RM_CVREF_T(vertArr[0]); + eles.attr(k + "0")[ei] = vertArr[tri[0]]; + eles.attr(k + "1")[ei] = vertArr[tri[1]]; + eles.attr(k + "2")[ei] = vertArr[tri[2]]; + }, + [](...) {})(verts.attr(attribTag)); + } + } else { + for (auto &[key, vertArr] : verts.attrs) { + auto const &k = key; + match( + [&k, &eles, &tri, ei](auto &vertArr) + -> std::enable_if_t::value> { + using T = RM_CVREF_T(vertArr[0]); + eles.attr(k + "0")[ei] = vertArr[tri[0]]; + eles.attr(k + "1")[ei] = vertArr[tri[1]]; + eles.attr(k + "2")[ei] = vertArr[tri[2]]; + }, + [](...) {})(vertArr); + } } for (auto &e : tri) e = fas[e]; }); } else { bool uv_exist = prim->uvs.size() > 0 && loops.has_attr("uvs"); - verts.foreach_attr([&](auto const &key, auto const &arr) { + auto promoteVertAttribToLoop = [&](auto const &key, auto const &arr) { using T = std::decay_t; if (key != "uv") loops.add_attr(key); @@ -908,35 +949,73 @@ struct PrimitiveFuse : INode { loops.add_attr("uvs"); prim->uvs.resize(loops.size()); } - }); - pol(range(polys), [&fas, &verts, &loops, &prim, uv_exist](const auto &poly) mutable { + }; + if (preservedAttribs.size() > 0) { + for (const auto &attribTag : preservedAttribs) { + if (verts.has_attr(attribTag)) + match([&](const auto &arr) { promoteVertAttribToLoop(attribTag, arr); })(verts.attr(attribTag)); + } + } else { + verts.foreach_attr(promoteVertAttribToLoop); + } + + pol(range(polys), [&fas, &verts, &loops, &prim, &preservedAttribs, uv_exist](const auto &poly) mutable { auto offset = poly[0]; auto size = poly[1]; for (int i = 0; i < size; ++i) { auto loopI = offset + i; auto ptNo = loops[loopI]; - for (auto &[key, vertArr] : verts.attrs) { - auto const &k = key; - auto &lps = loops; - if (k == "uv") { - if (!uv_exist) { - auto &loopUV = loops.attr("uvs"); - loopUV[loopI] = loopI; - auto &uvs = prim->uvs.values; - const auto &srcVertUV = std::get>(vertArr); - auto vertUV = srcVertUV[ptNo]; - uvs[loopI] = vec2f(vertUV[0], vertUV[1]); + if (preservedAttribs.size() > 0) { + for (const auto &attribTag : preservedAttribs) { + if (verts.has_attr(attribTag)) { + const auto &k = attribTag; + const auto &vertArr = verts.attr(attribTag); + auto &lps = loops; + if (k == "uv") { + if (!uv_exist) { + auto &loopUV = loops.attr("uvs"); + loopUV[loopI] = loopI; + auto &uvs = prim->uvs.values; + const auto &srcVertUV = std::get>(vertArr); + auto vertUV = srcVertUV[ptNo]; + uvs[loopI] = vec2f(vertUV[0], vertUV[1]); + } + } else { + match( + [&k, &lps, loopI, ptNo](auto &vertArr) + -> std::enable_if_t< + variant_contains::value> { + using T = RM_CVREF_T(vertArr[0]); + lps.attr(k)[loopI] = vertArr[ptNo]; + }, + [](...) {})(vertArr); + } + } + } + } else { + for (auto &[key, vertArr] : verts.attrs) { + auto const &k = key; + auto &lps = loops; + if (k == "uv") { + if (!uv_exist) { + auto &loopUV = loops.attr("uvs"); + loopUV[loopI] = loopI; + auto &uvs = prim->uvs.values; + const auto &srcVertUV = std::get>(vertArr); + auto vertUV = srcVertUV[ptNo]; + uvs[loopI] = vec2f(vertUV[0], vertUV[1]); + } + } else { + match( + [&k, &lps, loopI, ptNo](auto &vertArr) + -> std::enable_if_t< + variant_contains::value> { + using T = RM_CVREF_T(vertArr[0]); + lps.attr(k)[loopI] = vertArr[ptNo]; + }, + [](...) {})(vertArr); } - } else { - match( - [&k, &lps, loopI, ptNo](auto &vertArr) - -> std::enable_if_t< - variant_contains::value> { - using T = RM_CVREF_T(vertArr[0]); - lps.attr(k)[loopI] = vertArr[ptNo]; - }, - [](...) {})(vertArr); } } @@ -952,7 +1031,9 @@ struct PrimitiveFuse : INode { }; ZENDEFNODE(PrimitiveFuse, { - {{"PrimitiveObject", "prim"}, {"float", "proximity_theshold", "0.00001"}}, + {{"PrimitiveObject", "prim"}, + {"float", "proximity_theshold", "0.00001"}, + {"string", "preserved_vert_attribs", ""}}, { {"PrimitiveObject", "prim"}, }, From 2ed51daaec8bf9ce371471986f97d549bfcaef8b Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 17:35:39 +0800 Subject: [PATCH 027/106] fix --- projects/Alembic/ReadAlembic.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index 5c379d5179..73aba6d23e 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -89,7 +89,7 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp } else if (prim->polys.size() * 3 == data.size()) { auto &attr = prim->polys.add_attr(p.getName()); - for (auto i = 0; i < prim->verts.size(); i++) { + for (auto i = 0; i < prim->polys.size(); i++) { attr[i] = { data[ 3 * i], data[3 * i + 1], data[3 * i + 2]}; } } @@ -824,6 +824,7 @@ struct ReadAlembic : INode { read_done = true; usedPath = path; } + zeno::log_info("..........."); { auto namelist = std::make_shared(); abctree->visitPrims([&] (auto const &p) { From dda91649d80411e93ac818b85428383cd786cf89 Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Mon, 11 Dec 2023 17:48:37 +0800 Subject: [PATCH 028/106] params json command parse --- ui/include/common.h | 1 + ui/zenoedit/launch/optixcmd.cpp | 1 + ui/zenoedit/launch/serialize.cpp | 19 +++++++++++++------ ui/zenoedit/recordmain.cpp | 23 ++++++++++++++--------- ui/zenoedit/util/apphelper.cpp | 21 +++++++++++++++++++++ ui/zenoedit/zenomainwindow.cpp | 22 ++++++++++++++++++++++ ui/zenomodel/include/modeldata.h | 1 + 7 files changed, 73 insertions(+), 15 deletions(-) diff --git a/ui/include/common.h b/ui/include/common.h index af6757c754..30565a59c6 100644 --- a/ui/include/common.h +++ b/ui/include/common.h @@ -114,6 +114,7 @@ struct ZENO_RECORD_RUN_INITPARAM { QString configFilePath = ""; QString videoName = ""; QString subZsg = ""; + QString paramsJson = ""; bool exitWhenRecordFinish = false; }; diff --git a/ui/zenoedit/launch/optixcmd.cpp b/ui/zenoedit/launch/optixcmd.cpp index 9505bc2974..8bde9a3374 100644 --- a/ui/zenoedit/launch/optixcmd.cpp +++ b/ui/zenoedit/launch/optixcmd.cpp @@ -57,6 +57,7 @@ int optixcmd(const QCoreApplication& app, int port) {"cacheautorm", "cacheautoremove", "remove cache after render"}, {"optixShowBackground", "optixShowBackground", "optix record with background"}, {"paramsPath", "paramsPath", "paramsPath"}, + {"paramsJson", "paramsJson", "paramsJson"}, }); cmdParser.process(app); diff --git a/ui/zenoedit/launch/serialize.cpp b/ui/zenoedit/launch/serialize.cpp index 24497a1810..383a99b48e 100644 --- a/ui/zenoedit/launch/serialize.cpp +++ b/ui/zenoedit/launch/serialize.cpp @@ -298,14 +298,21 @@ static void serializeGraph(IGraphsModel* pGraphsModel, const QModelIndex& subgId //command params const QString& objPath = inSockIdx.data(ROLE_OBJPATH).toString(); - if (!configPath.isEmpty() && commandParams.contains(objPath)) + if (commandParams.contains(objPath)) { - const QString& command = commandParams[objPath].name; - if (configDoc.HasMember(command.toUtf8())) + if (!configPath.isEmpty()) { - const auto& obj = configDoc[command.toStdString().c_str()]; - if (obj.IsObject() && obj.HasMember("value")) - defl = UiHelper::parseJsonByType(sockType, obj["value"], nullptr); + const QString& command = commandParams[objPath].name; + if (configDoc.HasMember(command.toUtf8())) + { + const auto& obj = configDoc[command.toStdString().c_str()]; + if (obj.IsObject() && obj.HasMember("value")) + defl = UiHelper::parseJsonByType(sockType, obj["value"], nullptr); + } + } + else if (commandParams[objPath].bIsCommand) + { + defl = commandParams[objPath].value; } } diff --git a/ui/zenoedit/recordmain.cpp b/ui/zenoedit/recordmain.cpp index 31eb67d078..86941b7ed5 100644 --- a/ui/zenoedit/recordmain.cpp +++ b/ui/zenoedit/recordmain.cpp @@ -92,7 +92,8 @@ int record_main(const QCoreApplication& app) {"subzsg", "subgraphzsg", "subgraph zsg file path"}, {"cacheautorm", "cacheautoremove", "remove cache after render"}, {"paramsPath", "paramsPath", "paramsPath"}, - }); + {"paramsJson", "paramsJson", "paramsJson"}, + }); cmdParser.process(app); if (cmdParser.isSet("zsg")) @@ -160,17 +161,21 @@ int record_main(const QCoreApplication& app) } param.iBitrate = cmdParser.isSet("bitrate") ? cmdParser.value("bitrate").toInt() : 20000; param.iFps = cmdParser.isSet("fps") ? cmdParser.value("fps").toInt() : 24; - param.bOptix = cmdParser.isSet("optix") ? cmdParser.value("optix").toInt() : 0; - param.isExportVideo = cmdParser.isSet("video") ? cmdParser.value("video").toInt() : 0; - param.needDenoise = cmdParser.isSet("needDenoise") ? cmdParser.value("needDenoise").toInt() : 0; - int enableAOV = cmdParser.isSet("aov") ? cmdParser.value("aov").toInt() : 0; - param.export_exr = cmdParser.isSet("exr") && cmdParser.value("exr").toInt() != 0; - auto &ud = zeno::getSession().userData(); + param.bOptix = cmdParser.isSet("optix") ? cmdParser.value("optix").toInt() : 0; + param.isExportVideo = cmdParser.isSet("video") ? cmdParser.value("video").toInt() : 0; + param.needDenoise = cmdParser.isSet("needDenoise") ? cmdParser.value("needDenoise").toInt() : 0; + int enableAOV = cmdParser.isSet("aov") ? cmdParser.value("aov").toInt() : 0; + param.export_exr = cmdParser.isSet("exr") && cmdParser.value("exr").toInt() != 0; + auto& ud = zeno::getSession().userData(); ud.set2("output_aov", enableAOV != 0); ud.set2("output_exr", param.export_exr); - param.videoName = cmdParser.isSet("videoname") ? cmdParser.value("videoname") : "output.mp4"; - param.subZsg = cmdParser.isSet("subzsg") ? cmdParser.value("subzsg") : ""; + param.videoName = cmdParser.isSet("videoname") ? cmdParser.value("videoname") : "output.mp4"; + param.subZsg = cmdParser.isSet("subzsg") ? cmdParser.value("subzsg") : ""; + if (cmdParser.isSet("paramsJson")) + { + param.paramsJson = cmdParser.value("paramsJson"); + } if (!param.bOptix) { //gl normal recording may not be work in cmd mode. diff --git a/ui/zenoedit/util/apphelper.cpp b/ui/zenoedit/util/apphelper.cpp index 66eac2c658..8b06acc751 100644 --- a/ui/zenoedit/util/apphelper.cpp +++ b/ui/zenoedit/util/apphelper.cpp @@ -432,6 +432,27 @@ bool AppHelper::openZsgAndRun(const ZENO_RECORD_RUN_INITPARAM& param, LAUNCH_PAR auto& ud = zeno::getSession().userData(); ud.set2("optix_show_background", pGraphs->userdataInfo().optix_show_background); + if (!param.paramsJson.isEmpty()) + { + //parse paramsJson + rapidjson::Document configDoc; + configDoc.Parse(param.paramsJson.toUtf8()); + if (!configDoc.IsObject()) + { + zeno::log_error("config file is corrupted"); + } + FuckQMap commands = pGraphs->currentModel()->commandParams(); + for (auto& [key, param] : commands) + { + if (configDoc.HasMember(param.name.toUtf8())) + { + param.value = UiHelper::parseJson(configDoc[param.name.toStdString().c_str()], nullptr); + param.bIsCommand = true; + } + pGraphs->currentModel()->updateCommandParam(key, param); + } + } + launchProgram(pModel, launchParam); return true; } diff --git a/ui/zenoedit/zenomainwindow.cpp b/ui/zenoedit/zenomainwindow.cpp index 4b5b080f85..76976e13ac 100644 --- a/ui/zenoedit/zenomainwindow.cpp +++ b/ui/zenoedit/zenomainwindow.cpp @@ -1119,6 +1119,28 @@ void ZenoMainWindow::solidRunRender(const ZENO_RECORD_RUN_INITPARAM& param, LAUN pGraphsModel->updateNodeStatus(subgNodeId, info, mainGraphIdx, true); } } + if (!param.paramsJson.isEmpty()) + { + //parse paramsJson + rapidjson::Document configDoc; + configDoc.Parse(param.paramsJson.toUtf8()); + if (!configDoc.IsObject()) + { + zeno::log_error("config file is corrupted"); + } + IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + ZASSERT_EXIT(pGraphsModel); + FuckQMap commands = pGraphsModel->commandParams(); + for (auto& [key, param] : commands) + { + if (configDoc.HasMember(param.name.toUtf8())) + { + param.value = UiHelper::parseJson(configDoc[param.name.toStdString().c_str()], nullptr); + param.bIsCommand = true; + } + pGraphsModel->updateCommandParam(key, param); + } + } zeno::getSession().globalComm->clearState(); launchParam.beginFrame = recInfo.frameRange.first; diff --git a/ui/zenomodel/include/modeldata.h b/ui/zenomodel/include/modeldata.h index f0dd21075d..43da03fc63 100644 --- a/ui/zenomodel/include/modeldata.h +++ b/ui/zenomodel/include/modeldata.h @@ -335,6 +335,7 @@ struct CommandParam QString name; QString description; QVariant value; + bool bIsCommand = false; bool operator==(const CommandParam& rhs) const { return name == rhs.name && description == rhs.description && value == rhs.value; } From 0636386a0c5718120553c1edfe21e26496ac98c7 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 19:12:50 +0800 Subject: [PATCH 029/106] improve-abc --- projects/Alembic/ReadAlembic.cpp | 46 +++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index 73aba6d23e..772a5b5feb 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -241,6 +241,39 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp } } } + else if (IC3fGeomParam::matches(p)) { + if (!read_done) { + log_info("[alembic] IC3fGeomParam attr {}.", p.getName()); + } + IC3fGeomParam param(arbattrs, p.getName()); + IC3fGeomParam::Sample samp = param.getIndexedValue(iSS); + if (prim->verts.size() == samp.getVals()->size()) { + auto &attr = prim->add_attr(p.getName()); + for (auto i = 0; i < prim->verts.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else if (prim->loops.size() == samp.getVals()->size()) { + auto &attr = prim->loops.add_attr(p.getName()); + for (auto i = 0; i < prim->loops.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else if (prim->polys.size() == samp.getVals()->size()) { + auto &attr = prim->polys.add_attr(p.getName()); + for (auto i = 0; i < prim->polys.size(); i++) { + auto v = samp.getVals()->get()[i]; + attr[i] = {v[0], v[1], v[2]}; + } + } + else { + if (!read_done) { + log_error("[alembic] can not load C3f attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + } + } + } else { if (!read_done) { log_error("[alembic] can not load attr {}..", p.getName()); @@ -298,6 +331,18 @@ static void read_user_data(std::shared_ptr prim, ICompoundPrope auto value = param.getValue(iSS); prim->userData().set2(p.getName(), value); } + else if (IBoolProperty::matches(p)) { + IBoolProperty param(arbattrs, p.getName()); + + auto value = param.getValue(iSS); + prim->userData().set2(p.getName(), int(value)); + } + else if (IInt16Property::matches(p)) { + IInt16Property param(arbattrs, p.getName()); + + auto value = param.getValue(iSS); + prim->userData().set2(p.getName(), int(value)); + } else { if (!read_done) { log_error("[alembic] can not load user data {}..", p.getName()); @@ -824,7 +869,6 @@ struct ReadAlembic : INode { read_done = true; usedPath = path; } - zeno::log_info("..........."); { auto namelist = std::make_shared(); abctree->visitPrims([&] (auto const &p) { From 0051b76c13cd06bfe0261279e509afffb487239e Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 19:27:47 +0800 Subject: [PATCH 030/106] improve-abc --- projects/Alembic/ReadAlembic.cpp | 33 -------------------------------- 1 file changed, 33 deletions(-) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index 772a5b5feb..39951c34dd 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -241,39 +241,6 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp } } } - else if (IC3fGeomParam::matches(p)) { - if (!read_done) { - log_info("[alembic] IC3fGeomParam attr {}.", p.getName()); - } - IC3fGeomParam param(arbattrs, p.getName()); - IC3fGeomParam::Sample samp = param.getIndexedValue(iSS); - if (prim->verts.size() == samp.getVals()->size()) { - auto &attr = prim->add_attr(p.getName()); - for (auto i = 0; i < prim->verts.size(); i++) { - auto v = samp.getVals()->get()[i]; - attr[i] = {v[0], v[1], v[2]}; - } - } - else if (prim->loops.size() == samp.getVals()->size()) { - auto &attr = prim->loops.add_attr(p.getName()); - for (auto i = 0; i < prim->loops.size(); i++) { - auto v = samp.getVals()->get()[i]; - attr[i] = {v[0], v[1], v[2]}; - } - } - else if (prim->polys.size() == samp.getVals()->size()) { - auto &attr = prim->polys.add_attr(p.getName()); - for (auto i = 0; i < prim->polys.size(); i++) { - auto v = samp.getVals()->get()[i]; - attr[i] = {v[0], v[1], v[2]}; - } - } - else { - if (!read_done) { - log_error("[alembic] can not load C3f attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); - } - } - } else { if (!read_done) { log_error("[alembic] can not load attr {}..", p.getName()); From 3a1f2b940f8c9040715ff08e0bec1323d39ce089 Mon Sep 17 00:00:00 2001 From: archibate <1931127624@qq.com> Date: Mon, 11 Dec 2023 19:50:46 +0800 Subject: [PATCH 031/106] 111 --- .gitignore | 1 + zeno/include/zeno/extra/ShaderNode.h | 8 ++++++++ zeno/src/extra/ShaderNode.cpp | 13 ++++++++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 899f95e73c..fa0f8a577c 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ Release/ /.idea /.vscode /.cache +CMakeKits.json CMakeSettings.json CMakeUserPresets.json .vim_localrc diff --git a/zeno/include/zeno/extra/ShaderNode.h b/zeno/include/zeno/extra/ShaderNode.h index 6396a65ff2..418bb72c40 100644 --- a/zeno/include/zeno/extra/ShaderNode.h +++ b/zeno/include/zeno/extra/ShaderNode.h @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -35,6 +36,11 @@ struct EmissionPass { Backend backend = GLSL; + struct ConstInfo { + int type; + NumericValue value; + }; + struct VarInfo { int type; ShaderNode *node; @@ -47,6 +53,8 @@ struct EmissionPass { std::string code; }; + std::map constmap; + std::vector constants; std::map varmap; /* varmap[node] = 40, then the variable of node is "tmp40" */ std::vector variables; /* variables[40].type = 3, then the variable type will be "vec3 tmp40;" */ std::vector lines; /* contains a list of operations, e.g. {"tmp40 = tmp41 + 1;", "tmp42 = tmp40 * 2;"} */ diff --git a/zeno/src/extra/ShaderNode.cpp b/zeno/src/extra/ShaderNode.cpp index 36234f254c..e6f2758300 100644 --- a/zeno/src/extra/ShaderNode.cpp +++ b/zeno/src/extra/ShaderNode.cpp @@ -27,7 +27,10 @@ ZENO_API std::string EmissionPass::finalizeCode() { ZENO_API int EmissionPass::determineType(IObject *object) { if (auto num = dynamic_cast(object)) { - return std::visit([&] (auto const &value) -> int { + if (auto it = constmap.find(num); it != constmap.end()) + return constants.at(it->second).type; + + int type = std::visit([&] (auto const &value) -> int { using T = std::decay_t; if constexpr (std::is_same_v) { return 1; @@ -41,6 +44,9 @@ ZENO_API int EmissionPass::determineType(IObject *object) { throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); } }, num->value); + constmap[num] = constants.size(); + constants.push_back(ConstInfo{type, num->value}); + return type; } else if (auto tree = dynamic_cast(object)) { assert(tree->node); @@ -144,6 +150,10 @@ static std::string ftos(float x) { ZENO_API std::string EmissionPass::determineExpr(IObject *object) const { if (auto num = dynamic_cast(object)) { + int id; +#if 0 + return "constmp" + std::to_string(constmap.at(num)); +#else return std::visit([&] (auto const &value) -> std::string { using T = std::decay_t; if constexpr (std::is_same_v) { @@ -160,6 +170,7 @@ ZENO_API std::string EmissionPass::determineExpr(IObject *object) const { throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); } }, num->value); +#endif } else if (auto tree = dynamic_cast(object)) { return "tmp" + std::to_string(varmap.at(tree->node.get())); From 49e1ea51167febdea6bf88123b431137d8e098d9 Mon Sep 17 00:00:00 2001 From: littlemine Date: Mon, 11 Dec 2023 19:54:14 +0800 Subject: [PATCH 032/106] enhance primitiveunfuse --- projects/CUDA/utils/Primitives.cpp | 315 +++++++++++++++++------------ 1 file changed, 186 insertions(+), 129 deletions(-) diff --git a/projects/CUDA/utils/Primitives.cpp b/projects/CUDA/utils/Primitives.cpp index 7750d243e2..728ffcb5f9 100644 --- a/projects/CUDA/utils/Primitives.cpp +++ b/projects/CUDA/utils/Primitives.cpp @@ -1041,162 +1041,219 @@ ZENDEFNODE(PrimitiveFuse, { {"zs_geom"}, }); -/// @note duplicate vertices shared by multiple groups -struct PrimitiveUnfuse : INode { - void apply() override { - using namespace zs; - auto prim = get_input("prim"); - auto tag = get_input2("partition_tag"); +static std::shared_ptr unfuse_primitive(std::shared_ptr prim, std::string tag) { + using namespace zs; + constexpr auto space = execspace_e::openmp; + auto pol = omp_exec(); - constexpr auto space = execspace_e::openmp; - auto pol = omp_exec(); + auto &verts = prim->verts; + const auto &pos = verts.values; - auto &verts = prim->verts; - const auto &pos = verts.values; + auto &tris = prim->tris; + const auto &triIds = tris.values; + const bool hasTris = tris.size() > 0; - auto &tris = prim->tris; - const auto &triIds = tris.values; - const bool hasTris = tris.size() > 0; + auto &polys = prim->polys; + const auto &loops = prim->loops; + const bool hasLoops = polys.size() > 1; - auto &polys = prim->polys; - const auto &loops = prim->loops; - const bool hasLoops = polys.size() > 1; - - if ((hasTris ^ hasLoops) == 0) - throw std::runtime_error("The input mesh must either own active triangle topology or loop topology."); + if ((hasTris ^ hasLoops) == 0) + throw std::runtime_error("The input mesh must either own active triangle topology or loop topology."); - std::vector> groupsPerVertex(pos.size()); - if (hasTris) { - const auto &triGroups = tris.attr(tag); - std::vector mtxs(pos.size()); - pol(zip(triIds, triGroups), [&mtxs, &groupsPerVertex](auto tri, int groupNo) { - for (int d = 0; d != 3; ++d) { - int vi = tri[d]; - auto &mtx = mtxs[vi]; - auto &group = groupsPerVertex[vi]; - { - mtxs[vi].lock(); - group.insert(groupNo); - mtxs[vi].unlock(); - } - }; - }); - } else { - const auto &polyGroups = polys.attr(tag); - std::vector mtxs(pos.size()); - pol(zip(polys.values, polyGroups), [&mtxs, &groupsPerVertex, &loops](zeno::vec2i poly, int groupNo) { - auto st = poly[0]; - auto ed = st + poly[1]; - for (; st != ed; ++st) { - int vi = loops.values[st]; - - auto &mtx = mtxs[vi]; - auto &group = groupsPerVertex[vi]; - { - mtxs[vi].lock(); - group.insert(groupNo); - mtxs[vi].unlock(); - } + std::vector> groupsPerVertex(pos.size()); + if (hasTris) { + const auto &triGroups = tris.attr(tag); + std::vector mtxs(pos.size()); + pol(zip(triIds, triGroups), [&mtxs, &groupsPerVertex](auto tri, int groupNo) { + for (int d = 0; d != 3; ++d) { + int vi = tri[d]; + auto &mtx = mtxs[vi]; + auto &group = groupsPerVertex[vi]; + { + mtxs[vi].lock(); + group.insert(groupNo); + mtxs[vi].unlock(); } - }); + }; + }); + } else { + const auto &polyGroups = polys.attr(tag); + std::vector mtxs(pos.size()); + pol(zip(polys.values, polyGroups), [&mtxs, &groupsPerVertex, &loops](zeno::vec2i poly, int groupNo) { + auto st = poly[0]; + auto ed = st + poly[1]; + for (; st != ed; ++st) { + int vi = loops.values[st]; + + auto &mtx = mtxs[vi]; + auto &group = groupsPerVertex[vi]; + { + mtxs[vi].lock(); + group.insert(groupNo); + mtxs[vi].unlock(); + } + } + }); + } + + std::vector numGroupsPerVertex(pos.size() + 1), ptrs(pos.size() + 1); + pol(zip(numGroupsPerVertex, groupsPerVertex), [](int &num, const std::set &g) { num = g.size(); }); + exclusive_scan(pol, std::begin(numGroupsPerVertex), std::end(numGroupsPerVertex), std::begin(ptrs)); + + auto numEntries = ptrs.back(); + std::vector inds(numEntries); + pol(enumerate(groupsPerVertex), [&inds, &ptrs](int vi, const std::set &groups) { + auto st = ptrs[vi], ed = ptrs[vi + 1]; + for (auto groupNo : groups) { + inds[st++] = groupNo; // the first group does not need to change } + }); - std::vector numGroupsPerVertex(pos.size() + 1), ptrs(pos.size() + 1); - pol(zip(numGroupsPerVertex, groupsPerVertex), [](int &num, const std::set &g) { num = g.size(); }); - exclusive_scan(pol, std::begin(numGroupsPerVertex), std::end(numGroupsPerVertex), std::begin(ptrs)); + auto resPrim = std::make_shared(); - auto numEntries = ptrs.back(); - std::vector inds(numEntries); - pol(enumerate(groupsPerVertex), [&inds, &ptrs](int vi, const std::set &groups) { - auto st = ptrs[vi], ed = ptrs[vi + 1]; - for (auto groupNo : groups) { - inds[st++] = groupNo; // the first group does not need to change - } + resPrim->verts.resize(numEntries); + auto &resVerts = resPrim->verts; + auto &resPos = resVerts.values; + verts.foreach_attr([&](const auto &key, const auto &arr) { + using T = std::decay_t; + resVerts.add_attr(key); + }); + pol(range(pos.size()), [&ptrs, &verts, &resVerts, &resPos](int vi) { + auto st = ptrs[vi], ed = ptrs[vi + 1]; + for (int j = st; j != ed; ++j) + resPos[j] = verts.values[vi]; + resVerts.foreach_attr([&](const auto &key, auto &dst) { + using T = std::decay_t; + const auto &src = verts.attr(key); + for (int j = st; j != ed; ++j) + dst[j] = src[vi]; }); + }); - auto resPrim = std::make_shared(); + if (hasTris) { + const auto &triGroups = tris.attr(tag); - resPrim->verts.resize(numEntries); - auto &resVerts = resPrim->verts; - auto &resPos = resVerts.values; - verts.foreach_attr([&](const auto &key, const auto &arr) { + resPrim->tris.resize(tris.size()); + auto &resTris = resPrim->tris; + auto &resTriIds = resTris.values; + tris.foreach_attr([&](const auto &key, const auto &arr) { using T = std::decay_t; - resVerts.add_attr(key); + resTris.add_attr(key) = arr; }); - pol(range(pos.size()), [&ptrs, &verts, &resVerts, &resPos](int vi) { - auto st = ptrs[vi], ed = ptrs[vi + 1]; - for (int j = st; j != ed; ++j) - resPos[j] = verts.values[vi]; - resVerts.foreach_attr([&](const auto &key, auto &dst) { - using T = std::decay_t; - const auto &src = verts.attr(key); - for (int j = st; j != ed; ++j) - dst[j] = src[vi]; - }); + pol(range(tris.size()), [&](int f) { + auto groupNo = triGroups[f]; + for (int d = 0; d != 3; ++d) { + int vi = tris[f][d]; + int st = ptrs[vi], ed = ptrs[vi + 1]; + for (; st != ed; ++st) { + if (groupNo == inds[st]) + break; + } + resTriIds[f][d] = st; + } }); + } else { + const auto &polyGroups = polys.attr(tag); + bool uvExist = prim->uvs.size() > 0 && loops.has_attr("uvs"); - if (hasTris) { - const auto &triGroups = tris.attr(tag); + resPrim->polys.resize(polys.size()); + resPrim->loops.resize(loops.size()); + auto &resPolys = resPrim->polys; + auto &resLoops = resPrim->loops; - resPrim->tris.resize(tris.size()); - auto &resTris = resPrim->tris; - auto &resTriIds = resTris.values; - tris.foreach_attr([&](const auto &key, const auto &arr) { - using T = std::decay_t; - resTris.add_attr(key) = arr; - }); - pol(range(tris.size()), [&](int f) { - auto groupNo = triGroups[f]; - for (int d = 0; d != 3; ++d) { - int vi = tris[f][d]; - int st = ptrs[vi], ed = ptrs[vi + 1]; - for (; st != ed; ++st) { - if (groupNo == inds[st]) - break; - } - resTriIds[f][d] = st; + resPolys.values = polys.values; + polys.foreach_attr([&](const auto &key, const auto &arr) { + using T = std::decay_t; + resPolys.add_attr(key) = arr; + }); + + loops.foreach_attr([&](const auto &key, const auto &arr) { + using T = std::decay_t; + resLoops.add_attr(key) = arr; + }); + // resLoops.values = loops.values; + pol(zip(polys.values, polyGroups), [&](zeno::vec2i poly, int groupNo) { + auto st = poly[0]; + auto ed = st + poly[1]; + for (; st != ed; ++st) { + int vi = loops.values[st]; + + int l = ptrs[vi], r = ptrs[vi + 1]; + for (; l != r; ++l) { + if (groupNo == inds[l]) + break; } - }); - } else { - const auto &polyGroups = polys.attr(tag); - bool uvExist = prim->uvs.size() > 0 && loops.has_attr("uvs"); + resLoops.values[st] = l; + } + }); + } + return resPrim; +} - resPrim->polys.resize(polys.size()); - resPrim->loops.resize(loops.size()); - auto &resPolys = resPrim->polys; - auto &resLoops = resPrim->loops; +/// @note duplicate vertices shared by multiple groups +struct PrimitiveUnfuse : INode { + void apply() override { + auto prim = get_input("prim"); + auto tag = get_input2("partition_tag"); - resPolys.values = polys.values; - polys.foreach_attr([&](const auto &key, const auto &arr) { - using T = std::decay_t; - resPolys.add_attr(key) = arr; - }); + auto resPrim = unfuse_primitive(prim, tag); - loops.foreach_attr([&](const auto &key, const auto &arr) { - using T = std::decay_t; - resLoops.add_attr(key) = arr; - }); - // resLoops.values = loops.values; - pol(zip(polys.values, polyGroups), [&](zeno::vec2i poly, int groupNo) { - auto st = poly[0]; - auto ed = st + poly[1]; - for (; st != ed; ++st) { - int vi = loops.values[st]; + bool toList = get_input2("to_list"); - int l = ptrs[vi], r = ptrs[vi + 1]; - for (; l != r; ++l) { - if (groupNo == inds[l]) - break; + if (toList) { + constexpr auto space = zs::execspace_e::openmp; + auto pol = zs::omp_exec(); + + auto &verts = resPrim->verts; + const auto &pos = verts.values; + + auto &tris = resPrim->tris; + const bool hasTris = tris.size() > 0; + + auto &polys = resPrim->polys; + const bool hasLoops = polys.size() > 1; + + auto &vertGroups = resPrim->verts.add_attr(tag); + + if (hasTris) { + const auto &triIds = tris.values; + const auto &triGroups = tris.attr(tag); + + pol(zs::zip(triIds, triGroups), [&vertGroups](auto tri, int groupNo) { + for (int d = 0; d != 3; ++d) { + int vi = tri[d]; + vertGroups[vi] = groupNo; } - resLoops.values[st] = l; - } - }); + }); + } else { + const auto &loops = resPrim->loops.values; + const auto &polyGroups = polys.attr(tag); + + pol(zs::zip(polys.values, polyGroups), [&vertGroups, &loops](zeno::vec2i poly, int groupNo) { + auto st = poly[0]; + auto ed = st + poly[1]; + for (; st != ed; ++st) { + int vi = loops[st]; + vertGroups[vi] = groupNo; + } + }); + } + + auto primList = primUnmergeVerts(resPrim.get(), tag); + auto listPrim = std::make_shared(); + for (auto &primPtr : primList) { + listPrim->arr.push_back(std::move(primPtr)); + } + set_output("partitioned_prim", std::move(listPrim)); + } else { + set_output("partitioned_prim", std::move(resPrim)); } - set_output("partitioned_prim", std::move(resPrim)); } }; ZENDEFNODE(PrimitiveUnfuse, { - {{"PrimitiveObject", "prim"}, {"string", "partition_tag", "triangle_index"}}, + {{"PrimitiveObject", "prim"}, + {"string", "partition_tag", "triangle_index"}, + {"bool", "to_list", "false"}}, { {"PrimitiveObject", "partitioned_prim"}, }, From 07c74d644933e577baad2b9ad1cc93ca89699acf Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 19:58:51 +0800 Subject: [PATCH 033/106] improve-abc --- zeno/src/nodes/JsonProcess.cpp | 54 ++++++++++++++++++++++++++++++---- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/zeno/src/nodes/JsonProcess.cpp b/zeno/src/nodes/JsonProcess.cpp index 7e6d414df7..6d84d27a13 100644 --- a/zeno/src/nodes/JsonProcess.cpp +++ b/zeno/src/nodes/JsonProcess.cpp @@ -33,6 +33,26 @@ ZENDEFNODE(ReadJson, { "json" }, }); +struct ReadJsonFromString : zeno::INode { + virtual void apply() override { + auto json = std::make_shared(); + auto content = get_input2("content"); + json->json = Json::parse(content); + set_output("json", json); + } +}; +ZENDEFNODE(ReadJsonFromString, { + { + {"string", "content"}, + }, + { + "json", + }, + {}, + { + "json" + }, +}); struct JsonGetArraySize : zeno::INode { virtual void apply() override { auto json = get_input("json"); @@ -76,20 +96,44 @@ ZENDEFNODE(JsonGetArrayItem, { struct JsonGetChild : zeno::INode { virtual void apply() override { - auto out_json = std::make_shared(); auto json = get_input("json"); auto name = get_input2("name"); - out_json->json = json->json[name]; - set_output("json", out_json); + auto type = get_input2("type"); + if (type == "json") { + auto out_json = std::make_shared(); + out_json->json = json->json[name]; + set_output("out", out_json); + } + else if (type == "int") { + set_output2("out", int(json->json[name])); + } + else if (type == "float") { + set_output2("out", float(json->json[name])); + } + else if (type == "string") { + set_output2("out", std::string(json->json[name])); + } + else if (type == "vec2f") { + float x = float(json->json[name][0]); + float y = float(json->json[name][1]); + set_output2("out", vec2f(x, y)); + } + else if (type == "vec3f") { + float x = float(json->json[name][0]); + float y = float(json->json[name][1]); + float z = float(json->json[name][2]); + set_output2("out", vec3f(x, y, z)); + } } }; ZENDEFNODE(JsonGetChild, { { {"json"}, - {"string", "name"} + {"string", "name"}, + {"enum json int float string vec2f vec3f", "type"}, }, { - "json", + "out", }, {}, { From b47eab23f55c729dd0258528b3fcae7b2352e566 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 20:29:54 +0800 Subject: [PATCH 034/106] improve json --- zeno/src/nodes/JsonProcess.cpp | 56 ++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/zeno/src/nodes/JsonProcess.cpp b/zeno/src/nodes/JsonProcess.cpp index 6d84d27a13..7ac4d6d56c 100644 --- a/zeno/src/nodes/JsonProcess.cpp +++ b/zeno/src/nodes/JsonProcess.cpp @@ -5,6 +5,7 @@ #include #include #include "zeno/utils/fileio.h" +#include "zeno/utils/string.h" using Json = nlohmann::json; namespace zeno { @@ -215,4 +216,59 @@ ZENDEFNODE(JsonGetTypeName, { }, }); +struct JsonData : zeno::INode { + virtual void apply() override { + auto json = get_input("json"); + auto path = get_input2("path"); + auto strings = zeno::split_str(path, ':'); + auto type = strings[1]; + path = strings[0]; + auto names = split_str(path, '/'); + + for (auto & name : names) { + json->json = json->json[name]; + } + + + if (type == "json") { + auto out_json = std::make_shared(); + out_json->json = json->json; + set_output("out", out_json); + } + else if (type == "int") { + set_output2("out", int(json->json)); + } + else if (type == "float") { + set_output2("out", float(json->json)); + } + else if (type == "string") { + set_output2("out", std::string(json->json)); + } + else if (type == "vec2f") { + float x = float(json->json[0]); + float y = float(json->json[1]); + set_output2("out", vec2f(x, y)); + } + else if (type == "vec3f") { + float x = float(json->json[0]); + float y = float(json->json[1]); + float z = float(json->json[2]); + set_output2("out", vec3f(x, y, z)); + } + } +}; +ZENDEFNODE(JsonData, { + { + {"json"}, + {"string", "path"}, + }, + { + "out", + }, + {}, + { + "json" + }, +}); + } \ No newline at end of file From 740dcfb3b7d4e009c40f15afbb7cee75a7547017 Mon Sep 17 00:00:00 2001 From: archibate <1931127624@qq.com> Date: Mon, 11 Dec 2023 21:32:01 +0800 Subject: [PATCH 035/106] shouhua --- zeno/src/extra/ShaderNode.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zeno/src/extra/ShaderNode.cpp b/zeno/src/extra/ShaderNode.cpp index d5cb4a6c43..b87b33be64 100644 --- a/zeno/src/extra/ShaderNode.cpp +++ b/zeno/src/extra/ShaderNode.cpp @@ -134,7 +134,7 @@ ZENO_API std::string EmissionPass::collectDefs() const { std::string res; int cnt = 0; for (auto const &var: constants) { - return std::visit([&] (auto const &value) -> std::string { + auto expr = std::visit([&] (auto const &value) -> std::string { using T = std::decay_t; if constexpr (std::is_same_v) { return typeNameOf(1) + "(" + ftos(value) + ")"; @@ -150,7 +150,7 @@ ZENO_API std::string EmissionPass::collectDefs() const { throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); } }, var.value); - res += typeNameOf(var.type) + " constmp" + std::to_string(cnt) + " = " + ";\n"; + res += typeNameOf(var.type) + " constmp" + std::to_string(cnt) + " = " + expr + ";\n"; cnt++; } cnt = 0; From dd2b3b22e7f0128404169bdb137f8fc59effa472 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 21:38:23 +0800 Subject: [PATCH 036/106] improve json --- zeno/src/nodes/JsonProcess.cpp | 83 ++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/zeno/src/nodes/JsonProcess.cpp b/zeno/src/nodes/JsonProcess.cpp index 7ac4d6d56c..a5e1925648 100644 --- a/zeno/src/nodes/JsonProcess.cpp +++ b/zeno/src/nodes/JsonProcess.cpp @@ -6,6 +6,12 @@ #include #include "zeno/utils/fileio.h" #include "zeno/utils/string.h" +#include "zeno/types/ListObject.h" +#include "zeno/types/DictObject.h" +#include +#include +#include + using Json = nlohmann::json; namespace zeno { @@ -271,4 +277,81 @@ ZENDEFNODE(JsonData, { }, }); +struct JsonGetData : zeno::INode { + virtual void apply() override { + auto in_json = get_input("json"); + auto multi_path = get_input2("paths"); + std::istringstream iss(multi_path); + std::vector paths; + std::string line; + while (std::getline(iss, line)) { + line = zeno::trim_string(line); + if (line.size()) { + paths.push_back(line); + } + } + + auto dict = std::make_shared(); + for (auto &path: paths) { + auto json = std::make_shared(); + json->json = in_json->json; + auto strings = zeno::split_str(path, ':'); + auto type = strings[1]; + path = strings[0]; + auto names = split_str(path, '/'); + + for (auto & name : names) { + json->json = json->json[name]; + } + + if (type == "json") { + auto out_json = std::make_shared(); + out_json->json = json->json; + dict->lut[path] = out_json; + } + else if (type == "int") { + dict->lut[path] = std::make_shared(int(json->json)); + } + else if (type == "float") { + dict->lut[path] = std::make_shared(float(json->json)); + } + else if (type == "string") { + dict->lut[path] = std::make_shared(std::string(json->json)); + } + else if (type == "vec2f") { + float x = float(json->json[0]); + float y = float(json->json[1]); + dict->lut[path] = std::make_shared(vec2f(x, y)); + } + else if (type == "vec3f") { + float x = float(json->json[0]); + float y = float(json->json[1]); + float z = float(json->json[2]); + dict->lut[path] = std::make_shared(vec3f(x, y, z)); + } + else if (type == "vec4f") { + float x = float(json->json[0]); + float y = float(json->json[1]); + float z = float(json->json[2]); + float w = float(json->json[3]); + dict->lut[path] = std::make_shared(vec4f(x, y, z, w)); + } + } + set_output("outs", dict); + } +}; +ZENDEFNODE(JsonGetData, { + { + {"json"}, + {"multiline_string", "paths"}, + }, + { + {"DictObject", "outs"} + }, + {}, + { + "json" + }, +}); + } \ No newline at end of file From cce6a9cb41151fdd12c1dd14f7e716987e667370 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 21:41:06 +0800 Subject: [PATCH 037/106] improve --- zeno/src/nodes/JsonProcess.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/zeno/src/nodes/JsonProcess.cpp b/zeno/src/nodes/JsonProcess.cpp index a5e1925648..4c767ce99b 100644 --- a/zeno/src/nodes/JsonProcess.cpp +++ b/zeno/src/nodes/JsonProcess.cpp @@ -144,7 +144,7 @@ ZENDEFNODE(JsonGetChild, { }, {}, { - "json" + "deprecated" }, }); struct JsonGetInt : zeno::INode { @@ -162,7 +162,7 @@ ZENDEFNODE(JsonGetInt, { }, {}, { - "json" + "deprecated" }, }); @@ -181,7 +181,7 @@ ZENDEFNODE(JsonGetFloat, { }, {}, { - "json" + "deprecated" }, }); @@ -200,7 +200,7 @@ ZENDEFNODE(JsonGetString, { }, {}, { - "json" + "deprecated" }, }); struct JsonGetTypeName : zeno::INode { @@ -218,7 +218,7 @@ ZENDEFNODE(JsonGetTypeName, { }, {}, { - "json" + "deprecated" }, }); @@ -273,7 +273,7 @@ ZENDEFNODE(JsonData, { }, {}, { - "json" + "deprecated" }, }); From a312c0ff1dcfa78db43d05b696a1407faae376d5 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Mon, 11 Dec 2023 21:58:42 +0800 Subject: [PATCH 038/106] revert shaderNode.cpp --- zeno/src/extra/ShaderNode.cpp | 348 ++++++++++++++++------------------ 1 file changed, 166 insertions(+), 182 deletions(-) diff --git a/zeno/src/extra/ShaderNode.cpp b/zeno/src/extra/ShaderNode.cpp index d5cb4a6c43..46bcdd8bdb 100644 --- a/zeno/src/extra/ShaderNode.cpp +++ b/zeno/src/extra/ShaderNode.cpp @@ -7,245 +7,229 @@ namespace zeno { -static std::string ftos(float x) { - std::ostringstream ss; - ss << x; - return ss.str(); -} - ZENO_API ShaderNode::ShaderNode() = default; ZENO_API ShaderNode::~ShaderNode() = default; ZENO_API void ShaderNode::apply() { - auto tree = std::make_shared(this); - set_output("out", std::move(tree)); + auto tree = std::make_shared(this); + set_output("out", std::move(tree)); } ZENO_API std::string EmissionPass::finalizeCode() { - auto defs = collectDefs(); - for (auto const &var: variables) { - var.node->emitCode(this); - } - translateCommonCode(); - auto code = collectCode(); - return defs + code; + auto defs = collectDefs(); + for (auto const &var: variables) { + var.node->emitCode(this); + } + translateCommonCode(); + auto code = collectCode(); + return defs + code; } ZENO_API int EmissionPass::determineType(IObject *object) { - if (auto num = dynamic_cast(object)) { - if (auto it = constmap.find(num); it != constmap.end()) - return constants.at(it->second).type; - - int type = std::visit([&] (auto const &value) -> int { - using T = std::decay_t; - if constexpr (std::is_same_v) { - return 1; - } else if constexpr (std::is_same_v) { - return 2; - } else if constexpr (std::is_same_v) { - return 3; - } else if constexpr (std::is_same_v) { - return 4; - } else { - throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); - } - }, num->value); - constmap[num] = constants.size(); - constants.push_back(ConstInfo{type, num->value}); - return type; - - } else if (auto tree = dynamic_cast(object)) { - assert(tree->node); - if (auto it = varmap.find(tree->node.get()); it != varmap.end()) - return variables.at(it->second).type; - int type = tree->node->determineType(this); - varmap[tree->node.get()] = variables.size(); - variables.push_back(VarInfo{type, tree->node.get()}); - return type; - - } else { - throw zeno::Exception("bad tree object type: " + (std::string)typeid(*object).name()); - } + if (auto num = dynamic_cast(object)) { + return std::visit([&] (auto const &value) -> int { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return 1; + } else if constexpr (std::is_same_v) { + return 2; + } else if constexpr (std::is_same_v) { + return 3; + } else if constexpr (std::is_same_v) { + return 4; + } else { + throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); + } + }, num->value); + + } else if (auto tree = dynamic_cast(object)) { + assert(tree->node); + if (auto it = varmap.find(tree->node.get()); it != varmap.end()) + return variables.at(it->second).type; + int type = tree->node->determineType(this); + varmap[tree->node.get()] = variables.size(); + variables.push_back(VarInfo{type, tree->node.get()}); + return type; + + } else { + throw zeno::Exception("bad tree object type: " + (std::string)typeid(*object).name()); + } } ZENO_API int EmissionPass::currentType(ShaderNode *node) const { - return variables[varmap.at(node)].type; + return variables[varmap.at(node)].type; } ZENO_API std::string EmissionPass::determineExpr(IObject *object, ShaderNode *node) const { - auto type = currentType(node); - auto expr = determineExpr(object); - duplicateIfHlsl(type, expr); - return typeNameOf(type) + "(" + expr + ")"; + auto type = currentType(node); + auto expr = determineExpr(object); + duplicateIfHlsl(type, expr); + return typeNameOf(type) + "(" + expr + ")"; } ZENO_API void EmissionPass::duplicateIfHlsl(int type, std::string &expr) const { - if (backend == HLSL && type > 1) { - /* WHY IS MICROSOFT SO STUPID? THIS IS A PROBLEM. */ - expr += " * float" + std::to_string(type) + "(1"; - auto tmp = ", 1"; - for (int i = 1; i < type; i++) - expr += tmp; - expr += ")"; - } + if (backend == HLSL && type > 1) { + /* WHY IS MICROSOFT SO STUPID? THIS IS A PROBLEM. */ + expr += " * float" + std::to_string(type) + "(1"; + auto tmp = ", 1"; + for (int i = 1; i < type; i++) + expr += tmp; + expr += ")"; + } } static const auto cihou = [] { - std::map cihou; - cihou["mix"] = "lerp"; - cihou["inversesqrt"] = "rsqrt"; - cihou["mod"] = "fmod"; - cihou["vec2"] = "float2"; - cihou["vec3"] = "float3"; - cihou["vec4"] = "float4"; - return cihou; + std::map cihou; + cihou["mix"] = "lerp"; + cihou["inversesqrt"] = "rsqrt"; + cihou["mod"] = "fmod"; + cihou["vec2"] = "float2"; + cihou["vec3"] = "float3"; + cihou["vec4"] = "float4"; + return cihou; }(); ZENO_API std::string EmissionPass::funcName(std::string const &fun) const { - if (backend == HLSL) { - if (auto it = cihou.find(fun); it != cihou.end()) - return it->second; - } - return fun; + if (backend == HLSL) { + if (auto it = cihou.find(fun); it != cihou.end()) + return it->second; + } + return fun; } ZENO_API std::string EmissionPass::addCommonFunc(EmissionPass::CommonFunc comm) { - int idx = commons.size(); - if (comm.name.empty()) - comm.name = "fun" + std::to_string(idx); - commons.push_back(std::move(comm)); - return commons.back().name; + int idx = commons.size(); + if (comm.name.empty()) + comm.name = "fun" + std::to_string(idx); + commons.push_back(std::move(comm)); + return commons.back().name; } ZENO_API std::string EmissionPass::getCommonCode() const { - std::string ret = commonCode; - for (int i = 0; i < commons.size(); i++) { - ret += "\n" + typeNameOf(commons[i].rettype) + " " + commons[i].name + commons[i].code + "\n"; - } - return ret; + std::string ret = commonCode; + for (int i = 0; i < commons.size(); i++) { + ret += "\n" + typeNameOf(commons[i].rettype) + " " + commons[i].name + commons[i].code + "\n"; + } + return ret; } ZENO_API std::string EmissionPass::typeNameOf(int type) const { - if (type == 1) return "float"; - else return (backend == HLSL ? "float" : "vec") + std::to_string(type); + if (type == 1) return "float"; + else return (backend == HLSL ? "float" : "vec") + std::to_string(type); } ZENO_API std::string EmissionPass::collectDefs() const { - std::string res; - int cnt = 0; - for (auto const &var: constants) { - return std::visit([&] (auto const &value) -> std::string { - using T = std::decay_t; - if constexpr (std::is_same_v) { - return typeNameOf(1) + "(" + ftos(value) + ")"; - } else if constexpr (std::is_same_v) { - return typeNameOf(2) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ")"; - } else if constexpr (std::is_same_v) { - return typeNameOf(3) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ", " - + ftos(value[2]) + ")"; - } else if constexpr (std::is_same_v) { - return typeNameOf(4) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ", " - + ftos(value[2]) + ", " + ftos(value[3]) + ")"; - } else { - throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); - } - }, var.value); - res += typeNameOf(var.type) + " constmp" + std::to_string(cnt) + " = " + ";\n"; - cnt++; - } - cnt = 0; - for (auto const &var: variables) { - res += typeNameOf(var.type) + " tmp" + std::to_string(cnt) + ";\n"; - cnt++; - } - return res; + std::string res; + int cnt = 0; + for (auto const &var: variables) { + res += typeNameOf(var.type) + " tmp" + std::to_string(cnt) + ";\n"; + cnt++; + } + return res; } ZENO_API std::string EmissionPass::collectCode() const { - std::string res; - for (auto const &line: lines) { - res += line + "\n"; - } - return res; + std::string res; + for (auto const &line: lines) { + res += line + "\n"; + } + return res; +} + +static std::string ftos(float x) { + std::ostringstream ss; + ss << x; + return ss.str(); } ZENO_API std::string EmissionPass::determineExpr(IObject *object) const { - if (auto num = dynamic_cast(object)) { - int id; -#if 0 - return "constmp" + std::to_string(constmap.at(num)); -#else -#endif - - } else if (auto tree = dynamic_cast(object)) { - return "tmp" + std::to_string(varmap.at(tree->node.get())); - } - return {}; + if (auto num = dynamic_cast(object)) { + return std::visit([&] (auto const &value) -> std::string { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return typeNameOf(1) + "(" + ftos(value) + ")"; + } else if constexpr (std::is_same_v) { + return typeNameOf(2) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ")"; + } else if constexpr (std::is_same_v) { + return typeNameOf(3) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ", " + + ftos(value[2]) + ")"; + } else if constexpr (std::is_same_v) { + return typeNameOf(4) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ", " + + ftos(value[2]) + ", " + ftos(value[3]) + ")"; + } else { + throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); + } + }, num->value); + + } else if (auto tree = dynamic_cast(object)) { + return "tmp" + std::to_string(varmap.at(tree->node.get())); + } + return {}; } ZENO_API void EmissionPass::emitCode(std::string const &line) { - int idx = lines.size(); - lines.push_back("tmp" + std::to_string(idx) + " = " + line + ";"); + int idx = lines.size(); + lines.push_back("tmp" + std::to_string(idx) + " = " + line + ";"); } ZENO_API std::string EmissionPass::finalizeCode(std::vector> const &keys, std::vector> const &vals) { - std::vector vartypes; - vartypes.reserve(keys.size()); - for (int i = 0; i < keys.size(); i++) { - int their_type = determineType(vals[i].get()); - int our_type = keys[i].first; - if (their_type != our_type && their_type != 1) - throw zeno::Exception("unexpected input for " + keys[i].second + " which requires " - + typeNameOf(our_type) + " but got " + typeNameOf(their_type)); - vartypes.push_back(their_type); - } - auto code = finalizeCode(); - for (int i = 0; i < keys.size(); i++) { - auto expr = determineExpr(vals[i].get()); - int our_type = keys[i].first; - duplicateIfHlsl(our_type, expr); - //printf("!!!!!!!!!!!!%d %s\n", our_type, expr.c_str()); - code += typeNameOf(our_type) + " " + keys[i].second + " = " + typeNameOf(our_type) + "(" + expr + ");\n"; - } - return code; + std::vector vartypes; + vartypes.reserve(keys.size()); + for (int i = 0; i < keys.size(); i++) { + int their_type = determineType(vals[i].get()); + int our_type = keys[i].first; + if (their_type != our_type && their_type != 1) + throw zeno::Exception("unexpected input for " + keys[i].second + " which requires " + + typeNameOf(our_type) + " but got " + typeNameOf(their_type)); + vartypes.push_back(their_type); + } + auto code = finalizeCode(); + for (int i = 0; i < keys.size(); i++) { + auto expr = determineExpr(vals[i].get()); + int our_type = keys[i].first; + duplicateIfHlsl(our_type, expr); + //printf("!!!!!!!!!!!!%d %s\n", our_type, expr.c_str()); + code += typeNameOf(our_type) + " " + keys[i].second + " = " + typeNameOf(our_type) + "(" + expr + ");\n"; + } + return code; } ZENO_API void EmissionPass::translateToHlsl(std::string &code) { - std::string ret; - for (auto const &[key, val]: cihou) { - size_t pos = 0, last_pos = 0; - ret.clear(); - auto isident = [] (char c) -> bool { - return ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; - }; - while ((pos = code.find(key, pos)) != std::string::npos) { - if (pos != 0 && isident(code[pos - 1])) { - pos += key.size(); - continue; - } - if (pos + key.size() != code.size() && isident(code[pos + key.size()])) { - pos += key.size(); - continue; - } - //printf("%s %s %d %d\n", key.c_str(), code.substr(pos).c_str(), last_pos, pos); - ret.append(code, last_pos, pos - last_pos); - ret.append(val); - pos += key.size(); - last_pos = pos; - } - if (!ret.empty() && last_pos != 0) { - ret.append(code, last_pos, std::string::npos); - code = std::move(ret); - } + std::string ret; + for (auto const &[key, val]: cihou) { + size_t pos = 0, last_pos = 0; + ret.clear(); + auto isident = [] (char c) -> bool { + return ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; + }; + while ((pos = code.find(key, pos)) != std::string::npos) { + if (pos != 0 && isident(code[pos - 1])) { + pos += key.size(); + continue; + } + if (pos + key.size() != code.size() && isident(code[pos + key.size()])) { + pos += key.size(); + continue; + } + //printf("%s %s %d %d\n", key.c_str(), code.substr(pos).c_str(), last_pos, pos); + ret.append(code, last_pos, pos - last_pos); + ret.append(val); + pos += key.size(); + last_pos = pos; + } + if (!ret.empty() && last_pos != 0) { + ret.append(code, last_pos, std::string::npos); + code = std::move(ret); } + } } ZENO_API void EmissionPass::translateCommonCode() { - if (backend != HLSL) return; - for (auto &comm: commons) - translateToHlsl(comm.code); - translateToHlsl(commonCode); + if (backend != HLSL) return; + for (auto &comm: commons) + translateToHlsl(comm.code); + translateToHlsl(commonCode); } } From 196f4f243c1ff01930b8ee3ccd0bfe3d256fce70 Mon Sep 17 00:00:00 2001 From: littlemine Date: Mon, 11 Dec 2023 22:00:05 +0800 Subject: [PATCH 039/106] enhance primunmerge --- projects/CUDA/utils/Primitives.cpp | 111 +++++++++++++++++++---------- projects/CUDA/zpc | 2 +- 2 files changed, 75 insertions(+), 38 deletions(-) diff --git a/projects/CUDA/utils/Primitives.cpp b/projects/CUDA/utils/Primitives.cpp index 728ffcb5f9..0e648ecb78 100644 --- a/projects/CUDA/utils/Primitives.cpp +++ b/projects/CUDA/utils/Primitives.cpp @@ -1190,6 +1190,47 @@ static std::shared_ptr unfuse_primitive(std::shared_ptr prim, std::string tag) { + using namespace zs; + constexpr auto space = execspace_e::openmp; + auto pol = omp_exec(); + + auto &verts = prim->verts; + const auto &pos = verts.values; + + auto &tris = prim->tris; + const bool hasTris = tris.size() > 0; + + auto &polys = prim->polys; + const bool hasLoops = polys.size() > 1; + + auto &vertGroups = prim->verts.add_attr(tag); + + if (hasTris) { + const auto &triIds = tris.values; + const auto &triGroups = tris.attr(tag); + + pol(zs::zip(triIds, triGroups), [&vertGroups](auto tri, int groupNo) { + for (int d = 0; d != 3; ++d) { + int vi = tri[d]; + vertGroups[vi] = groupNo; + } + }); + } else { + const auto &loops = prim->loops.values; + const auto &polyGroups = polys.attr(tag); + + pol(zs::zip(polys.values, polyGroups), [&vertGroups, &loops](zeno::vec2i poly, int groupNo) { + auto st = poly[0]; + auto ed = st + poly[1]; + for (; st != ed; ++st) { + int vi = loops[st]; + vertGroups[vi] = groupNo; + } + }); + } +} + /// @note duplicate vertices shared by multiple groups struct PrimitiveUnfuse : INode { void apply() override { @@ -1201,43 +1242,7 @@ struct PrimitiveUnfuse : INode { bool toList = get_input2("to_list"); if (toList) { - constexpr auto space = zs::execspace_e::openmp; - auto pol = zs::omp_exec(); - - auto &verts = resPrim->verts; - const auto &pos = verts.values; - - auto &tris = resPrim->tris; - const bool hasTris = tris.size() > 0; - - auto &polys = resPrim->polys; - const bool hasLoops = polys.size() > 1; - - auto &vertGroups = resPrim->verts.add_attr(tag); - - if (hasTris) { - const auto &triIds = tris.values; - const auto &triGroups = tris.attr(tag); - - pol(zs::zip(triIds, triGroups), [&vertGroups](auto tri, int groupNo) { - for (int d = 0; d != 3; ++d) { - int vi = tri[d]; - vertGroups[vi] = groupNo; - } - }); - } else { - const auto &loops = resPrim->loops.values; - const auto &polyGroups = polys.attr(tag); - - pol(zs::zip(polys.values, polyGroups), [&vertGroups, &loops](zeno::vec2i poly, int groupNo) { - auto st = poly[0]; - auto ed = st + poly[1]; - for (; st != ed; ++st) { - int vi = loops[st]; - vertGroups[vi] = groupNo; - } - }); - } + assign_group_tag_to_verts(resPrim, tag); auto primList = primUnmergeVerts(resPrim.get(), tag); auto listPrim = std::make_shared(); @@ -1261,6 +1266,38 @@ ZENDEFNODE(PrimitiveUnfuse, { {"zs_geom"}, }); +struct PrimitiveUnmerge : INode { + virtual void apply() override { + auto prim = get_input("prim"); + auto tag = get_input2("tagAttr"); + auto method = get_input2("method"); + + if (method == "faces") { + assign_group_tag_to_verts(prim, tag); + } + auto primList = primUnmergeVerts(prim.get(), tag); + + auto listPrim = std::make_shared(); + for (auto &primPtr : primList) { + listPrim->arr.push_back(std::move(primPtr)); + } + set_output("listPrim", std::move(listPrim)); + } +}; + +ZENDEFNODE(PrimitiveUnmerge, { + { + {"primitive", "prim"}, + {"string", "tagAttr", "tag"}, + {"enum verts faces", "method", "verts"}, + }, + { + {"list", "listPrim"}, + }, + {}, + {"primitive"}, + }); + struct MarkSelectedVerts : INode { void apply() override { auto prim = get_input("prim"); diff --git a/projects/CUDA/zpc b/projects/CUDA/zpc index efd865f356..2cc395e980 160000 --- a/projects/CUDA/zpc +++ b/projects/CUDA/zpc @@ -1 +1 @@ -Subproject commit efd865f35618a56f03277a3cc65bb848f7664b4a +Subproject commit 2cc395e980c311bc2ef04322c915124127237810 From c749535e07f9e11647b32de0d5f490722bad0cf3 Mon Sep 17 00:00:00 2001 From: littlemine Date: Mon, 11 Dec 2023 22:02:27 +0800 Subject: [PATCH 040/106] supp 'preSimplify' as original --- projects/CUDA/utils/Primitives.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/projects/CUDA/utils/Primitives.cpp b/projects/CUDA/utils/Primitives.cpp index 0e648ecb78..7986074625 100644 --- a/projects/CUDA/utils/Primitives.cpp +++ b/projects/CUDA/utils/Primitives.cpp @@ -1272,6 +1272,9 @@ struct PrimitiveUnmerge : INode { auto tag = get_input2("tagAttr"); auto method = get_input2("method"); + if (get_input2("preSimplify")) { + primSimplifyTag(prim.get(), tag); + } if (method == "faces") { assign_group_tag_to_verts(prim, tag); } @@ -1289,6 +1292,7 @@ ZENDEFNODE(PrimitiveUnmerge, { { {"primitive", "prim"}, {"string", "tagAttr", "tag"}, + {"bool", "preSimplify", "0"}, {"enum verts faces", "method", "verts"}, }, { From 64255ee6d1f5693087897706eb64dd522b6ce2d1 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 11 Dec 2023 22:40:05 +0800 Subject: [PATCH 041/106] improve --- zeno/src/nodes/JsonProcess.cpp | 35 ++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/zeno/src/nodes/JsonProcess.cpp b/zeno/src/nodes/JsonProcess.cpp index 4c767ce99b..d1889e1593 100644 --- a/zeno/src/nodes/JsonProcess.cpp +++ b/zeno/src/nodes/JsonProcess.cpp @@ -251,16 +251,23 @@ struct JsonData : zeno::INode { set_output2("out", std::string(json->json)); } else if (type == "vec2f") { - float x = float(json->json[0]); - float y = float(json->json[1]); + float x = float(json->json["x"]); + float y = float(json->json["y"]); set_output2("out", vec2f(x, y)); } else if (type == "vec3f") { - float x = float(json->json[0]); - float y = float(json->json[1]); - float z = float(json->json[2]); + float x = float(json->json["x"]); + float y = float(json->json["y"]); + float z = float(json->json["z"]); set_output2("out", vec3f(x, y, z)); } + else if (type == "vec4f") { + float x = float(json->json["x"]); + float y = float(json->json["y"]); + float z = float(json->json["z"]); + float w = float(json->json["w"]); + set_output2("out", vec4f(x, y, z, w)); + } } }; ZENDEFNODE(JsonData, { @@ -319,21 +326,21 @@ struct JsonGetData : zeno::INode { dict->lut[path] = std::make_shared(std::string(json->json)); } else if (type == "vec2f") { - float x = float(json->json[0]); - float y = float(json->json[1]); + float x = float(json->json["x"]); + float y = float(json->json["y"]); dict->lut[path] = std::make_shared(vec2f(x, y)); } else if (type == "vec3f") { - float x = float(json->json[0]); - float y = float(json->json[1]); - float z = float(json->json[2]); + float x = float(json->json["x"]); + float y = float(json->json["y"]); + float z = float(json->json["z"]); dict->lut[path] = std::make_shared(vec3f(x, y, z)); } else if (type == "vec4f") { - float x = float(json->json[0]); - float y = float(json->json[1]); - float z = float(json->json[2]); - float w = float(json->json[3]); + float x = float(json->json["x"]); + float y = float(json->json["y"]); + float z = float(json->json["z"]); + float w = float(json->json["w"]); dict->lut[path] = std::make_shared(vec4f(x, y, z, w)); } } From 3a25fbb3b6cb9ea28d5302079257b24b9d566919 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Tue, 12 Dec 2023 03:12:09 +0800 Subject: [PATCH 042/106] fix important SSS bug --- zenovis/xinxinoptix/DisneyBSDF.h | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/zenovis/xinxinoptix/DisneyBSDF.h b/zenovis/xinxinoptix/DisneyBSDF.h index 3566e43357..2e15f008e0 100644 --- a/zenovis/xinxinoptix/DisneyBSDF.h +++ b/zenovis/xinxinoptix/DisneyBSDF.h @@ -278,6 +278,7 @@ namespace DisneyBSDF{ // Onb tbn = Onb(N); world2local(wi, T, B, N); world2local(wo, T, B, N); + world2local(N2, T, B, N); bool reflect = wi.z * wo.z > 0.0f; @@ -411,7 +412,7 @@ namespace DisneyBSDF{ } if(sssPr>0.0) { - bool trans = wo.z * wi.z < 0.0f; + bool trans = wo.z * wi.z < 0.0f && dot(wo, N2) * dot(wi, N2)<0; float FL = BRDFBasics::SchlickWeight(abs(wi.z)); float FV = BRDFBasics::SchlickWeight(abs(wo.z)); float term = wo.z>0?FV:FL; @@ -627,6 +628,21 @@ namespace DisneyBSDF{ //go inside wi = -BRDFBasics::UniformSampleHemisphere(r1, r2); + + } + } + + tbn.inverse_transform(wi); + wi = normalize(wi); + + bool sameside2 = (dot(wi, N) * dot(wi, N2)) > 0.0f; + if (sameside == false) { + wi = normalize(wi - 1.01f * dot(wi, N2) * N2); + } + auto woo = wo; + tbn.inverse_transform(woo); + if(dot(wi, N2) * dot(woo, N2)<0 && dot(wi, N2)<0) { + isSS = true; flag = transmissionEvent; vec3 color = mix(mat.basecolor, mat.sssColor, mat.subsurface); @@ -636,18 +652,10 @@ namespace DisneyBSDF{ prd->ss_alpha = color; if (isSS) { medium = PhaseFunctions::isotropic; - CalculateExtinction2(color, sssRadius, prd->sigma_t, prd->ss_alpha, 1.4f); + CalculateExtinction2(color, sssRadius, prd->sigma_t, + prd->ss_alpha, 1.4f); } } - } - - tbn.inverse_transform(wi); - wi = normalize(wi); - - bool sameside2 = (dot(wi, N) * dot(wi, N2)) > 0.0f; - if (sameside == false) { - wi = normalize(wi - 1.01f * dot(wi, N2) * N2); - } //reflectance = vec3(1.0f) * M_PIf ; //return true; From b26833a6a4018bda3938147d977b19dc01b06240 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Tue, 12 Dec 2023 04:50:31 +0800 Subject: [PATCH 043/106] make sss greate again and agian --- zenovis/xinxinoptix/DisneyBSDF.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/zenovis/xinxinoptix/DisneyBSDF.h b/zenovis/xinxinoptix/DisneyBSDF.h index 2e15f008e0..a23d1e0d76 100644 --- a/zenovis/xinxinoptix/DisneyBSDF.h +++ b/zenovis/xinxinoptix/DisneyBSDF.h @@ -263,7 +263,8 @@ namespace DisneyBSDF{ float nDl, vec3 &dterm, vec3 &sterm, - vec3 &tterm) + vec3 &tterm, + bool reflectance = false) { bool sameside = (dot(wo, N)*dot(wo, N2))>0.0f; @@ -410,9 +411,9 @@ namespace DisneyBSDF{ f = f + s; fPdf += tmpPdf * clearCtPr; } - if(sssPr>0.0) + if((sssPr>0.0&&reflectance) || (sssPr>0.0 && dot(wo, N2)<0.0)) { - bool trans = wo.z * wi.z < 0.0f && dot(wo, N2) * dot(wi, N2)<0; + bool trans = dot(wo, N2) * dot(wi, N2)<0; float FL = BRDFBasics::SchlickWeight(abs(wi.z)); float FV = BRDFBasics::SchlickWeight(abs(wo.z)); float term = wo.z>0?FV:FL; @@ -742,7 +743,7 @@ namespace DisneyBSDF{ float pdf, pdf2; vec3 rd, rs, rt; reflectance = EvaluateDisney2(vec3(1.0f), mat, wi, wo, T, B, N, N2, thin, - is_inside, pdf, pdf2, 0, rd, rs, rt); + is_inside, pdf, pdf2, 0, rd, rs, rt, true); fPdf = pdf>1e-5?pdf:0.0f; reflectance = pdf>1e-5?reflectance:vec3(0.0f); return true; From 4761535b6546657a90aefd83792d85ff6d3d312e Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Tue, 12 Dec 2023 05:27:26 +0800 Subject: [PATCH 044/106] fix offset in a smart way so everything works --- zenovis/xinxinoptix/DeflMatShader.cu | 2 +- zenovis/xinxinoptix/PTKernel.cu | 2 +- zenovis/xinxinoptix/TraceStuff.h | 6 ++++-- zenovis/xinxinoptix/optixPathTracer.cpp | 6 ++---- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index d4b7086e69..f1b91025c7 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -491,7 +491,7 @@ extern "C" __global__ void __closesthit__radiance() auto P_Local = interp(barys, v0, v1, v2); P = optixTransformPointFromObjectToWorldSpace(P_Local); // this value has precision issue for big float - attrs.pos = P + prd->camPos; + attrs.pos = P; float3 N_Local = normalize( cross( normalize(v1-v0), normalize(v2-v1) ) ); // this value has precision issue for big float float3 N_World = normalize(optixTransformNormalFromObjectToWorldSpace(N_Local)); diff --git a/zenovis/xinxinoptix/PTKernel.cu b/zenovis/xinxinoptix/PTKernel.cu index 480afcbd28..6390d750ff 100644 --- a/zenovis/xinxinoptix/PTKernel.cu +++ b/zenovis/xinxinoptix/PTKernel.cu @@ -154,7 +154,7 @@ extern "C" __global__ void __raygen__rg() terminal_point = camera_transform * terminal_point; eye_shake = camera_transform * eye_shake; - float3 ray_origin = eye_shake; + float3 ray_origin = cam.eye + eye_shake; float3 ray_direction = terminal_point - eye_shake; ray_direction = normalize(ray_direction); diff --git a/zenovis/xinxinoptix/TraceStuff.h b/zenovis/xinxinoptix/TraceStuff.h index bbb2378bda..e29f3068a6 100644 --- a/zenovis/xinxinoptix/TraceStuff.h +++ b/zenovis/xinxinoptix/TraceStuff.h @@ -132,9 +132,11 @@ struct RadiancePRD } void offsetUpdateRay(float3& P, float3 new_dir) { - this->origin = P; + auto beforeOffset = P - this->camPos; + //this->origin = P; this->direction = new_dir; - offsetRay(this->origin, new_dir); + offsetRay(beforeOffset, new_dir); + this->origin = beforeOffset + this->camPos; } uint8_t _mask_ = EverythingMask; diff --git a/zenovis/xinxinoptix/optixPathTracer.cpp b/zenovis/xinxinoptix/optixPathTracer.cpp index 37189fe5cc..5c60ff4e50 100644 --- a/zenovis/xinxinoptix/optixPathTracer.cpp +++ b/zenovis/xinxinoptix/optixPathTracer.cpp @@ -430,7 +430,7 @@ static void updateRootIAS() { timer.tick(); auto campos = state.params.cam.eye; - const float mat3r4c[12] = {1,0,0,-campos.x, 0,1,0,-campos.y, 0,0,1,-campos.z}; + const float mat3r4c[12] = {1,0,0,0, 0,1,0,0, 0,0,1,0}; std::vector optix_instances{}; uint sbt_offset = 0u; { @@ -563,9 +563,7 @@ static void handleCameraUpdate( Params& params ) //params.vp4 = cam_vp4; camera.setAspectRatio( static_cast( params.windowSpace.x ) / static_cast( params.windowSpace.y ) ); - CUDA_SYNC_CHECK(); - updateRootIAS(); - CUDA_SYNC_CHECK(); + //params.eye = camera.eye(); //camera.UVWFrame( params.U, params.V, params.W ); } From 87477e591c5c69848e7ce3165ce89f0acd3010fd Mon Sep 17 00:00:00 2001 From: archibate <1931127624@qq.com> Date: Tue, 12 Dec 2023 09:48:35 +0800 Subject: [PATCH 045/106] nimabirevnima --- zeno/src/extra/ShaderNode.cpp | 308 ++++++++++++++++------------------ 1 file changed, 148 insertions(+), 160 deletions(-) diff --git a/zeno/src/extra/ShaderNode.cpp b/zeno/src/extra/ShaderNode.cpp index 2e4b872f43..fd9ea7f14b 100644 --- a/zeno/src/extra/ShaderNode.cpp +++ b/zeno/src/extra/ShaderNode.cpp @@ -7,119 +7,130 @@ namespace zeno { +static std::string ftos(float x) { + std::ostringstream ss; + ss << x; + return ss.str(); +} + ZENO_API ShaderNode::ShaderNode() = default; ZENO_API ShaderNode::~ShaderNode() = default; ZENO_API void ShaderNode::apply() { - auto tree = std::make_shared(this); - set_output("out", std::move(tree)); + auto tree = std::make_shared(this); + set_output("out", std::move(tree)); } ZENO_API std::string EmissionPass::finalizeCode() { - auto defs = collectDefs(); - for (auto const &var: variables) { - var.node->emitCode(this); - } - translateCommonCode(); - auto code = collectCode(); - return defs + code; + auto defs = collectDefs(); + for (auto const &var: variables) { + var.node->emitCode(this); + } + translateCommonCode(); + auto code = collectCode(); + return defs + code; } ZENO_API int EmissionPass::determineType(IObject *object) { - if (auto num = dynamic_cast(object)) { - return std::visit([&] (auto const &value) -> int { - using T = std::decay_t; - if constexpr (std::is_same_v) { - return 1; - } else if constexpr (std::is_same_v) { - return 2; - } else if constexpr (std::is_same_v) { - return 3; - } else if constexpr (std::is_same_v) { - return 4; - } else { - throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); - } - }, num->value); + if (auto num = dynamic_cast(object)) { + if (auto it = constmap.find(num); it != constmap.end()) + return constants.at(it->second).type; - } else if (auto tree = dynamic_cast(object)) { - assert(tree->node); - if (auto it = varmap.find(tree->node.get()); it != varmap.end()) - return variables.at(it->second).type; - int type = tree->node->determineType(this); - varmap[tree->node.get()] = variables.size(); - variables.push_back(VarInfo{type, tree->node.get()}); - return type; - - } else { - throw zeno::Exception("bad tree object type: " + (std::string)typeid(*object).name()); - } + int type = std::visit([&] (auto const &value) -> int { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return 1; + } else if constexpr (std::is_same_v) { + return 2; + } else if constexpr (std::is_same_v) { + return 3; + } else if constexpr (std::is_same_v) { + return 4; + } else { + throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); + } + }, num->value); + constmap[num] = constants.size(); + constants.push_back(ConstInfo{type, num->value}); + return type; + + } else if (auto tree = dynamic_cast(object)) { + assert(tree->node); + if (auto it = varmap.find(tree->node.get()); it != varmap.end()) + return variables.at(it->second).type; + int type = tree->node->determineType(this); + varmap[tree->node.get()] = variables.size(); + variables.push_back(VarInfo{type, tree->node.get()}); + return type; + + } else { + throw zeno::Exception("bad tree object type: " + (std::string)typeid(*object).name()); + } } ZENO_API int EmissionPass::currentType(ShaderNode *node) const { - return variables[varmap.at(node)].type; + return variables[varmap.at(node)].type; } ZENO_API std::string EmissionPass::determineExpr(IObject *object, ShaderNode *node) const { - auto type = currentType(node); - auto expr = determineExpr(object); - duplicateIfHlsl(type, expr); - return typeNameOf(type) + "(" + expr + ")"; + auto type = currentType(node); + auto expr = determineExpr(object); + duplicateIfHlsl(type, expr); + return typeNameOf(type) + "(" + expr + ")"; } ZENO_API void EmissionPass::duplicateIfHlsl(int type, std::string &expr) const { - if (backend == HLSL && type > 1) { - /* WHY IS MICROSOFT SO STUPID? THIS IS A PROBLEM. */ - expr += " * float" + std::to_string(type) + "(1"; - auto tmp = ", 1"; - for (int i = 1; i < type; i++) - expr += tmp; - expr += ")"; - } + if (backend == HLSL && type > 1) { + /* WHY IS MICROSOFT SO STUPID? THIS IS A PROBLEM. */ + expr += " * float" + std::to_string(type) + "(1"; + auto tmp = ", 1"; + for (int i = 1; i < type; i++) + expr += tmp; + expr += ")"; + } } static const auto cihou = [] { - std::map cihou; - cihou["mix"] = "lerp"; - cihou["inversesqrt"] = "rsqrt"; - cihou["mod"] = "fmod"; - cihou["vec2"] = "float2"; - cihou["vec3"] = "float3"; - cihou["vec4"] = "float4"; - return cihou; + std::map cihou; + cihou["mix"] = "lerp"; + cihou["inversesqrt"] = "rsqrt"; + cihou["mod"] = "fmod"; + cihou["vec2"] = "float2"; + cihou["vec3"] = "float3"; + cihou["vec4"] = "float4"; + return cihou; }(); ZENO_API std::string EmissionPass::funcName(std::string const &fun) const { - if (backend == HLSL) { - if (auto it = cihou.find(fun); it != cihou.end()) - return it->second; - } - return fun; + if (backend == HLSL) { + if (auto it = cihou.find(fun); it != cihou.end()) + return it->second; + } + return fun; } ZENO_API std::string EmissionPass::addCommonFunc(EmissionPass::CommonFunc comm) { - int idx = commons.size(); - if (comm.name.empty()) - comm.name = "fun" + std::to_string(idx); - commons.push_back(std::move(comm)); - return commons.back().name; + int idx = commons.size(); + if (comm.name.empty()) + comm.name = "fun" + std::to_string(idx); + commons.push_back(std::move(comm)); + return commons.back().name; } ZENO_API std::string EmissionPass::getCommonCode() const { - std::string ret = commonCode; - for (int i = 0; i < commons.size(); i++) { - ret += "\n" + typeNameOf(commons[i].rettype) + " " + commons[i].name + commons[i].code + "\n"; - } - return ret; + std::string ret = commonCode; + for (int i = 0; i < commons.size(); i++) { + ret += "\n" + typeNameOf(commons[i].rettype) + " " + commons[i].name + commons[i].code + "\n"; + } + return ret; } ZENO_API std::string EmissionPass::typeNameOf(int type) const { - if (type == 1) return "float"; - else return (backend == HLSL ? "float" : "vec") + std::to_string(type); + if (type == 1) return "float"; + else return (backend == HLSL ? "float" : "vec") + std::to_string(type); } ZENO_API std::string EmissionPass::collectDefs() const { - std::string res; int cnt = 0; for (auto const &var: constants) { @@ -148,111 +159,88 @@ ZENO_API std::string EmissionPass::collectDefs() const { cnt++; } return res; - } ZENO_API std::string EmissionPass::collectCode() const { - std::string res; - for (auto const &line: lines) { - res += line + "\n"; - } - return res; -} - -static std::string ftos(float x) { - std::ostringstream ss; - ss << x; - return ss.str(); + std::string res; + for (auto const &line: lines) { + res += line + "\n"; + } + return res; } ZENO_API std::string EmissionPass::determineExpr(IObject *object) const { - if (auto num = dynamic_cast(object)) { - return std::visit([&] (auto const &value) -> std::string { - using T = std::decay_t; - if constexpr (std::is_same_v) { - return typeNameOf(1) + "(" + ftos(value) + ")"; - } else if constexpr (std::is_same_v) { - return typeNameOf(2) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ")"; - } else if constexpr (std::is_same_v) { - return typeNameOf(3) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ", " - + ftos(value[2]) + ")"; - } else if constexpr (std::is_same_v) { - return typeNameOf(4) + "(" + ftos(value[0]) + ", " + ftos(value[1]) + ", " - + ftos(value[2]) + ", " + ftos(value[3]) + ")"; - } else { - throw zeno::Exception("bad numeric object type: " + (std::string)typeid(T).name()); - } - }, num->value); - - } else if (auto tree = dynamic_cast(object)) { - return "tmp" + std::to_string(varmap.at(tree->node.get())); - } - return {}; + if (auto num = dynamic_cast(object)) { + return "constmp" + std::to_string(constmap.at(num)); + } else if (auto tree = dynamic_cast(object)) { + return "tmp" + std::to_string(varmap.at(tree->node.get())); + } + return {}; } ZENO_API void EmissionPass::emitCode(std::string const &line) { - int idx = lines.size(); - lines.push_back("tmp" + std::to_string(idx) + " = " + line + ";"); + int idx = lines.size(); + lines.push_back("tmp" + std::to_string(idx) + " = " + line + ";"); } ZENO_API std::string EmissionPass::finalizeCode(std::vector> const &keys, std::vector> const &vals) { - std::vector vartypes; - vartypes.reserve(keys.size()); - for (int i = 0; i < keys.size(); i++) { - int their_type = determineType(vals[i].get()); - int our_type = keys[i].first; - if (their_type != our_type && their_type != 1) - throw zeno::Exception("unexpected input for " + keys[i].second + " which requires " - + typeNameOf(our_type) + " but got " + typeNameOf(their_type)); - vartypes.push_back(their_type); - } - auto code = finalizeCode(); - for (int i = 0; i < keys.size(); i++) { - auto expr = determineExpr(vals[i].get()); - int our_type = keys[i].first; - duplicateIfHlsl(our_type, expr); - //printf("!!!!!!!!!!!!%d %s\n", our_type, expr.c_str()); - code += typeNameOf(our_type) + " " + keys[i].second + " = " + typeNameOf(our_type) + "(" + expr + ");\n"; - } - return code; + std::vector vartypes; + vartypes.reserve(keys.size()); + for (int i = 0; i < keys.size(); i++) { + int their_type = determineType(vals[i].get()); + int our_type = keys[i].first; + if (their_type != our_type && their_type != 1) + throw zeno::Exception("unexpected input for " + keys[i].second + " which requires " + + typeNameOf(our_type) + " but got " + typeNameOf(their_type)); + vartypes.push_back(their_type); + } + auto code = finalizeCode(); + for (int i = 0; i < keys.size(); i++) { + auto expr = determineExpr(vals[i].get()); + int our_type = keys[i].first; + duplicateIfHlsl(our_type, expr); + //printf("!!!!!!!!!!!!%d %s\n", our_type, expr.c_str()); + code += typeNameOf(our_type) + " " + keys[i].second + " = " + typeNameOf(our_type) + "(" + expr + ");\n"; + } + return code; } ZENO_API void EmissionPass::translateToHlsl(std::string &code) { - std::string ret; - for (auto const &[key, val]: cihou) { - size_t pos = 0, last_pos = 0; - ret.clear(); - auto isident = [] (char c) -> bool { - return ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; - }; - while ((pos = code.find(key, pos)) != std::string::npos) { - if (pos != 0 && isident(code[pos - 1])) { - pos += key.size(); - continue; - } - if (pos + key.size() != code.size() && isident(code[pos + key.size()])) { - pos += key.size(); - continue; - } - //printf("%s %s %d %d\n", key.c_str(), code.substr(pos).c_str(), last_pos, pos); - ret.append(code, last_pos, pos - last_pos); - ret.append(val); - pos += key.size(); - last_pos = pos; - } - if (!ret.empty() && last_pos != 0) { - ret.append(code, last_pos, std::string::npos); - code = std::move(ret); + std::string ret; + for (auto const &[key, val]: cihou) { + size_t pos = 0, last_pos = 0; + ret.clear(); + auto isident = [] (char c) -> bool { + return ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; + }; + while ((pos = code.find(key, pos)) != std::string::npos) { + if (pos != 0 && isident(code[pos - 1])) { + pos += key.size(); + continue; + } + if (pos + key.size() != code.size() && isident(code[pos + key.size()])) { + pos += key.size(); + continue; + } + //printf("%s %s %d %d\n", key.c_str(), code.substr(pos).c_str(), last_pos, pos); + ret.append(code, last_pos, pos - last_pos); + ret.append(val); + pos += key.size(); + last_pos = pos; + } + if (!ret.empty() && last_pos != 0) { + ret.append(code, last_pos, std::string::npos); + code = std::move(ret); + } } - } } ZENO_API void EmissionPass::translateCommonCode() { - if (backend != HLSL) return; - for (auto &comm: commons) - translateToHlsl(comm.code); - translateToHlsl(commonCode); + if (backend != HLSL) return; + for (auto &comm: commons) + translateToHlsl(comm.code); + translateToHlsl(commonCode); } } From 47db171dafdded8025b6ebb5e2dbb50aac6eedef Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Tue, 12 Dec 2023 11:35:33 +0800 Subject: [PATCH 046/106] Import Material values File --- ui/zenoedit/dialog/zforksubgrapdlg.h | 7 +- ui/zenoedit/dialog/zforksubgraphdlg.cpp | 119 ++++++++++++++++++------ 2 files changed, 94 insertions(+), 32 deletions(-) diff --git a/ui/zenoedit/dialog/zforksubgrapdlg.h b/ui/zenoedit/dialog/zforksubgrapdlg.h index f44c30e152..187bea88b1 100644 --- a/ui/zenoedit/dialog/zforksubgrapdlg.h +++ b/ui/zenoedit/dialog/zforksubgrapdlg.h @@ -3,6 +3,7 @@ #include #include "zenoui/comctrl/dialog/zframelessdialog.h" +#include class ZForkSubgraphDlg : public ZFramelessDialog { @@ -10,13 +11,17 @@ class ZForkSubgraphDlg : public ZFramelessDialog public: ZForkSubgraphDlg(const QMap & subgs, QWidget* parent = nullptr); signals: - +private slots: + void onOkClicked(); + void onImportClicked(); private: void initUi(); private: QString m_version; QTableWidget* m_pTableWidget; QMap m_subgsMap; + QString m_importPath; + QPushButton* m_pImportBtn; }; #endif \ No newline at end of file diff --git a/ui/zenoedit/dialog/zforksubgraphdlg.cpp b/ui/zenoedit/dialog/zforksubgraphdlg.cpp index 52ff19dc5e..83d1888f9c 100644 --- a/ui/zenoedit/dialog/zforksubgraphdlg.cpp +++ b/ui/zenoedit/dialog/zforksubgraphdlg.cpp @@ -4,6 +4,9 @@ #include "zenoapplication.h" #include #include +#include +#include +#include "variantptr.h" ZForkSubgraphDlg::ZForkSubgraphDlg(const QMap& subgs, QWidget* parent) : ZFramelessDialog(parent) @@ -52,45 +55,99 @@ void ZForkSubgraphDlg::initUi() QHBoxLayout* pHLayout = new QHBoxLayout(this); QPushButton* pOkBtn = new QPushButton(tr("Ok"), this); QPushButton* pCancelBtn = new QPushButton(tr("Cancel"), this); + m_pImportBtn = new QPushButton(tr("Import Material File"), this); int width = ZenoStyle::dpiScaled(80); - pOkBtn->setFixedWidth(width); - pCancelBtn->setFixedWidth(width); + int height = ZenoStyle::dpiScaled(24); + pOkBtn->setFixedSize(width, height); + pCancelBtn->setFixedSize(width, height); + m_pImportBtn->setFixedHeight(height); + pHLayout->addWidget(m_pImportBtn); pHLayout->addStretch(); pHLayout->addWidget(pOkBtn); pHLayout->addWidget(pCancelBtn); pLayout->addLayout(pHLayout); this->setMainWidget(pWidget); - connect(pOkBtn, &QPushButton::clicked, this, [=]() { - int count = m_pTableWidget->rowCount(); - int rowNum = qSqrt(count); - int colunmNum = count / (rowNum > 0 ? rowNum : 1); - QPointF pos; - for (int row = 0; row < count; row++) + connect(pOkBtn, &QPushButton::clicked, this, &ZForkSubgraphDlg::onOkClicked); + connect(pCancelBtn, &QPushButton::clicked, this, &ZForkSubgraphDlg::reject); + connect(m_pImportBtn, &QPushButton::clicked, this, &ZForkSubgraphDlg::onImportClicked); +} + +void ZForkSubgraphDlg::onImportClicked() +{ + m_importPath = QFileDialog::getOpenFileName(nullptr, "File to Open", "", "All Files(*);;"); + QStringList strLst = m_importPath.split("/"); + if (!strLst.isEmpty()) + m_pImportBtn->setText(tr("Material File: ") + strLst.last()); +} + +void ZForkSubgraphDlg::onOkClicked() +{ + int count = m_pTableWidget->rowCount(); + int rowNum = qSqrt(count); + int colunmNum = count / (rowNum > 0 ? rowNum : 1); + QPointF pos; + for (int row = 0; row < count; row++) + { + QString subgName = m_pTableWidget->item(row, 0)->data(Qt::DisplayRole).toString(); + QString name = m_pTableWidget->item(row, 1)->data(Qt::DisplayRole).toString(); + QString mtlid = m_pTableWidget->item(row, 2)->data(Qt::DisplayRole).toString(); + QString old_mtlid = m_pTableWidget->item(row, 2)->data(Qt::UserRole).toString(); + IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + const QModelIndex& index = pGraphsModel->forkMaterial(pGraphsModel->index(subgName), name, mtlid, old_mtlid); + if (!index.isValid()) { - QString subgName = m_pTableWidget->item(row, 0)->data(Qt::DisplayRole).toString(); - QString name = m_pTableWidget->item(row, 1)->data(Qt::DisplayRole).toString(); - QString mtlid = m_pTableWidget->item(row, 2)->data(Qt::DisplayRole).toString(); - QString old_mtlid = m_pTableWidget->item(row, 2)->data(Qt::UserRole).toString(); - IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); - const QModelIndex& index = pGraphsModel->forkMaterial(pGraphsModel->index(subgName), name, mtlid, old_mtlid); - if (!index.isValid()) - { - QMessageBox::warning(this, tr("warring"), tr("fork preset subgraph '%1' failed.").arg(name)); - } - if (row > 0) - { - int currC = row / rowNum; - int currR = row % rowNum; - QPointF newPos(pos.x() + currC * 600, pos.y() + currR * 600); - pGraphsModel->ModelSetData(index, newPos, ROLE_OBJPOS); - } - else + QMessageBox::warning(this, tr("warring"), tr("fork preset subgraph '%1' failed.").arg(name)); + continue; + } + if (row > 0) + { + int currC = row / rowNum; + int currR = row % rowNum; + QPointF newPos(pos.x() + currC * 600, pos.y() + currR * 600); + pGraphsModel->ModelSetData(index, newPos, ROLE_OBJPOS); + } + else + { + pos = index.data(ROLE_OBJPOS).toPointF(); + } + + QFile file(m_importPath); + bool ret = file.open(QIODevice::ReadOnly | QIODevice::Text); + if (!ret) { + zeno::log_error("cannot open file: {} ({})", m_importPath.toStdString(), + file.errorString().toStdString()); + return; + } + + rapidjson::Document doc; + QByteArray bytes = file.readAll(); + doc.Parse(bytes); + + if (!doc.IsObject()) + { + zeno::log_error("json file is corrupted"); + return; + } + auto jsonObject = doc.GetObject(); + + if (jsonObject.HasMember(mtlid.toUtf8())) + { + const auto& objVal = jsonObject[mtlid.toStdString().c_str()]; + NodeParamModel* nodeParams = QVariantPtr::asPtr(index.data(ROLE_NODE_PARAMS)); + if (nodeParams) { - pos = index.data(ROLE_OBJPOS).toPointF(); + for (const auto& inputIdx : nodeParams->getInputIndice()) + { + QString name = inputIdx.data(ROLE_PARAM_NAME).toString(); + if (objVal.HasMember(name.toUtf8())) + { + QVariant val = UiHelper::parseJson(objVal[name.toStdString().c_str()]); + pGraphsModel->ModelSetData(inputIdx, val, ROLE_PARAM_VALUE); + } + } } } - accept(); - }); - connect(pCancelBtn, &QPushButton::clicked, this, &ZForkSubgraphDlg::reject); -} \ No newline at end of file + } + accept(); +} \ No newline at end of file From 2e475299827fda0c8bcb58527452e4a4a8225bc5 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Tue, 12 Dec 2023 12:33:20 +0800 Subject: [PATCH 047/106] improve abc --- projects/Alembic/ReadAlembic.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index 39951c34dd..730b644eae 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -99,9 +99,15 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp attr[i] = data[i]; } } + else if (prim->loops.size() * 3 == data.size()) { + auto &attr = prim->loops.add_attr(p.getName()); + for (auto i = 0; i < prim->loops.size(); i++) { + attr[i] = { data[ 3 * i], data[3 * i + 1], data[3 * i + 2]}; + } + } else { if (!read_done) { - log_error("[alembic] can not load float attr {}: {}. Check if link to Points channel when exported from Houdini.", p.getName(), data.size()); + log_warn("[alembic] can not load float attr {}: {}.", p.getName(), data.size()); } } } @@ -138,7 +144,7 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp } else { if (!read_done) { - log_error("[alembic] can not load int attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + log_warn("[alembic] can not load int attr {}:{}.", p.getName(), data.size()); } } } @@ -171,7 +177,7 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp } else { if (!read_done) { - log_error("[alembic] can not load vec3f attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + log_warn("[alembic] can not load vec3f attr {}:{}.", p.getName(), int(samp.getVals()->size())); } } } @@ -204,7 +210,7 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp } else { if (!read_done) { - log_error("[alembic] can not load N3f attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + log_warn("[alembic] can not load N3f attr {}:{}.", p.getName(), int(samp.getVals()->size())); } } } @@ -237,13 +243,13 @@ static void read_attributes(std::shared_ptr prim, ICompoundProp } else { if (!read_done) { - log_error("[alembic] can not load C3f attr {}. Check if link to Points channel when exported from Houdini.", p.getName()); + log_warn("[alembic] can not load C3f attr {}:{}.", p.getName(), int(samp.getVals()->size())); } } } else { if (!read_done) { - log_error("[alembic] can not load attr {}..", p.getName()); + log_warn("[alembic] can not load attr {}..", p.getName()); } } } @@ -312,7 +318,7 @@ static void read_user_data(std::shared_ptr prim, ICompoundPrope } else { if (!read_done) { - log_error("[alembic] can not load user data {}..", p.getName()); + log_warn("[alembic] can not load user data {}..", p.getName()); } } } From c5446619114bbc6067fdcb6ba53e73f76b7ba472 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Tue, 12 Dec 2023 13:59:15 +0800 Subject: [PATCH 048/106] fix --- projects/Alembic/ReadAlembic.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/projects/Alembic/ReadAlembic.cpp b/projects/Alembic/ReadAlembic.cpp index 730b644eae..320c298185 100644 --- a/projects/Alembic/ReadAlembic.cpp +++ b/projects/Alembic/ReadAlembic.cpp @@ -748,6 +748,7 @@ void traverseABC( tree.prim = foundABCPoints(points_sch, frameid, read_done); tree.prim->userData().set2("_abc_name", obj.getName()); tree.prim->userData().set2("_abc_path", path); + tree.prim->userData().set2("faceset_count", 0); } else if(Alembic::AbcGeom::ICurvesSchema::matches(md)) { if (!read_done) { log_debug("[alembic] found curves [{}]", obj.getName()); @@ -757,6 +758,7 @@ void traverseABC( tree.prim = foundABCCurves(curves_sch, frameid, read_done); tree.prim->userData().set2("_abc_name", obj.getName()); tree.prim->userData().set2("_abc_path", path); + tree.prim->userData().set2("faceset_count", 0); } else if (Alembic::AbcGeom::ISubDSchema::matches(md)) { if (!read_done) { log_debug("[alembic] found SubD [{}]", obj.getName()); From 1abe3019c581ac4010057a49bf32672502c27714 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Tue, 12 Dec 2023 14:39:35 +0800 Subject: [PATCH 049/106] final resolve sss small bugs --- zenovis/xinxinoptix/DeflMatShader.cu | 10 ++++----- zenovis/xinxinoptix/DisneyBSDF.h | 33 ++++++++++++++-------------- zenovis/xinxinoptix/Sampling.h | 6 ++--- zenovis/xinxinoptix/TraceStuff.h | 10 +++++++-- 4 files changed, 33 insertions(+), 26 deletions(-) diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index f1b91025c7..39662f612a 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -482,18 +482,18 @@ extern "C" __global__ void __closesthit__radiance() float3 _vertices_[3]; optixGetTriangleVertexData( gas, primIdx, sbtGASIndex, 0, _vertices_); - const float3& v0 = _vertices_[0]; - const float3& v1 = _vertices_[1]; - const float3& v2 = _vertices_[2]; + const float3& v0 = optixTransformPointFromObjectToWorldSpace(_vertices_[0]); + const float3& v1 = optixTransformPointFromObjectToWorldSpace(_vertices_[1]); + const float3& v2 = optixTransformPointFromObjectToWorldSpace(_vertices_[2]); /* MODMA */ float2 barys = optixGetTriangleBarycentrics(); auto P_Local = interp(barys, v0, v1, v2); - P = optixTransformPointFromObjectToWorldSpace(P_Local); // this value has precision issue for big float + P = P_Local; // this value has precision issue for big float attrs.pos = P; - float3 N_Local = normalize( cross( normalize(v1-v0), normalize(v2-v1) ) ); // this value has precision issue for big float + float3 N_Local = normalize( cross( normalize(_vertices_[1]-_vertices_[0]), normalize(_vertices_[2]-_vertices_[1]) ) ); // this value has precision issue for big float float3 N_World = normalize(optixTransformNormalFromObjectToWorldSpace(N_Local)); if (isBadVector(N_World)) diff --git a/zenovis/xinxinoptix/DisneyBSDF.h b/zenovis/xinxinoptix/DisneyBSDF.h index a23d1e0d76..f93fec323a 100644 --- a/zenovis/xinxinoptix/DisneyBSDF.h +++ b/zenovis/xinxinoptix/DisneyBSDF.h @@ -413,7 +413,7 @@ namespace DisneyBSDF{ } if((sssPr>0.0&&reflectance) || (sssPr>0.0 && dot(wo, N2)<0.0)) { - bool trans = dot(wo, N2) * dot(wi, N2)<0; + bool trans = (dot(wi, N2) * dot(wo, N2)<0) && (wi.z * wo.z<0); float FL = BRDFBasics::SchlickWeight(abs(wi.z)); float FV = BRDFBasics::SchlickWeight(abs(wo.z)); float term = wo.z>0?FV:FL; @@ -629,21 +629,8 @@ namespace DisneyBSDF{ //go inside wi = -BRDFBasics::UniformSampleHemisphere(r1, r2); - - } - } - - tbn.inverse_transform(wi); - wi = normalize(wi); - - bool sameside2 = (dot(wi, N) * dot(wi, N2)) > 0.0f; - if (sameside == false) { - wi = normalize(wi - 1.01f * dot(wi, N2) * N2); - } - auto woo = wo; - tbn.inverse_transform(woo); - if(dot(wi, N2) * dot(woo, N2)<0 && dot(wi, N2)<0) { - + wi.z = min(-0.2f, wi.z); + wi = normalize(wi); isSS = true; flag = transmissionEvent; vec3 color = mix(mat.basecolor, mat.sssColor, mat.subsurface); @@ -656,6 +643,20 @@ namespace DisneyBSDF{ CalculateExtinction2(color, sssRadius, prd->sigma_t, prd->ss_alpha, 1.4f); } + + } + } + + tbn.inverse_transform(wi); + wi = normalize(wi); + + bool sameside2 = (dot(wi, N) * dot(wi, N2)) > 0.0f; + if (sameside == false) { + wi = normalize(wi - 1.01f * dot(wi, N2) * N2); + } + if(dot(wi, N2)>0) + { + isSS = false; } //reflectance = vec3(1.0f) * M_PIf ; //return true; diff --git a/zenovis/xinxinoptix/Sampling.h b/zenovis/xinxinoptix/Sampling.h index f186bea0f6..2a76f7a28d 100644 --- a/zenovis/xinxinoptix/Sampling.h +++ b/zenovis/xinxinoptix/Sampling.h @@ -194,9 +194,9 @@ inline Vector3f GramSchmidt(Vector3f v, Vector3f w) { namespace rtgems { - constexpr float origin() { return 1.0f / 16.0f; } - constexpr float int_scale() { return 3.0f * 256.0f; } - constexpr float float_scale() { return 3.0f / 65536.0f; } + constexpr float origin() { return 1.0f / 32.0f; } + constexpr float int_scale() { return 1.0f * 256.0f; } + constexpr float float_scale() { return 1.0f / 65536.0f; } // Normal points outward for rays exiting the surface, else is flipped. static __inline__ __device__ float3 offset_ray(const float3 p, const float3 n) diff --git a/zenovis/xinxinoptix/TraceStuff.h b/zenovis/xinxinoptix/TraceStuff.h index e29f3068a6..c8306a1454 100644 --- a/zenovis/xinxinoptix/TraceStuff.h +++ b/zenovis/xinxinoptix/TraceStuff.h @@ -132,11 +132,17 @@ struct RadiancePRD } void offsetUpdateRay(float3& P, float3 new_dir) { - auto beforeOffset = P - this->camPos; + double x = (double)(P.x) - (double)(this->camPos.x); + double y = (double)(P.y) - (double)(this->camPos.y); + double z = (double)(P.z) - (double)(this->camPos.z); + auto beforeOffset = make_float3(x, y, z); //this->origin = P; this->direction = new_dir; offsetRay(beforeOffset, new_dir); - this->origin = beforeOffset + this->camPos; + double x2 = (double)(beforeOffset.x) + (double)(this->camPos.x); + double y2 = (double)(beforeOffset.y) + (double)(this->camPos.y); + double z2 = (double)(beforeOffset.z) + (double)(this->camPos.z); + this->origin = make_float3(x2, y2, z2); } uint8_t _mask_ = EverythingMask; From a38c588fb5fdc58e2eee5cdc5b14f3113dd0d8cc Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Tue, 12 Dec 2023 14:39:37 +0800 Subject: [PATCH 050/106] fix bug about material subgraphs --- ui/zenoedit/dialog/zforksubgraphdlg.cpp | 19 +++++++++++--- ui/zenoedit/nodesview/zenographseditor.cpp | 26 +++++++++---------- .../nodesview/zsubnetlistitemdelegate.cpp | 6 +++++ ui/zenoedit/nodesys/zenonode.cpp | 2 +- ui/zenoedit/panel/zenospreadsheet.cpp | 11 +++++++- ui/zenoedit/settings/zenosettingsmanager.cpp | 2 +- ui/zenomodel/include/igraphsmodel.h | 4 +-- ui/zenomodel/src/graphsmodel.cpp | 8 +++--- ui/zenomodel/src/graphsmodel.h | 4 +-- 9 files changed, 54 insertions(+), 28 deletions(-) diff --git a/ui/zenoedit/dialog/zforksubgraphdlg.cpp b/ui/zenoedit/dialog/zforksubgraphdlg.cpp index 83d1888f9c..05f27cb62a 100644 --- a/ui/zenoedit/dialog/zforksubgraphdlg.cpp +++ b/ui/zenoedit/dialog/zforksubgraphdlg.cpp @@ -7,6 +7,9 @@ #include #include #include "variantptr.h" +#include "nodesview/zenographseditor.h" +#include "nodesys/zenosubgraphscene.h" +#include "zenomainwindow.h" ZForkSubgraphDlg::ZForkSubgraphDlg(const QMap& subgs, QWidget* parent) : ZFramelessDialog(parent) @@ -83,6 +86,14 @@ void ZForkSubgraphDlg::onImportClicked() void ZForkSubgraphDlg::onOkClicked() { + ZenoMainWindow* pWin = zenoApp->getMainWindow(); + ZASSERT_EXIT(pWin); + ZenoGraphsEditor* pEditor = pWin->getAnyEditor(); + ZASSERT_EXIT(pEditor); + ZenoSubGraphView* pView = pEditor->getCurrentSubGraphView(); + ZASSERT_EXIT(pView); + auto sugIdx = pView->scene()->subGraphIndex(); + ZASSERT_EXIT(sugIdx.isValid()); int count = m_pTableWidget->rowCount(); int rowNum = qSqrt(count); int colunmNum = count / (rowNum > 0 ? rowNum : 1); @@ -94,7 +105,7 @@ void ZForkSubgraphDlg::onOkClicked() QString mtlid = m_pTableWidget->item(row, 2)->data(Qt::DisplayRole).toString(); QString old_mtlid = m_pTableWidget->item(row, 2)->data(Qt::UserRole).toString(); IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); - const QModelIndex& index = pGraphsModel->forkMaterial(pGraphsModel->index(subgName), name, mtlid, old_mtlid); + const QModelIndex& index = pGraphsModel->forkMaterial(sugIdx, pGraphsModel->index(subgName), name, mtlid, old_mtlid); if (!index.isValid()) { QMessageBox::warning(this, tr("warring"), tr("fork preset subgraph '%1' failed.").arg(name)); @@ -112,12 +123,14 @@ void ZForkSubgraphDlg::onOkClicked() pos = index.data(ROLE_OBJPOS).toPointF(); } + if (m_importPath.isEmpty()) + continue; QFile file(m_importPath); bool ret = file.open(QIODevice::ReadOnly | QIODevice::Text); if (!ret) { zeno::log_error("cannot open file: {} ({})", m_importPath.toStdString(), file.errorString().toStdString()); - return; + continue; } rapidjson::Document doc; @@ -127,7 +140,7 @@ void ZForkSubgraphDlg::onOkClicked() if (!doc.IsObject()) { zeno::log_error("json file is corrupted"); - return; + continue; } auto jsonObject = doc.GetObject(); diff --git a/ui/zenoedit/nodesview/zenographseditor.cpp b/ui/zenoedit/nodesview/zenographseditor.cpp index 56e842e53d..13ab25bb70 100644 --- a/ui/zenoedit/nodesview/zenographseditor.cpp +++ b/ui/zenoedit/nodesview/zenographseditor.cpp @@ -125,7 +125,7 @@ void ZenoGraphsEditor::initSignals() connect(m_ui->graphsViewTab, &QTabWidget::currentChanged, this, [=](int index) { if (m_ui->graphsViewTab->tabText(index).compare("main", Qt::CaseInsensitive) == 0) { - ZenoSettingsManager::GetInstance().setValue(zsSubgraphType, SUBGRAPH_NOR); + closeMaterialTab(); } }); connect(m_ui->searchEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onSearchEdited(const QString&))); @@ -137,6 +137,16 @@ void ZenoGraphsEditor::initSignals() ZenoSettingsManager::GetInstance().setValue("zencache-enable", true); } + connect(&ZenoSettingsManager::GetInstance(), &ZenoSettingsManager::valueChanged, this, [=](QString zsName) { + if (zsName == zsSubgraphType) + { + int type = ZenoSettingsManager::GetInstance().getValue(zsName).toInt(); + m_ui->label->setText(type == SUBGRAPH_TYPE::SUBGRAPH_NOR ? tr("Subnet") : type == SUBGRAPH_TYPE::SUBGRAPH_METERIAL ? tr("Material Subnet") : tr("Preset Subnet")); + if (type != SUBGRAPH_METERIAL) + closeMaterialTab(); + } + }); + //m_selection->setCurrentIndex(m_sideBarModel->index(0, 0), QItemSelectionModel::SelectCurrent); } @@ -189,18 +199,8 @@ void ZenoGraphsEditor::resetModel(IGraphsModel* pModel) connect(pModel, &IGraphsModel::modelClear, this, &ZenoGraphsEditor::onModelCleared); connect(pModel, SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)), this, SLOT(onSubGraphsToRemove(const QModelIndex&, int, int))); connect(pModel, SIGNAL(modelReset()), this, SLOT(onModelReset())); - connect(pModel, SIGNAL(graphRenamed(const QString&, const QString&)), this, SLOT(onSubGraphRename(const QString&, const QString&))); - connect(&ZenoSettingsManager::GetInstance(), &ZenoSettingsManager::valueChanged, this, [=](QString zsName) { - if (zsName == zsSubgraphType) - { - proxyModel->invalidate(); - int type = ZenoSettingsManager::GetInstance().getValue(zsName).toInt(); - m_ui->label->setText(type == SUBGRAPH_TYPE::SUBGRAPH_NOR ? tr("Subnet") : type == SUBGRAPH_TYPE::SUBGRAPH_METERIAL ? tr("Material Subnet") : tr("Preset Subnet")); - if (type != SUBGRAPH_METERIAL) - closeMaterialTab(); - } - }); - activateTab("main"); + connect(pModel, SIGNAL(graphRenamed(const QString&, const QString&)), this, SLOT(onSubGraphRename(const QString&, const QString&))); + activateTab("main"); } void ZenoGraphsEditor::onModelCleared() diff --git a/ui/zenoedit/nodesview/zsubnetlistitemdelegate.cpp b/ui/zenoedit/nodesview/zsubnetlistitemdelegate.cpp index c7e16aeb29..8eafbf5a70 100644 --- a/ui/zenoedit/nodesview/zsubnetlistitemdelegate.cpp +++ b/ui/zenoedit/nodesview/zsubnetlistitemdelegate.cpp @@ -273,6 +273,12 @@ void ZSubnetListItemDelegate::setSelectedIndexs(const QModelIndexList &list) SubListSortProxyModel::SubListSortProxyModel(QObject* parent) : QSortFilterProxyModel(parent) { + connect(&ZenoSettingsManager::GetInstance(), &ZenoSettingsManager::valueChanged, this, [=](QString zsName) { + if (zsName == zsSubgraphType) + { + invalidate(); + } + }); } bool SubListSortProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const diff --git a/ui/zenoedit/nodesys/zenonode.cpp b/ui/zenoedit/nodesys/zenonode.cpp index 0fb419e4f8..82dd24eecc 100644 --- a/ui/zenoedit/nodesys/zenonode.cpp +++ b/ui/zenoedit/nodesys/zenonode.cpp @@ -1617,7 +1617,7 @@ void ZenoNode::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) const auto& paramIdx = pNodeParams->getParam(PARAM_INPUT, "mtlid"); ZASSERT_EXIT(paramIdx.isValid()); QString mtlid = paramIdx.data(ROLE_PARAM_VALUE).toString(); - if (!pGraphsModel->newMaterialSubgraph(mtlid, this->pos() + QPointF(800, 0))) + if (!pGraphsModel->newMaterialSubgraph(m_subGpIndex, mtlid, this->pos() + QPointF(800, 0))) QMessageBox::warning(nullptr, tr("Info"), tr("Create material subgraph '%1' failed.").arg(mtlid)); }); QMenu *nodeMenu = new QMenu; diff --git a/ui/zenoedit/panel/zenospreadsheet.cpp b/ui/zenoedit/panel/zenospreadsheet.cpp index a408b17a32..c00b413c45 100644 --- a/ui/zenoedit/panel/zenospreadsheet.cpp +++ b/ui/zenoedit/panel/zenospreadsheet.cpp @@ -16,6 +16,7 @@ #include "dialog/zforksubgrapdlg.h" #include "nodesview/zenographseditor.h" #include "settings/zenosettingsmanager.h" +#include "nodesys/zenosubgraphscene.h" ZenoSpreadsheet::ZenoSpreadsheet(QWidget *parent) : QWidget(parent) { dataModel = new PrimAttrTableModel(); @@ -244,9 +245,17 @@ bool ZenoSpreadsheet::eventFilter(QObject* watched, QEvent* event) } connect(newSubGraph, &QAction::triggered, this, [=]() { + ZenoMainWindow* pWin = zenoApp->getMainWindow(); + ZASSERT_EXIT(pWin); + ZenoGraphsEditor* pEditor = pWin->getAnyEditor(); + ZASSERT_EXIT(pEditor); + ZenoSubGraphView* pView = pEditor->getCurrentSubGraphView(); + ZASSERT_EXIT(pView); + auto sugIdx = pView->scene()->subGraphIndex(); + ZASSERT_EXIT(sugIdx.isValid()); for (const auto& mtlid : matLst) { - if (!pGraphsModel->newMaterialSubgraph(mtlid, QPointF(800, 0))) + if (!pGraphsModel->newMaterialSubgraph(sugIdx, mtlid, QPointF(800, 0))) QMessageBox::warning(nullptr, tr("Info"), tr("Create material subgraph '%1' failed.").arg(mtlid)); } }); diff --git a/ui/zenoedit/settings/zenosettingsmanager.cpp b/ui/zenoedit/settings/zenosettingsmanager.cpp index 41aeadcabd..11a2753453 100644 --- a/ui/zenoedit/settings/zenosettingsmanager.cpp +++ b/ui/zenoedit/settings/zenosettingsmanager.cpp @@ -24,7 +24,7 @@ ZenoSettingsManager::ZenoSettingsManager(QObject *parent) : bool ZenoSettingsManager::setValue(const QString& name, const QVariant& value) { - if (zsSubgraphType == name) + if (zsSubgraphType == name && value != m_settings[name]) { m_settings[name] = value; emit valueChanged(name); diff --git a/ui/zenomodel/include/igraphsmodel.h b/ui/zenomodel/include/igraphsmodel.h index 3ce6312731..c73fec781a 100644 --- a/ui/zenomodel/include/igraphsmodel.h +++ b/ui/zenomodel/include/igraphsmodel.h @@ -56,7 +56,7 @@ class IGraphsModel : public QAbstractItemModel fork subnet node indexed by subnetNodeIdx under subgIdx. */ virtual QModelIndex fork(const QModelIndex& subgIdx, const QModelIndex& subnetNodeIdx) = 0; - virtual QModelIndex forkMaterial(const QModelIndex& subnetNodeIdx, const QString& subgName, const QString& mtlid, const QString& mtlid_old) = 0; + virtual QModelIndex forkMaterial(const QModelIndex& subgIdx, const QModelIndex& subnetNodeIdx, const QString& subgName, const QString& mtlid, const QString& mtlid_old) = 0; virtual void updateParamInfo(const QString& id, PARAM_UPDATE_INFO info, const QModelIndex& subGpIdx, bool enableTransaction = false) = 0; virtual void updateSocketDefl(const QString& id, PARAM_UPDATE_INFO info, const QModelIndex& subGpIdx, bool enableTransaction = false) = 0; @@ -76,7 +76,7 @@ class IGraphsModel : public QAbstractItemModel virtual void redo() = 0; virtual void switchSubGraph(const QString& graphName) {} virtual void newSubgraph(const QString& graphName, SUBGRAPH_TYPE type = SUBGRAPH_TYPE::SUBGRAPH_NOR) = 0; - virtual bool newMaterialSubgraph(const QString& graphName, const QPointF& pos) = 0; + virtual bool newMaterialSubgraph(const QModelIndex& subgIdx, const QString& graphName, const QPointF& pos) = 0; virtual void initMainGraph() = 0; virtual void renameSubGraph(const QString& oldName, const QString& newName) = 0; virtual bool isDirty() const = 0; diff --git a/ui/zenomodel/src/graphsmodel.cpp b/ui/zenomodel/src/graphsmodel.cpp index 4114b6c2b3..3bf8a0a874 100644 --- a/ui/zenomodel/src/graphsmodel.cpp +++ b/ui/zenomodel/src/graphsmodel.cpp @@ -120,7 +120,7 @@ void GraphsModel::newSubgraph(const QString &graphName, SUBGRAPH_TYPE type) } } -bool GraphsModel::newMaterialSubgraph(const QString& graphName, const QPointF& pos) +bool GraphsModel::newMaterialSubgraph(const QModelIndex & currentSubIdx, const QString& graphName, const QPointF& pos) { if (subGraph(graphName)) { @@ -129,7 +129,6 @@ bool GraphsModel::newMaterialSubgraph(const QString& graphName, const QPointF& p } beginTransaction("extract a new graph"); - int currentRow = m_selection->currentIndex().row(); //first, new the target subgraph newSubgraph(graphName, SUBGRAPH_TYPE::SUBGRAPH_METERIAL); QModelIndex subgIdx = index(graphName); @@ -155,7 +154,6 @@ bool GraphsModel::newMaterialSubgraph(const QString& graphName, const QPointF& p link.outSockPath = inParam.data(ROLE_OBJPATH).toString(); addLink(subgIdx, link, false); //add material subgraph node - QModelIndex currentSubIdx = index(currentRow, 0); const QString& subIdent = NodesMgr::createNewNode(this, currentSubIdx, graphName, pos); auto subgNodeIdx = nodeIndex(subIdent); QVariant newValue = OPT_VIEW; @@ -857,13 +855,13 @@ QModelIndex GraphsModel::fork(const QModelIndex& subgIdx, const QModelIndex &sub return newForkNodeIdx; } -QModelIndex GraphsModel::forkMaterial(const QModelIndex& subnetNodeIdx, const QString& subgName, const QString& mtlid, const QString& mtlid_old) +QModelIndex GraphsModel::forkMaterial(const QModelIndex& currSubgIdx, const QModelIndex& subnetNodeIdx, const QString& subgName, const QString& mtlid, const QString& mtlid_old) { if (subGraph(subgName)) return QModelIndex(); if (!subnetNodeIdx.isValid()) return QModelIndex(); - QModelIndex index = fork(m_selection->currentIndex(), subnetNodeIdx); + QModelIndex index = fork(currSubgIdx, subnetNodeIdx); ModelSetData(index, OPT_VIEW, ROLE_OPTIONS); QString name = index.data(ROLE_OBJNAME).toString(); diff --git a/ui/zenomodel/src/graphsmodel.h b/ui/zenomodel/src/graphsmodel.h index cece0ea4d1..cd3dbb14dc 100644 --- a/ui/zenomodel/src/graphsmodel.h +++ b/ui/zenomodel/src/graphsmodel.h @@ -33,7 +33,7 @@ class GraphsModel : public IGraphsModel SubGraphModel *currentGraph(); void switchSubGraph(const QString& graphName) override; void newSubgraph(const QString& graphName, SUBGRAPH_TYPE type = SUBGRAPH_TYPE::SUBGRAPH_NOR) override; - bool newMaterialSubgraph(const QString& graphName, const QPointF& pos) override; + bool newMaterialSubgraph(const QModelIndex& subgIdx, const QString& graphName, const QPointF& pos) override; void initMainGraph() override; void renameSubGraph(const QString& oldName, const QString& newName) override; QItemSelectionModel* selectionModel() const; @@ -44,7 +44,7 @@ class GraphsModel : public IGraphsModel //NODE_DESC void appendSubGraph(SubGraphModel* pGraph); QModelIndex fork(const QModelIndex& subgIdx, const QModelIndex& subnetNodeIdx) override; - QModelIndex forkMaterial(const QModelIndex& subnetNodeIdx, const QString&subgName, const QString& mtlid, const QString& mtlid_old) override; + QModelIndex forkMaterial(const QModelIndex& subgIdx, const QModelIndex& subnetNodeIdx, const QString&subgName, const QString& mtlid, const QString& mtlid_old) override; void removeGraph(int idx) override; bool isDirty() const override; void markDirty() override; From e666ddbec0b4c15aa2027f1d346169da10bd94bb Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Tue, 12 Dec 2023 15:22:29 +0800 Subject: [PATCH 051/106] abc list --- projects/Alembic/GetAlembicPrim.cpp | 38 +++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/projects/Alembic/GetAlembicPrim.cpp b/projects/Alembic/GetAlembicPrim.cpp index 4aa160ab3a..573f97f808 100644 --- a/projects/Alembic/GetAlembicPrim.cpp +++ b/projects/Alembic/GetAlembicPrim.cpp @@ -230,6 +230,44 @@ ZENDEFNODE(AllAlembicPrim, { {"alembic"}, }); +struct AlembicPrimList : INode { + virtual void apply() override { + auto abctree = get_input("abctree"); + auto prims = std::make_shared(); + int use_xform = get_input2("use_xform"); + if (use_xform) { + prims = get_xformed_prims(abctree); + } else { + abctree->visitPrims([&] (auto const &p) { + auto np = std::static_pointer_cast(p->clone()); + prims->arr.push_back(np); + }); + } + for (auto &prim: prims->arr) { + auto _prim = std::dynamic_pointer_cast(prim); + if (get_input2("flipFrontBack")) { + flipFrontBack(_prim); + } + if (get_input2("triangulate") == 1) { + zeno::primTriangulate(_prim.get()); + } + } + set_output("prims", std::move(prims)); + } +}; + +ZENDEFNODE(AlembicPrimList, { + { + {"bool", "flipFrontBack", "1"}, + {"ABCTree", "abctree"}, + {"bool", "use_xform", "0"}, + {"bool", "triangulate", "0"}, + }, + {"prims"}, + {}, + {"alembic"}, +}); + struct GetAlembicCamera : INode { virtual void apply() override { auto abctree = get_input("abctree"); From 47cb3d3dd45a2a4838991f162f9adefd9f4eeffa Mon Sep 17 00:00:00 2001 From: iaomw Date: Tue, 12 Dec 2023 18:43:35 +0800 Subject: [PATCH 052/106] DirtyTBN --- projects/FBX/MayaCamera.cpp | 57 +++++++++++++++++++++++++++ zenovis/src/optx/RenderEngineOptx.cpp | 4 +- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/projects/FBX/MayaCamera.cpp b/projects/FBX/MayaCamera.cpp index 1d7e74ad62..1257676f3c 100644 --- a/projects/FBX/MayaCamera.cpp +++ b/projects/FBX/MayaCamera.cpp @@ -514,6 +514,63 @@ ZENO_DEFNODE(LightNode)({ {"shader"}, }); +struct DirtyTBN : INode { + virtual void apply() override { + + auto AxisT = get_input2("T"); + auto AxisB = get_input2("B"); + //auto AxisN = get_input2("N"); + + if (lengthSquared(AxisT) == 0 ) { + AxisT = {1,0,0}; + } + AxisT = zeno::normalize(AxisT); + + if (lengthSquared(AxisB) == 0 ) { + AxisB = {0,0,1}; + } + AxisB = zeno::normalize(AxisB); + + auto tmp = zeno::dot(AxisT, AxisB); + if (abs(tmp) > 0.0) { // not vertical + AxisB -= AxisT * tmp; + AxisB = zeno::normalize(AxisB); + } + + if (has_input("prim")) { + auto prim = get_input("prim"); + + auto pos = prim->userData().get2("pos", {0,0,0}); + auto scale = prim->userData().get2("scale", {1,1,1}); + + auto v0 = pos - AxisT * scale[0] * 0.5f - AxisB * scale[2] * 0.5f; + auto e1 = AxisT * scale[0]; + auto e2 = AxisB * scale[2]; + + prim->verts[0] = v0 + e1 + e2; + prim->verts[1] = v0 + e1; + prim->verts[2] = v0 + e2; + prim->verts[3] = v0; + + set_output("prim", std::move(prim)); + } + } +}; + + +ZENO_DEFNODE(DirtyTBN)({ + { + {"PrimitiveObject", "prim"}, + {"vec3f", "T", "1, 0, 0"}, + {"vec3f", "B", "0, 0, 1"}, + }, + { + "prim" + }, + {}, + {"shader"}, +}); + struct LiveMeshNode : INode { typedef std::vector> UVS; typedef std::vector> VERTICES; diff --git a/zenovis/src/optx/RenderEngineOptx.cpp b/zenovis/src/optx/RenderEngineOptx.cpp index f15530d18f..8558475c36 100644 --- a/zenovis/src/optx/RenderEngineOptx.cpp +++ b/zenovis/src/optx/RenderEngineOptx.cpp @@ -622,7 +622,9 @@ struct GraphicsManager { e2 = -e2; // invert e2 // facing down in local space - nor = zeno::normalize(zeno::cross(e2, e1)); + auto ne2 = zeno::normalize(e2); + auto ne1 = zeno::normalize(e1); + nor = zeno::normalize(zeno::cross(ne2, ne1)); if (ivD) { nor *= -1; } if (prim_in->verts.has_attr("clr")) { From 1a7924d88c40089e8e7715b3a71e0de787b1804d Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Tue, 12 Dec 2023 19:41:45 +0800 Subject: [PATCH 053/106] match json --- ui/zenoedit/dialog/zforksubgrapdlg.h | 3 +- ui/zenoedit/dialog/zforksubgraphdlg.cpp | 132 ++++++++++++++++++------ ui/zenoedit/panel/zenospreadsheet.cpp | 2 +- 3 files changed, 103 insertions(+), 34 deletions(-) diff --git a/ui/zenoedit/dialog/zforksubgrapdlg.h b/ui/zenoedit/dialog/zforksubgrapdlg.h index 187bea88b1..927e789b8f 100644 --- a/ui/zenoedit/dialog/zforksubgrapdlg.h +++ b/ui/zenoedit/dialog/zforksubgrapdlg.h @@ -16,10 +16,11 @@ private slots: void onImportClicked(); private: void initUi(); + QMap> readFile(); private: QString m_version; QTableWidget* m_pTableWidget; - QMap m_subgsMap; + QMap m_subgsMap; // QString m_importPath; QPushButton* m_pImportBtn; }; diff --git a/ui/zenoedit/dialog/zforksubgraphdlg.cpp b/ui/zenoedit/dialog/zforksubgraphdlg.cpp index 05f27cb62a..5ffc34df3f 100644 --- a/ui/zenoedit/dialog/zforksubgraphdlg.cpp +++ b/ui/zenoedit/dialog/zforksubgraphdlg.cpp @@ -76,6 +76,92 @@ void ZForkSubgraphDlg::initUi() connect(m_pImportBtn, &QPushButton::clicked, this, &ZForkSubgraphDlg::onImportClicked); } +QMap> ZForkSubgraphDlg::readFile() +{ + QMap> matValueMap; + QFile file(m_importPath); + bool ret = file.open(QIODevice::ReadOnly | QIODevice::Text); + if (!ret) { + zeno::log_error("cannot open file: {} ({})", m_importPath.toStdString(), + file.errorString().toStdString()); + return matValueMap; + } + rapidjson::Document doc; + QByteArray bytes = file.readAll(); + doc.Parse(bytes); + + if (!doc.IsObject()) + { + zeno::log_error("json file is corrupted"); + return matValueMap; + } + QMap> presetParamMap; // + QMap> matKeyMap; // + auto jsonObject = doc.GetObject(); + QMap> matchMap;//> + if (jsonObject.HasMember("match")) + { + const auto& objVal = jsonObject["match"]; + if (objVal.IsObject()) + { + for (auto iter = objVal.MemberBegin(); iter != objVal.MemberEnd(); iter++) { + QString matType = iter->name.GetString(); + if (iter->value.IsObject()) + { + for (auto iter1 = iter->value.MemberBegin(); iter1 != iter->value.MemberEnd(); iter1++) { + QString paramName = iter1->name.GetString(); + QString matKey = iter1->value.GetString(); + matchMap[matType][matKey] = paramName; + } + } + } + } + } + for (const auto& mtlid : m_subgsMap.keys()) + { + QString mat = m_subgsMap[mtlid]; + IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + auto subgIdx = pGraphsModel->index(mat); + if (subgIdx.isValid()) + { + //preset + QModelIndexList nodes = pGraphsModel->searchInSubgraph("SubInput", subgIdx); + for (QModelIndex subInput : nodes) + { + NodeParamModel* nodeParams = QVariantPtr::asPtr(subInput.data(ROLE_NODE_PARAMS)); + QModelIndex nameIdx = nodeParams->getParam(PARAM_PARAM, "name"); + QString paramName = nameIdx.data(ROLE_PARAM_VALUE).toString(); + presetParamMap[mat].insert(paramName); + } + } + if (jsonObject.HasMember(mtlid.toUtf8())) + { + const auto& objVal = jsonObject[mtlid.toStdString().c_str()]; + if (objVal.IsObject()) + { + for (auto iter = objVal.MemberBegin(); iter != objVal.MemberEnd(); iter++) { + matKeyMap[mat].insert(iter->name.GetString()); + QVariant val = UiHelper::parseJson(iter->value); + QString matKey = iter->name.GetString(); + if (matchMap.contains(mat)) + { + if (matchMap.contains(mat)) + { + const auto& match = matchMap[mat]; + if (match.contains(matKey)) + { + matKey = match[matKey]; + } + } + } + matValueMap[mtlid][matKey] = val; + } + } + } + } + return matValueMap; +} + void ZForkSubgraphDlg::onImportClicked() { m_importPath = QFileDialog::getOpenFileName(nullptr, "File to Open", "", "All Files(*);;"); @@ -86,6 +172,8 @@ void ZForkSubgraphDlg::onImportClicked() void ZForkSubgraphDlg::onOkClicked() { + IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + ZASSERT_EXIT(pGraphsModel); ZenoMainWindow* pWin = zenoApp->getMainWindow(); ZASSERT_EXIT(pWin); ZenoGraphsEditor* pEditor = pWin->getAnyEditor(); @@ -98,13 +186,16 @@ void ZForkSubgraphDlg::onOkClicked() int rowNum = qSqrt(count); int colunmNum = count / (rowNum > 0 ? rowNum : 1); QPointF pos; + QMap> matValueMap; + if (!m_importPath.isEmpty()) + matValueMap = readFile(); for (int row = 0; row < count; row++) { QString subgName = m_pTableWidget->item(row, 0)->data(Qt::DisplayRole).toString(); QString name = m_pTableWidget->item(row, 1)->data(Qt::DisplayRole).toString(); QString mtlid = m_pTableWidget->item(row, 2)->data(Qt::DisplayRole).toString(); QString old_mtlid = m_pTableWidget->item(row, 2)->data(Qt::UserRole).toString(); - IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); + const QModelIndex& index = pGraphsModel->forkMaterial(sugIdx, pGraphsModel->index(subgName), name, mtlid, old_mtlid); if (!index.isValid()) { @@ -123,41 +214,18 @@ void ZForkSubgraphDlg::onOkClicked() pos = index.data(ROLE_OBJPOS).toPointF(); } - if (m_importPath.isEmpty()) - continue; - QFile file(m_importPath); - bool ret = file.open(QIODevice::ReadOnly | QIODevice::Text); - if (!ret) { - zeno::log_error("cannot open file: {} ({})", m_importPath.toStdString(), - file.errorString().toStdString()); - continue; - } - - rapidjson::Document doc; - QByteArray bytes = file.readAll(); - doc.Parse(bytes); - - if (!doc.IsObject()) - { - zeno::log_error("json file is corrupted"); + if (!matValueMap.contains(old_mtlid)) continue; - } - auto jsonObject = doc.GetObject(); - - if (jsonObject.HasMember(mtlid.toUtf8())) + const auto& valueMap = matValueMap[old_mtlid]; + NodeParamModel* nodeParams = QVariantPtr::asPtr(index.data(ROLE_NODE_PARAMS)); + if (nodeParams) { - const auto& objVal = jsonObject[mtlid.toStdString().c_str()]; - NodeParamModel* nodeParams = QVariantPtr::asPtr(index.data(ROLE_NODE_PARAMS)); - if (nodeParams) + for (const auto& inputIdx : nodeParams->getInputIndice()) { - for (const auto& inputIdx : nodeParams->getInputIndice()) + QString name = inputIdx.data(ROLE_PARAM_NAME).toString(); + if (valueMap.contains(name)) { - QString name = inputIdx.data(ROLE_PARAM_NAME).toString(); - if (objVal.HasMember(name.toUtf8())) - { - QVariant val = UiHelper::parseJson(objVal[name.toStdString().c_str()]); - pGraphsModel->ModelSetData(inputIdx, val, ROLE_PARAM_VALUE); - } + pGraphsModel->ModelSetData(inputIdx, valueMap[name], ROLE_PARAM_VALUE); } } } diff --git a/ui/zenoedit/panel/zenospreadsheet.cpp b/ui/zenoedit/panel/zenospreadsheet.cpp index c00b413c45..ff3a9ac2ad 100644 --- a/ui/zenoedit/panel/zenospreadsheet.cpp +++ b/ui/zenoedit/panel/zenospreadsheet.cpp @@ -263,7 +263,7 @@ bool ZenoSpreadsheet::eventFilter(QObject* watched, QEvent* event) QMap map; for (const auto& mtlid : matLst) { - if (mtlid.contains("Cloth", Qt::CaseInsensitive)) + if (mtlid.contains("Cloth", Qt::CaseInsensitive) || mtlid.contains("Xiezi", Qt::CaseInsensitive)) { map[mtlid] = "ClothTypeMat"; } From 3b1d6eadeda143fb25a26ea0be17f028a972fb48 Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Wed, 13 Dec 2023 12:59:12 +0800 Subject: [PATCH 054/106] fix bug about switching type of subinput --- ui/zenomodel/src/nodeparammodel.cpp | 2 +- ui/zenoui/comctrl/gv/zitemfactory.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/zenomodel/src/nodeparammodel.cpp b/ui/zenomodel/src/nodeparammodel.cpp index 4fe719565b..5eb337c31b 100644 --- a/ui/zenomodel/src/nodeparammodel.cpp +++ b/ui/zenomodel/src/nodeparammodel.cpp @@ -1138,8 +1138,8 @@ void NodeParamModel::onSubIOEdited(const QVariant& oldValue, const VParamItem* p const QModelIndex& idx_defl = deflItem->index(); setData(idx_defl, newType, ROLE_PARAM_TYPE); - setData(idx_defl, newCtrl, ROLE_PARAM_CTRL); setData(idx_defl, newValue, ROLE_PARAM_VALUE); + setData(idx_defl, newCtrl, ROLE_PARAM_CTRL); //update desc. NODE_DESC desc; diff --git a/ui/zenoui/comctrl/gv/zitemfactory.cpp b/ui/zenoui/comctrl/gv/zitemfactory.cpp index 43ca80d610..31195e8907 100644 --- a/ui/zenoui/comctrl/gv/zitemfactory.cpp +++ b/ui/zenoui/comctrl/gv/zitemfactory.cpp @@ -269,7 +269,7 @@ namespace zenoui vec.resize(dim); } - ZVecEditorItem* pVecEditor = new ZVecEditorItem(value, bFloat, m_nodeParams.lineEditParam, scene); + ZVecEditorItem* pVecEditor = new ZVecEditorItem(QVariant::fromValue(vec), bFloat, m_nodeParams.lineEditParam, scene); pVecEditor->setData(GVKEY_SIZEHINT, ZenoStyle::dpiScaledSize(QSizeF(0, zenoui::g_ctrlHeight))); pVecEditor->setData(GVKEY_SIZEPOLICY, QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed)); pVecEditor->setData(GVKEY_TYPE, type); From c99e918e93374ed2a1c9b9e5b8f48824d1ab4479 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Wed, 13 Dec 2023 13:12:03 +0800 Subject: [PATCH 055/106] smart shader tex 2d bug fix --- zeno/src/nodes/mtl/ShaderTexture.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zeno/src/nodes/mtl/ShaderTexture.cpp b/zeno/src/nodes/mtl/ShaderTexture.cpp index d377434c07..a33dc65d08 100644 --- a/zeno/src/nodes/mtl/ShaderTexture.cpp +++ b/zeno/src/nodes/mtl/ShaderTexture.cpp @@ -189,21 +189,21 @@ struct SmartTexture2D : ShaderNodeClone if(!std::filesystem::exists(texture_path)){ zeno::log_warn("texture file not found!"); auto type = get_input2("type"); - auto number = get_input2("value"); + auto number = em->determineType(get_input("value").get()); if (type == "float" || type == "R") - em->emitCode(zeno::format("{}",number[0])); + em->emitCode(zeno::format("vec4({}).x",number)); else if (type == "G") - em->emitCode(zeno::format("{}",number[1])); + em->emitCode(zeno::format("vec4({}).y",number)); else if (type == "B") - em->emitCode(zeno::format("{}",number[2])); + em->emitCode(zeno::format("vec4({}).z",number)); else if (type == "A") - em->emitCode(zeno::format("{}",number[3])); + em->emitCode(zeno::format("vec4({}).w",number)); else if (type == "vec2") - em->emitCode(zeno::format("vec2({},{})",number[0],number[1])); + em->emitCode(zeno::format("vec2({})",number)); else if (type == "vec3") - em->emitCode(zeno::format("vec3({},{},{})",number[0],number[1],number[2])); + em->emitCode(zeno::format("vec3({})",number)); else if (type == "vec4") - em->emitCode(zeno::format("vec3({},{},{},{})",number[0],number[1],number[2],number[4])); + em->emitCode(zeno::format("vec4({})",number)); else throw zeno::Exception("ShaderTexture2D got bad type: " + type); From e7bee21d03628c87e1427151658c77c4df37fa8d Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Wed, 13 Dec 2023 14:29:18 +0800 Subject: [PATCH 056/106] shaderTexture default value bug fix --- zeno/src/nodes/mtl/ShaderTexture.cpp | 42 ++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/zeno/src/nodes/mtl/ShaderTexture.cpp b/zeno/src/nodes/mtl/ShaderTexture.cpp index a33dc65d08..3165aafc1a 100644 --- a/zeno/src/nodes/mtl/ShaderTexture.cpp +++ b/zeno/src/nodes/mtl/ShaderTexture.cpp @@ -189,21 +189,47 @@ struct SmartTexture2D : ShaderNodeClone if(!std::filesystem::exists(texture_path)){ zeno::log_warn("texture file not found!"); auto type = get_input2("type"); - auto number = em->determineType(get_input("value").get()); + vec4f number= vec4f(0,0,0,0); + if(has_input2("value")) + { + number[0] = get_input2("value"); + } + if(has_input2("value")) + { + auto in = get_input2("value"); + number[0] = in[0]; + number[1] = in[1]; + } + if(has_input2("value")) + { + auto in = get_input2("value"); + number[0] = in[0]; + number[1] = in[1]; + number[2] = in[2]; + } + if(has_input2("value")) + { + auto in = get_input2("value"); + number[0] = in[0]; + number[1] = in[1]; + number[2] = in[2]; + number[3] = in[3]; + } + if (type == "float" || type == "R") - em->emitCode(zeno::format("vec4({}).x",number)); + em->emitCode(zeno::format("{}",number[0])); else if (type == "G") - em->emitCode(zeno::format("vec4({}).y",number)); + em->emitCode(zeno::format("{}",number[1])); else if (type == "B") - em->emitCode(zeno::format("vec4({}).z",number)); + em->emitCode(zeno::format("{}",number[2])); else if (type == "A") - em->emitCode(zeno::format("vec4({}).w",number)); + em->emitCode(zeno::format("{}",number[3])); else if (type == "vec2") - em->emitCode(zeno::format("vec2({})",number)); + em->emitCode(zeno::format("vec2({},{})",number[0],number[1])); else if (type == "vec3") - em->emitCode(zeno::format("vec3({})",number)); + em->emitCode(zeno::format("vec3({},{},{})",number[0],number[1],number[2])); else if (type == "vec4") - em->emitCode(zeno::format("vec4({})",number)); + em->emitCode(zeno::format("vec3({},{},{},{})",number[0],number[1],number[2],number[4])); else throw zeno::Exception("ShaderTexture2D got bad type: " + type); From 0616ff3203aaa0b7180ff5a296e6a449208069d1 Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Wed, 13 Dec 2023 19:17:16 +0800 Subject: [PATCH 057/106] match matreial json --- ui/zenoedit/dialog/zforksubgrapdlg.h | 3 +- ui/zenoedit/dialog/zforksubgraphdlg.cpp | 56 +++++++--- ui/zenoedit/dialog/zmathpresetsubgrapdlg.cpp | 110 +++++++++++++++++++ ui/zenoedit/dialog/zmathpresetsubgrapdlg.h | 32 ++++++ 4 files changed, 186 insertions(+), 15 deletions(-) create mode 100644 ui/zenoedit/dialog/zmathpresetsubgrapdlg.cpp create mode 100644 ui/zenoedit/dialog/zmathpresetsubgrapdlg.h diff --git a/ui/zenoedit/dialog/zforksubgrapdlg.h b/ui/zenoedit/dialog/zforksubgrapdlg.h index 927e789b8f..e16036ff32 100644 --- a/ui/zenoedit/dialog/zforksubgrapdlg.h +++ b/ui/zenoedit/dialog/zforksubgrapdlg.h @@ -4,6 +4,7 @@ #include #include "zenoui/comctrl/dialog/zframelessdialog.h" #include +#include "zmathpresetsubgrapdlg.h" class ZForkSubgraphDlg : public ZFramelessDialog { @@ -18,11 +19,11 @@ private slots: void initUi(); QMap> readFile(); private: - QString m_version; QTableWidget* m_pTableWidget; QMap m_subgsMap; // QString m_importPath; QPushButton* m_pImportBtn; + QMap m_matchInfo; }; #endif \ No newline at end of file diff --git a/ui/zenoedit/dialog/zforksubgraphdlg.cpp b/ui/zenoedit/dialog/zforksubgraphdlg.cpp index 5ffc34df3f..bdf9f7cce4 100644 --- a/ui/zenoedit/dialog/zforksubgraphdlg.cpp +++ b/ui/zenoedit/dialog/zforksubgraphdlg.cpp @@ -95,8 +95,6 @@ QMap> ZForkSubgraphDlg::readFile() zeno::log_error("json file is corrupted"); return matValueMap; } - QMap> presetParamMap; // - QMap> matKeyMap; // auto jsonObject = doc.GetObject(); QMap> matchMap;//> if (jsonObject.HasMember("match")) @@ -122,16 +120,17 @@ QMap> ZForkSubgraphDlg::readFile() QString mat = m_subgsMap[mtlid]; IGraphsModel* pGraphsModel = zenoApp->graphsManagment()->currentModel(); auto subgIdx = pGraphsModel->index(mat); - if (subgIdx.isValid()) + if (subgIdx.isValid() && !m_matchInfo.contains(mat) && matchMap.isEmpty()) { + m_matchInfo[mat].m_matType = mat; //preset QModelIndexList nodes = pGraphsModel->searchInSubgraph("SubInput", subgIdx); - for (QModelIndex subInput : nodes) + for (const QModelIndex& subInput : nodes) { NodeParamModel* nodeParams = QVariantPtr::asPtr(subInput.data(ROLE_NODE_PARAMS)); QModelIndex nameIdx = nodeParams->getParam(PARAM_PARAM, "name"); - QString paramName = nameIdx.data(ROLE_PARAM_VALUE).toString(); - presetParamMap[mat].insert(paramName); + QString paramName = nameIdx.data(ROLE_PARAM_VALUE).toString(); + m_matchInfo[mat].m_matchInfo[paramName] = paramName; } } if (jsonObject.HasMember(mtlid.toUtf8())) @@ -140,25 +139,50 @@ QMap> ZForkSubgraphDlg::readFile() if (objVal.IsObject()) { for (auto iter = objVal.MemberBegin(); iter != objVal.MemberEnd(); iter++) { - matKeyMap[mat].insert(iter->name.GetString()); - QVariant val = UiHelper::parseJson(iter->value); QString matKey = iter->name.GetString(); + QVariant val = UiHelper::parseJson(iter->value); if (matchMap.contains(mat)) { - if (matchMap.contains(mat)) + const auto& match = matchMap[mat]; + if (match.contains(matKey)) + { + matKey = match[matKey]; + } + } + else if (matchMap.isEmpty()) + { + if (m_matchInfo[mat].m_matchInfo.contains(matKey)) + { + m_matchInfo[mat].m_matchInfo.remove(matKey); + } + else { - const auto& match = matchMap[mat]; - if (match.contains(matKey)) - { - matKey = match[matKey]; - } + m_matchInfo[mat].m_matKeys.insert(matKey); } } + matValueMap[mtlid][matKey] = val; } } } } + + for (auto iter = m_matchInfo.begin(); iter != m_matchInfo.end();) + { + if (iter->m_matchInfo.isEmpty() || iter->m_matKeys.isEmpty()) + m_matchInfo.erase(iter++); + else + iter++; + } + + if (!m_matchInfo.isEmpty()) + { + QMap infos = ZMatchPresetSubgraphDlg::getMatchInfo(m_matchInfo, this); + if (!infos.isEmpty()) + { + m_matchInfo = infos; + } + } return matValueMap; } @@ -223,6 +247,10 @@ void ZForkSubgraphDlg::onOkClicked() for (const auto& inputIdx : nodeParams->getInputIndice()) { QString name = inputIdx.data(ROLE_PARAM_NAME).toString(); + if (m_matchInfo.contains(subgName) && m_matchInfo[subgName].m_matchInfo.contains(name)) + { + name = m_matchInfo[subgName].m_matchInfo[name]; + } if (valueMap.contains(name)) { pGraphsModel->ModelSetData(inputIdx, valueMap[name], ROLE_PARAM_VALUE); diff --git a/ui/zenoedit/dialog/zmathpresetsubgrapdlg.cpp b/ui/zenoedit/dialog/zmathpresetsubgrapdlg.cpp new file mode 100644 index 0000000000..1bbce9e541 --- /dev/null +++ b/ui/zenoedit/dialog/zmathpresetsubgrapdlg.cpp @@ -0,0 +1,110 @@ +#include "zmathpresetsubgrapdlg.h" +#include +#include +#include "zenoapplication.h" +#include +#include +#include +#include +#include "variantptr.h" +#include "nodesview/zenographseditor.h" +#include "nodesys/zenosubgraphscene.h" +#include "zenomainwindow.h" +#include +#include + +//dialog +ZMatchPresetSubgraphDlg::ZMatchPresetSubgraphDlg(const QMap& info, QWidget* parent) + : ZFramelessDialog(parent) + , m_matchInfos(info) +{ + initUi(info); + QString path = ":/icons/zeno-logo.png"; + this->setTitleIcon(QIcon(path)); + this->setTitleText(tr("Math Info")); + resize(ZenoStyle::dpiScaledSize(QSize(500, 600))); +} + +void ZMatchPresetSubgraphDlg::initUi(const QMap& info) +{ + QWidget* pWidget = new QWidget(this); + QVBoxLayout* pLayout = new QVBoxLayout(pWidget); + m_pTreeView = new QTreeView(this); + m_pTreeView->setHeaderHidden(true); + m_pModel = new QStandardItemModel(this); + m_pTreeView->setModel(m_pModel); + connect(m_pModel, &QStandardItemModel::rowsInserted, this, &ZMatchPresetSubgraphDlg::onRowInserted); + initModel(); + pLayout->addWidget(m_pTreeView); + QHBoxLayout* pHLayout = new QHBoxLayout(this); + QPushButton* pOkBtn = new QPushButton(tr("Ok"), this); + QPushButton* pCancelBtn = new QPushButton(tr("Cancel"), this); + int width = ZenoStyle::dpiScaled(80); + int height = ZenoStyle::dpiScaled(30); + pOkBtn->setFixedSize(width, height); + pCancelBtn->setFixedSize(width, height); + pHLayout->addStretch(); + pHLayout->addWidget(pOkBtn); + pHLayout->addWidget(pCancelBtn); + pLayout->addLayout(pHLayout); + this->setMainWidget(pWidget); + + connect(pOkBtn, &QPushButton::clicked, this, &ZMatchPresetSubgraphDlg::accept); + connect(pCancelBtn, &QPushButton::clicked, this, &ZMatchPresetSubgraphDlg::reject); +} + +void ZMatchPresetSubgraphDlg::initModel() +{ + for (const auto& key : m_matchInfos.keys()) + { + const auto& info = m_matchInfos[key]; + QStandardItem* pItem = new QStandardItem(info.m_matType); + pItem->setData(QVariant::fromValue(info.m_matKeys), Qt::UserRole); + m_pModel->appendRow(pItem); + for (const auto& key : info.m_matchInfo.keys()) + { + const auto& match = info.m_matchInfo[key]; + QStandardItem* pChildItem = new QStandardItem; + QWidget* pWidget = new QWidget; + pChildItem->setData(key, Qt::DisplayRole); + pItem->appendRow(pChildItem); + } + m_pTreeView->setExpanded(pItem->index(), true); + } +} + +void ZMatchPresetSubgraphDlg::onRowInserted(const QModelIndex& parent, int first, int last) +{ + const QModelIndex& idx = m_pModel->index(first, 0, parent); + if (idx.isValid() && parent.isValid()) + { + QWidget* pWidget = new QWidget(this); + QHBoxLayout* pLayout = new QHBoxLayout(pWidget); + pLayout->setMargin(0); + QString param = idx.data(Qt::DisplayRole).toString(); + pLayout->addStretch(); + + ZComboBox* pComboBox = new ZComboBox(this); + QList lst = parent.data(Qt::UserRole).value >().toList(); + lst.prepend(param); + pComboBox->addItems(lst); + pComboBox->setCurrentText(param); + pLayout->addWidget(pComboBox); + m_pTreeView->setIndexWidget(idx, pWidget); + connect(pComboBox, &ZComboBox::currentTextChanged, this, [=]() { + QString mtlid = parent.data(Qt::DisplayRole).toString(); + if (m_matchInfos.contains(mtlid) && m_matchInfos[mtlid].m_matchInfo.contains(param)) + { + m_matchInfos[mtlid].m_matchInfo[param] = pComboBox->currentText(); + } + }); + } +} + +QMap ZMatchPresetSubgraphDlg::getMatchInfo(const QMap& info, QWidget* parent) +{ + ZMatchPresetSubgraphDlg dlg(info, parent); + if (dlg.exec() == QDialog::Accepted) + return dlg.m_matchInfos; + return QMap(); +} \ No newline at end of file diff --git a/ui/zenoedit/dialog/zmathpresetsubgrapdlg.h b/ui/zenoedit/dialog/zmathpresetsubgrapdlg.h new file mode 100644 index 0000000000..55318d1d06 --- /dev/null +++ b/ui/zenoedit/dialog/zmathpresetsubgrapdlg.h @@ -0,0 +1,32 @@ +#ifndef __ZMatchPresetSubgraphDlg_H__ +#define __ZMatchPresetSubgraphDlg_H__ + +#include +#include "zenoui/comctrl/dialog/zframelessdialog.h" +#include + +struct STMatchMatInfo { + QString m_matType; + QMap m_matchInfo; + QSet m_matKeys; +}; + +class ZMatchPresetSubgraphDlg : public ZFramelessDialog +{ + Q_OBJECT +public: + ZMatchPresetSubgraphDlg(const QMap& info, QWidget* parent = nullptr); + static QMap getMatchInfo(const QMap& info, QWidget* parent = nullptr); +signals: +private slots: + void onRowInserted(const QModelIndex& parent, int first, int last); +private: + void initUi(const QMap& info); + void initModel(); +private: + QTreeView* m_pTreeView; + QStandardItemModel*m_pModel; + QMap m_matchInfos; +}; + +#endif \ No newline at end of file From 0e51c526b72e6abcbe2a90cefcd03172b76f23a2 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Thu, 14 Dec 2023 14:12:36 +0800 Subject: [PATCH 058/106] immediate transform --- ui/zenoedit/viewportinteraction/transform.cpp | 47 ++++++------------- ui/zenoedit/viewportinteraction/transform.h | 4 -- 2 files changed, 14 insertions(+), 37 deletions(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 65c8cc303b..c9fa0c5d5b 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -14,12 +14,10 @@ namespace zeno { FakeTransformer::FakeTransformer(ViewportWidget* viewport) : m_objects_center(0.0f) + , m_pivot(0.0f) , m_trans(0.0f) , m_scale(1.0f) , m_rotate({0, 0, 0, 1}) - , m_last_trans(0.0f) - , m_last_scale(1.0f) - , m_last_rotate({0, 0, 0, 1}) , m_status(false) , m_operation(NONE) , m_handler_scale(1.f) @@ -305,6 +303,7 @@ bool FakeTransformer::isTransforming() const { } void FakeTransformer::startTransform() { + zeno::log_info("FakeTransformer::startTransform"); markObjectsInteractive(); } @@ -396,6 +395,7 @@ void FakeTransformer::syncToTransformNode(NodeLocation& node_location, } void FakeTransformer::endTransform(bool moved) { + zeno::log_info("FakeTransformer::endTransform"); if (moved) { // write transform info to objects' user data for (auto &[obj_name, obj] : m_objects) { @@ -465,10 +465,6 @@ void FakeTransformer::endTransform(bool moved) { m_scale = {1, 1, 1}; m_rotate = {0, 0, 0, 1}; - m_last_trans = {0, 0, 0}; - m_last_scale = {1, 1, 1}; - m_last_rotate = {0, 0, 0, 1}; - m_operation_mode = zenovis::INTERACT_NONE; m_handler->setMode(zenovis::INTERACT_NONE); } @@ -631,9 +627,6 @@ void FakeTransformer::clear() { m_trans = {0, 0, 0}; m_scale = {1, 1, 1}; m_rotate = {0, 0, 0, 1}; - m_last_trans = {0, 0, 0}; - m_last_scale = {1, 1, 1}; - m_last_rotate = {0, 0, 0, 1}; m_operation = NONE; m_handler = nullptr; @@ -673,6 +666,7 @@ void FakeTransformer::rotate(glm::vec3 start_vec, glm::vec3 end_vec, glm::vec3 a } void FakeTransformer::doTransform() { + zeno::log_info("FakeTransformer::doTransform"); // qDebug() << "transformer's objects count " << m_objects.size(); glm::vec3 new_objects_center = {0, 0, 0}; for (auto &[obj_name, obj] : m_objects) { @@ -683,50 +677,40 @@ void FakeTransformer::doTransform() { auto rotate = zeno::vec_to_other(user_data.getLiterial("_rotate")); auto scale = zeno::vec_to_other(user_data.getLiterial("_scale")); - // inv last transform - auto pre_translate_matrix = glm::translate(translate + m_last_trans - m_pivot); - auto pre_quaternion = glm::quat(rotate[3], rotate[0], rotate[1], rotate[2]); - auto last_quaternion = glm::quat(m_last_rotate[3], m_last_rotate[0], m_last_rotate[1], m_last_rotate[2]); - auto pre_rotate_matrix = glm::toMat4(pre_quaternion); - auto pre_scale_matrix = glm::scale(scale * m_last_scale); - auto pre_transform_matrix = pre_translate_matrix * glm::toMat4(last_quaternion) * pre_rotate_matrix * pre_scale_matrix; - auto inv_pre_transform = glm::inverse(pre_transform_matrix); - // do this transform auto translate_matrix = glm::translate(translate + m_trans - m_pivot); auto cur_quaternion = glm::quat(m_rotate[3], m_rotate[0], m_rotate[1], m_rotate[2]); - auto rotate_matrix = glm::toMat4(cur_quaternion) * pre_rotate_matrix; + auto rotate_matrix = glm::toMat4(cur_quaternion); auto scale_matrix = glm::scale(scale * m_scale); auto transform_matrix = translate_matrix * rotate_matrix * - scale_matrix * - inv_pre_transform; + scale_matrix; - if (obj->has_attr("pos")) { + if (obj->has_attr("_origin_pos")) { // transform pos auto &pos = obj->attr("pos"); + auto &opos = obj->attr("_origin_pos"); #pragma omp parallel for // for (auto &po : pos) { for (size_t i = 0; i < pos.size(); ++i) { - auto& po = pos[i]; - auto p = zeno::vec_to_other(po); + auto p = zeno::vec_to_other(opos[i]); auto t = transform_matrix * glm::vec4(p, 1.0f); auto pt = glm::vec3(t) / t.w; - po = zeno::other_to_vec<3>(pt); + pos[i] = zeno::other_to_vec<3>(pt); } } - if (obj->has_attr("nrm")) { + if (obj->has_attr("_origin_nrm")) { // transform nrm auto &nrm = obj->attr("nrm"); + auto &onrm = obj->attr("_origin_nrm"); #pragma omp parallel for // for (auto &vec : nrm) { for (size_t i = 0; i < nrm.size(); ++i) { - auto& vec = nrm[i]; - auto n = zeno::vec_to_other(vec); + auto n = zeno::vec_to_other(nrm[i]); glm::mat3 norm_matrix(transform_matrix); norm_matrix = glm::transpose(glm::inverse(norm_matrix)); auto t = glm::normalize(norm_matrix * n); - vec = zeno::other_to_vec<3>(t); + onrm[i] = zeno::other_to_vec<3>(t); } } vec3f bmin, bmax; @@ -737,9 +721,6 @@ void FakeTransformer::doTransform() { } new_objects_center += (zeno::vec_to_other(bmin) + zeno::vec_to_other(bmax)) / 2.0f; } - m_last_trans = m_trans; - m_last_rotate = m_rotate; - m_last_scale = m_scale; new_objects_center /= m_objects.size(); m_objects_center = new_objects_center; diff --git a/ui/zenoedit/viewportinteraction/transform.h b/ui/zenoedit/viewportinteraction/transform.h index 13915ca32a..12c74c4ead 100644 --- a/ui/zenoedit/viewportinteraction/transform.h +++ b/ui/zenoedit/viewportinteraction/transform.h @@ -110,10 +110,6 @@ class FakeTransformer { glm::vec4 m_rotate; glm::vec3 m_scale; - glm::vec3 m_last_trans; - glm::vec4 m_last_rotate; - glm::vec3 m_last_scale; - glm::vec3 m_trans_start; glm::vec3 m_rotate_start; // glm::vec3 m_scale_start; From e672a6fe2381ab8331b811eb9cbda3ac4f29fff8 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Thu, 14 Dec 2023 15:11:38 +0800 Subject: [PATCH 059/106] tmp --- ui/zenoedit/viewportinteraction/transform.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index c9fa0c5d5b..155939f60b 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -65,14 +65,15 @@ void FakeTransformer::addObject(const std::string& name) { user_data.setLiterial("_bboxMin", bmin); user_data.setLiterial("_bboxMax", bmax); } - if (!user_data.has("_translate")) { + if (!user_data.has("_pivot")) { zeno::vec3f translate = {0, 0, 0}; user_data.setLiterial("_translate", translate); zeno::vec4f rotate = {0, 0, 0, 1}; user_data.setLiterial("_rotate", rotate); zeno::vec3f scale = {1, 1, 1}; user_data.setLiterial("_scale", scale); - user_data.set2("_pivot", "bboxCenter"); + auto bboxCenter = (bmin + bmax) / 2; + user_data.set2("_pivot", bboxCenter); if (object->has_attr("pos") && !object->has_attr("_origin_pos")) { auto &pos = object->attr("pos"); object->verts.add_attr("_origin_pos") = pos; @@ -84,6 +85,7 @@ void FakeTransformer::addObject(const std::string& name) { } auto m = zeno::vec_to_other(bmax); auto n = zeno::vec_to_other(bmin); + m_pivot = zeno::vec_to_other(user_data.get2("_pivot")); m_objects_center += (m + n) / 2.0f; m_objects[name] = object; m_objects_center /= m_objects.size(); From 935b79bf49a1089947d2bce7972248c341ac1e16 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Thu, 14 Dec 2023 15:11:56 +0800 Subject: [PATCH 060/106] temp --- zeno/src/nodes/prim/TransformPrimitive.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/zeno/src/nodes/prim/TransformPrimitive.cpp b/zeno/src/nodes/prim/TransformPrimitive.cpp index 1088b4b032..9f0d3c3038 100644 --- a/zeno/src/nodes/prim/TransformPrimitive.cpp +++ b/zeno/src/nodes/prim/TransformPrimitive.cpp @@ -272,6 +272,7 @@ struct PrimitiveTransform : zeno::INode { auto prim = get_input("prim"); std::string pivotType = get_input2("pivot"); + zeno::vec3f _pivot = {}; if (pivotType == "bboxCenter") { zeno::vec3f _min; zeno::vec3f _max; @@ -280,6 +281,7 @@ struct PrimitiveTransform : zeno::INode { auto pivot_to_local = glm::translate(glm::vec3(-p[0], -p[1], -p[2])); auto pivot_to_world = glm::translate(glm::vec3(p[0], p[1], p[2])); matrix = pivot_to_world * matrix * pivot_to_local; + _pivot = p; } auto outprim = std::make_unique(*prim); @@ -311,7 +313,7 @@ struct PrimitiveTransform : zeno::INode { vec4f rotate = {myQuat.x, myQuat.y, myQuat.z, myQuat.w}; user_data.setLiterial("_rotate", rotate); user_data.setLiterial("_scale", scaling); - user_data.set2("_pivot", pivotType); + user_data.set2("_pivot", _pivot); //auto oMat = std::make_shared(); //oMat->m = matrix; set_output("outPrim", std::move(outprim)); From 501efe6e0a926849838542faf82874e39aaecce5 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Thu, 14 Dec 2023 15:26:48 +0800 Subject: [PATCH 061/106] clamp D --- zenovis/xinxinoptix/DisneyBRDF.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zenovis/xinxinoptix/DisneyBRDF.h b/zenovis/xinxinoptix/DisneyBRDF.h index fd202a095b..cd494692cb 100644 --- a/zenovis/xinxinoptix/DisneyBRDF.h +++ b/zenovis/xinxinoptix/DisneyBRDF.h @@ -443,7 +443,7 @@ vec3 EvalMicrofacetReflection(float ax, float ay, vec3 V, vec3 L, vec3 H, vec3 F if (L.z * V.z <= 0.0) return vec3(0.0); - float D = GTR2Aniso(abs(H.z), H.x, H.y, ax, ay); + float D = clamp(GTR2Aniso(abs(H.z), H.x, H.y, ax, ay),0.0f, 10.0f); float G1 = SmithGAniso(abs(V.z), V.x, V.y, ax, ay); float G2 = G1 * SmithGAniso(abs(L.z), L.x, L.y, ax, ay); @@ -463,7 +463,7 @@ vec3 EvalMicrofacetRefraction(vec3 baseColor, float ax, float ay, float eta, vec float LDotH = dot(L, H); //always negative float VDotH = dot(V, H); //always positive - float D = GTR2Aniso(abs(H.z), H.x, H.y, ax, ay); + float D = clamp(GTR2Aniso(abs(H.z), H.x, H.y, ax, ay),0.0f, 10.0f); float G1 = SmithGAniso(abs(V.z), V.x, V.y, ax, ay); float G2 = G1 * SmithGAniso(abs(L.z), L.x, L.y, ax, ay); float denom = LDotH * eta + VDotH; @@ -493,7 +493,7 @@ vec3 EvalClearcoat(float ccR, vec3 V, vec3 L, vec3 H, float &pdf) float VDotH = abs(dot(V, H)); float F = mix(0.04, 1.0, SchlickWeight(VDotH)); - float D = GTR1(H.z, ccR); + float D = clamp(GTR1(H.z, ccR),0.0f, 10.0f); float G = SmithG(L.z, 0.25f) * SmithG(V.z, 0.25f); float jacobian = 1.0f / (4.0f * VDotH); From c131c24aebd0ae9a90fcfa8e69ffdcd3c587eb7e Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Thu, 14 Dec 2023 15:40:55 +0800 Subject: [PATCH 062/106] pivot --- ui/zenoedit/viewportinteraction/transform.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 155939f60b..6f5f2985da 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -680,13 +680,11 @@ void FakeTransformer::doTransform() { auto scale = zeno::vec_to_other(user_data.getLiterial("_scale")); // do this transform - auto translate_matrix = glm::translate(translate + m_trans - m_pivot); + auto translate_matrix = glm::translate(translate + m_trans); auto cur_quaternion = glm::quat(m_rotate[3], m_rotate[0], m_rotate[1], m_rotate[2]); auto rotate_matrix = glm::toMat4(cur_quaternion); auto scale_matrix = glm::scale(scale * m_scale); - auto transform_matrix = translate_matrix * - rotate_matrix * - scale_matrix; + auto transform_matrix = glm::translate(m_pivot) * translate_matrix * rotate_matrix * scale_matrix * glm::translate(-m_pivot); if (obj->has_attr("_origin_pos")) { // transform pos From f646bc526d1aa70ad2d9f82344dbd50fb48a77f9 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Thu, 14 Dec 2023 15:56:21 +0800 Subject: [PATCH 063/106] improve json new name mapp --- zeno/src/nodes/JsonProcess.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/zeno/src/nodes/JsonProcess.cpp b/zeno/src/nodes/JsonProcess.cpp index d1889e1593..176161919b 100644 --- a/zeno/src/nodes/JsonProcess.cpp +++ b/zeno/src/nodes/JsonProcess.cpp @@ -305,6 +305,11 @@ struct JsonGetData : zeno::INode { auto strings = zeno::split_str(path, ':'); auto type = strings[1]; path = strings[0]; + std::string new_name = path; + if (strings.size() == 3) { + new_name = zeno::trim_string(strings[2]); + } + auto names = split_str(path, '/'); for (auto & name : names) { @@ -314,34 +319,34 @@ struct JsonGetData : zeno::INode { if (type == "json") { auto out_json = std::make_shared(); out_json->json = json->json; - dict->lut[path] = out_json; + dict->lut[new_name] = out_json; } else if (type == "int") { - dict->lut[path] = std::make_shared(int(json->json)); + dict->lut[new_name] = std::make_shared(int(json->json)); } else if (type == "float") { - dict->lut[path] = std::make_shared(float(json->json)); + dict->lut[new_name] = std::make_shared(float(json->json)); } else if (type == "string") { - dict->lut[path] = std::make_shared(std::string(json->json)); + dict->lut[new_name] = std::make_shared(std::string(json->json)); } else if (type == "vec2f") { float x = float(json->json["x"]); float y = float(json->json["y"]); - dict->lut[path] = std::make_shared(vec2f(x, y)); + dict->lut[new_name] = std::make_shared(vec2f(x, y)); } else if (type == "vec3f") { float x = float(json->json["x"]); float y = float(json->json["y"]); float z = float(json->json["z"]); - dict->lut[path] = std::make_shared(vec3f(x, y, z)); + dict->lut[new_name] = std::make_shared(vec3f(x, y, z)); } else if (type == "vec4f") { float x = float(json->json["x"]); float y = float(json->json["y"]); float z = float(json->json["z"]); float w = float(json->json["w"]); - dict->lut[path] = std::make_shared(vec4f(x, y, z, w)); + dict->lut[new_name] = std::make_shared(vec4f(x, y, z, w)); } } set_output("outs", dict); From bc9654ee471d8c4b50932b991a086d61582f6af3 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Thu, 14 Dec 2023 16:27:20 +0800 Subject: [PATCH 064/106] fix --- ui/zenoedit/viewportinteraction/transform.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 6f5f2985da..9df5888445 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -678,11 +678,13 @@ void FakeTransformer::doTransform() { auto translate = zeno::vec_to_other(user_data.getLiterial("_translate")); auto rotate = zeno::vec_to_other(user_data.getLiterial("_rotate")); auto scale = zeno::vec_to_other(user_data.getLiterial("_scale")); + auto pre_quaternion = glm::quat(rotate[3], rotate[0], rotate[1], rotate[2]); + auto pre_rotate_matrix = glm::toMat4(pre_quaternion); // do this transform auto translate_matrix = glm::translate(translate + m_trans); auto cur_quaternion = glm::quat(m_rotate[3], m_rotate[0], m_rotate[1], m_rotate[2]); - auto rotate_matrix = glm::toMat4(cur_quaternion); + auto rotate_matrix = glm::toMat4(cur_quaternion) * pre_rotate_matrix; auto scale_matrix = glm::scale(scale * m_scale); auto transform_matrix = glm::translate(m_pivot) * translate_matrix * rotate_matrix * scale_matrix * glm::translate(-m_pivot); From 12450d29ea0c3cf22bc813d9e3309c88c88bf3ed Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Thu, 14 Dec 2023 16:32:01 +0800 Subject: [PATCH 065/106] del log --- ui/zenoedit/viewportinteraction/transform.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 9df5888445..0ed28c56e3 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -305,7 +305,6 @@ bool FakeTransformer::isTransforming() const { } void FakeTransformer::startTransform() { - zeno::log_info("FakeTransformer::startTransform"); markObjectsInteractive(); } @@ -397,7 +396,6 @@ void FakeTransformer::syncToTransformNode(NodeLocation& node_location, } void FakeTransformer::endTransform(bool moved) { - zeno::log_info("FakeTransformer::endTransform"); if (moved) { // write transform info to objects' user data for (auto &[obj_name, obj] : m_objects) { @@ -668,7 +666,6 @@ void FakeTransformer::rotate(glm::vec3 start_vec, glm::vec3 end_vec, glm::vec3 a } void FakeTransformer::doTransform() { - zeno::log_info("FakeTransformer::doTransform"); // qDebug() << "transformer's objects count " << m_objects.size(); glm::vec3 new_objects_center = {0, 0, 0}; for (auto &[obj_name, obj] : m_objects) { From 5c207622a759589f72feef3aaf2da5a70e4c5b42 Mon Sep 17 00:00:00 2001 From: YingQ Date: Thu, 14 Dec 2023 18:04:39 +0800 Subject: [PATCH 066/106] add more string node --- zeno/src/nodes/StringNodes.cpp | 77 ++++++++++++++++++++++++-- zeno/src/nodes/prim/WBTestFunction.cpp | 2 +- 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 41fa2d0f56..51e70bdf65 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -6,6 +6,8 @@ #include #include #include +#include +//#include #include namespace zeno { @@ -386,8 +388,7 @@ ZENDEFNODE(EndFrame, { {"fileio"}, });*/ -struct StringToNumber : zeno::INode { - +struct StringToNumber : zeno::INode {//todo?::Returns 0.0 if the string does not contain a number. virtual void apply() override { auto in_str = get_input2("str"); auto type = get_input2("type"); @@ -410,7 +411,7 @@ struct StringToNumber : zeno::INode { ZENDEFNODE(StringToNumber, {{ /* inputs: */ - {"enum float int", "type", "all"}, + {"enum float int", "type", "float"}, {"string", "str", "0"}, }, @@ -446,6 +447,7 @@ struct StringToList : zeno::INode { auto list = std::make_shared(); auto separator = get_input2("Separator"); auto trimoption = get_input2("Trim"); + auto keepempty = get_input2("KeepEmpty"); std::vector strings; size_t pos = 0; size_t posbegin = 0; @@ -453,14 +455,14 @@ struct StringToList : zeno::INode { while ((pos = stringlist.find(separator, pos)) != std::string::npos) { word = stringlist.substr(posbegin, pos-posbegin); if(trimoption) trim(word); - strings.push_back(word); + if(keepempty || !word.empty()) strings.push_back(word); pos += separator.length(); posbegin = pos; } if (posbegin < stringlist.length()) { //push last word word = stringlist.substr(posbegin); if(trimoption) trim(word); - strings.push_back(word); + if(keepempty || !word.empty()) strings.push_back(word); } for(const auto &string : strings) { auto obj = std::make_unique(); @@ -476,6 +478,7 @@ ZENDEFNODE(StringToList, { {"multiline_string", "string", ""}, {"string", "Separator", ""}, {"bool", "Trim", "false"}, + {"bool", "KeepEmpty", "false"}, }, {{"list"}, }, @@ -483,5 +486,69 @@ ZENDEFNODE(StringToList, { {"string"}, }); +struct StringJoin : zeno::INode {//zeno string only support list for now + virtual void apply() override { + auto list = get_input("list"); + auto stringvec = list->get2(); + auto separator = get_input2("Separator"); + auto output = join_str(stringvec, separator); + set_output2("string", output); + } +}; + +ZENDEFNODE(StringJoin, { + { + {"list"}, + {"string", "Separator", ""}, + }, + {{"string", "string"}, + }, + {}, + {"string"}, +}); + +struct NumbertoString : zeno::INode { + virtual void apply() override { + auto num = get_input("number"); + auto obj = std::make_unique(); + std::visit([&](const auto &v) { + obj->set(zeno::to_string(v)); + }, num->value); + set_output("string", std::move(obj)); + } +}; + +ZENDEFNODE(NumbertoString, { + { + {"number"}, + }, + {{"string", "string"}, + }, + {}, + {"string"}, +}); + +struct SubString : zeno::INode {//slice... + virtual void apply() override { + auto string = get_input2("string"); + auto start = get_input2("start"); + auto length = get_input2("length"); + auto output = string.substr(start, length); + set_output2("string", output); + } +}; + +ZENDEFNODE(SubString, { + { + {"multiline_string", "string", ""}, + {"int", "start", "0"}, + {"int", "length", "1"}, + }, + {{"string", "string"}, + }, + {}, + {"string"}, +}); + } } diff --git a/zeno/src/nodes/prim/WBTestFunction.cpp b/zeno/src/nodes/prim/WBTestFunction.cpp index d565b9041a..37d2763fe9 100644 --- a/zeno/src/nodes/prim/WBTestFunction.cpp +++ b/zeno/src/nodes/prim/WBTestFunction.cpp @@ -295,7 +295,7 @@ ZENDEFNODE(str2num, { }, /* category: */ { - "WBTest", + "deprecated", }}); From a44532a80721b95ca776f0267ce8c8ec769738da Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Fri, 15 Dec 2023 02:53:39 +0800 Subject: [PATCH 067/106] switch to rgba8 for textures --- zenovis/xinxinoptix/OptiXStuff.h | 38 ++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/zenovis/xinxinoptix/OptiXStuff.h b/zenovis/xinxinoptix/OptiXStuff.h index 03178e43ab..0808ac0acf 100644 --- a/zenovis/xinxinoptix/OptiXStuff.h +++ b/zenovis/xinxinoptix/OptiXStuff.h @@ -348,29 +348,29 @@ inline sutil::Texture loadCubeMap(const std::string& ppm_filename) inline std::shared_ptr makeCudaTexture(unsigned char* img, int nx, int ny, int nc) { auto texture = std::make_shared(); - std::vector data; + std::vector data; data.resize(nx*ny); for(int j=0;j=1?(float)(img[idx*nc + 0])/255.0f:0, - nc>=2?(float)(img[idx*nc + 1])/255.0f:0, - nc>=3?(float)(img[idx*nc + 2])/255.0f:0, - nc>=4?(float)(img[idx*nc + 3])/255.0f:0, + nc>=1?(img[idx*nc + 0]):(unsigned char)0, + nc>=2?(img[idx*nc + 1]):(unsigned char)0, + nc>=3?(img[idx*nc + 2]):(unsigned char)0, + nc>=4?(img[idx*nc + 3]):(unsigned char)0, }; } - cudaChannelFormatDesc channelDescriptor = cudaCreateChannelDesc(32, 32, 32, 32, cudaChannelFormatKindFloat); + cudaChannelFormatDesc channelDescriptor = cudaCreateChannelDesc(8, 8, 8, 8, cudaChannelFormatKindUnsigned); cudaError_t rc = cudaMallocArray(&texture->gpuImageArray, &channelDescriptor, nx, ny, 0); if (rc != cudaSuccess) { std::cout<<"texture space alloc failed\n"; return 0; } rc = cudaMemcpy2DToArray(texture->gpuImageArray, 0, 0, data.data(), - nx * sizeof(float) * 4, - nx * sizeof(float) * 4, + nx * sizeof(unsigned char) * 4, + nx * sizeof(unsigned char) * 4, ny, cudaMemcpyHostToDevice); if (rc != cudaSuccess) { @@ -390,7 +390,7 @@ inline std::shared_ptr makeCudaTexture(unsigned char* img, int nx, in textureDescriptor.disableTrilinearOptimization = 1; textureDescriptor.filterMode = cudaFilterModeLinear; textureDescriptor.normalizedCoords = true; - textureDescriptor.readMode = cudaReadModeElementType; + textureDescriptor.readMode = cudaReadModeNormalizedFloat ; textureDescriptor.sRGB = 0; rc = cudaCreateTextureObject(&texture->texture, &resourceDescriptor, &textureDescriptor, nullptr); if (rc != cudaSuccess) { @@ -740,19 +740,25 @@ inline void addTexture(std::string path) calc_sky_cdf_map(nx, ny, 3, (float *)img->verts.data()); } if (channels == 3) { - g_tex[path] = makeCudaTexture((float *)img->verts.data(), nx, ny, 3); + std::vector ucdata; + ucdata.resize(img->verts.size()*3); + for(int i=0;iverts.size()*3;i++) + { + ucdata[i] = (unsigned char)(((float*)img->verts.data())[i]*255.0); + } + g_tex[path] = makeCudaTexture(ucdata.data(), nx, ny, 3); } else { - std::vector data(nx * ny); + std::vector data(nx * ny); auto &alpha = img->verts.attr("alpha"); for (auto i = 0; i < nx * ny; i++) { - data[i][0] = img->verts[i][0]; - data[i][1] = img->verts[i][1]; - data[i][2] = img->verts[i][2]; - data[i][3] = alpha[i]; + data[i].x = (unsigned char)(img->verts[i][0]*255.0); + data[i].y = (unsigned char)(img->verts[i][1]*255.0); + data[i].z = (unsigned char)(img->verts[i][2]*255.0); + data[i].w = (unsigned char)(alpha[i] *255.0); } - g_tex[path] = makeCudaTexture((float *)data.data(), nx, ny, 4); + g_tex[path] = makeCudaTexture((unsigned char *)data.data(), nx, ny, 4); } } else if (stbi_is_hdr(native_path.c_str())) { From dba5d31048eca94b298228d24d66017b35094db2 Mon Sep 17 00:00:00 2001 From: YingQ Date: Fri, 15 Dec 2023 11:45:54 +0800 Subject: [PATCH 068/106] add find and replace str --- zeno/src/nodes/StringNodes.cpp | 60 +++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 51e70bdf65..1b3bb777ee 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -7,7 +7,7 @@ #include #include #include -//#include +#include #include namespace zeno { @@ -528,6 +528,64 @@ ZENDEFNODE(NumbertoString, { {"string"}, }); +std::string strreplace(std::string textToSearch, std::string_view toReplace, std::string_view replacement) +{ + size_t pos = 0; + for (;;) + { + pos = textToSearch.find(toReplace, pos); + if (pos == std::string::npos) + return textToSearch; + textToSearch.replace(pos, toReplace.length(), replacement); + pos += replacement.length(); + } +} + +struct StringReplace : zeno::INode { + virtual void apply() override { + std::string string = get_input2("string"); + std::string oldstr = get_input2("old"); + std::string newstr = get_input2("new"); + auto output = strreplace(string, oldstr, newstr); + set_output2("string", output); + } +}; + +ZENDEFNODE(StringReplace, { + { + {"multiline_string", "string", ""}, + {"string", "old", ""}, + {"string", "new", ""}, + }, + {{"string", "string"}, + }, + {}, + {"string"}, +}); + +struct StringFind : zeno::INode {//return -1 if not found + virtual void apply() override { + auto string = get_input2("string"); + auto substring = get_input2("substring"); + auto start = get_input2("start"); + std::string::size_type n = string.find(substring, start); + int output = (n == std::string::npos) ? -1 : static_cast(n); + set_output2("Position", output); + } +}; + +ZENDEFNODE(StringFind, { + { + {"multiline_string", "string", ""}, + {"string", "substring", ""}, + {"int", "start", "0"}, + }, + {{"int", "Position"}, + }, + {}, + {"string"}, +}); + struct SubString : zeno::INode {//slice... virtual void apply() override { auto string = get_input2("string"); From c1ef24f817d6df8aef50c0a418367d3f84573f3f Mon Sep 17 00:00:00 2001 From: YingQ Date: Fri, 15 Dec 2023 13:32:46 +0800 Subject: [PATCH 069/106] some simple stringnode --- zeno/src/nodes/StringNodes.cpp | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 1b3bb777ee..b7cd94a146 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -608,5 +608,64 @@ ZENDEFNODE(SubString, { {"string"}, }); +struct StringtoLower : zeno::INode { + virtual void apply() override { + auto string = get_input2("string"); + std::string output = string; + std::transform(output.begin(), output.end(), output.begin(), [] (auto c) { + return static_cast (std::tolower (static_cast (c))); }); + set_output2("string", output); + } +}; + +ZENDEFNODE(StringtoLower, { + { + {"string", "string", ""}, + }, + {{"string", "string"}, + }, + {}, + {"string"}, +}); + +struct StringtoUpper : zeno::INode { + virtual void apply() override { + auto string = get_input2("string"); + std::string output = string; + std::transform(output.begin(), output.end(), output.begin(), [] (auto c) { + return static_cast (std::toupper (static_cast (c))); }); + set_output2("string", output); + } +}; + +ZENDEFNODE(StringtoUpper, { + { + {"string", "string", ""}, + }, + {{"string", "string"}, + }, + {}, + {"string"}, +}); + +struct StringLength : zeno::INode { + virtual void apply() override { + auto string = get_input2("string"); + int output = string.length(); + set_output2("length", output); + } +}; + +ZENDEFNODE(StringLength, { + { + {"string", "string", ""}, + }, + {{"int", "length"}, + }, + {}, + {"string"}, +}); + + } } From 7da03b6c31f57db805c036d01d47986d38cffb74 Mon Sep 17 00:00:00 2001 From: seeeagull Date: Fri, 15 Dec 2023 13:48:17 +0800 Subject: [PATCH 070/106] init tetwild --- projects/Geometry/CMakeLists.txt | 4 +- projects/Geometry/tetmesh.cpp | 232 +++++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+), 1 deletion(-) create mode 100644 projects/Geometry/tetmesh.cpp diff --git a/projects/Geometry/CMakeLists.txt b/projects/Geometry/CMakeLists.txt index b4eb1ce357..f0bdff4a71 100644 --- a/projects/Geometry/CMakeLists.txt +++ b/projects/Geometry/CMakeLists.txt @@ -3,6 +3,8 @@ project(Geometry) cmake_minimum_required(VERSION 3.16) set(CMAKE_CXX_STANDARD 17) -target_sources(zeno PRIVATE quadmesh.cpp) +target_sources(zeno PRIVATE quadmesh.cpp tetmesh.cpp) target_link_libraries(zeno PRIVATE InstantMeshesApi) +target_link_libraries(zeno PRIVATE FTetwildApi) add_subdirectory(instant_meshes) +add_subdirectory(fTetWild) diff --git a/projects/Geometry/tetmesh.cpp b/projects/Geometry/tetmesh.cpp new file mode 100644 index 0000000000..7737f13c36 --- /dev/null +++ b/projects/Geometry/tetmesh.cpp @@ -0,0 +1,232 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "./fTetWild/api.h" + +namespace zeno { + +struct FTetWild : INode { + virtual void apply() override { + auto input_dir = get_input2("input_dir"); + auto output_dir = get_input2("output_dir"); + auto tag = get_input2("tag"); + tag.erase(tag.find_last_not_of(" ")+1); + auto operation = get_input2("operation"); + float edge_length = get_input2("edge_length"); + float epsilon = get_input2("epsilon"); + float stop_energy = get_input2("stop_energy"); + bool skip_simplify = get_input2("skip_simplify"); + bool no_binary = get_input2("no_binary"); + bool no_color = get_input2("no_color"); + bool smooth = get_input2("smooth_open_boundary"); + bool export_raw = get_input2("export_raw"); + bool manifold = get_input2("manifold_surface"); + bool coarsen = get_input2("coarsen"); + auto csg = get_input2("csg"); + csg.erase(csg.find_last_not_of(" ")+1); + bool disable_filter = get_input2("disable_filtering"); + bool floodfill = get_input2("use_floodfill"); + bool general_wn = get_input2("use_general_wn"); + bool input_wn = get_input2("use_input_for_wn"); + auto bg_mesh = get_input2("bg_mesh"); + bg_mesh.erase(bg_mesh.find_last_not_of(" ")+1); + + int argc = 1; + char* argv[40]; + argv[0] = (char*)malloc(sizeof("./FloatTetwild_bin\0")); + strcpy(argv[0], "./FloatTetwild_bin\0"); + if (input_dir.size() > 0) { + argv[argc] = (char*)malloc(sizeof("-i\0")); + strcpy(argv[argc], "-i\0"); + argv[argc+1] = (char*)malloc((input_dir.size()+1)*sizeof(char)); + for (int i = 0; i < input_dir.size(); ++i) + argv[argc+1][i] = input_dir[i]; + argv[argc+1][input_dir.size()] = '\0'; + argc += 2; + } + if (output_dir.size() > 0) { + argv[argc] = (char*)malloc(sizeof("-o\0")); + strcpy(argv[argc], "-o\0"); + argv[argc+1] = (char*)malloc((output_dir.size()+1)*sizeof(char)); + for (int i = 0; i < output_dir.size(); ++i) + argv[argc+1][i] = output_dir[i]; + argv[argc+1][output_dir.size()] = '\0'; + argc += 2; + } + if (tag.size() > 0) { + argv[argc] = (char*)malloc(sizeof("--tag\0")); + strcpy(argv[argc], "--tag\0"); + argv[argc+1] = (char*)malloc((tag.size()+1)*sizeof(char)); + for (int i = 0; i < tag.size(); ++i) + argv[argc+1][i] = tag[i]; + argv[argc+1][tag.size()] = '\0'; + argc += 2; + } + if (operation == "union") { + argv[argc] = (char*)malloc(sizeof("--op\0")); + strcpy(argv[argc], "--op\0"); + argv[argc+1] = (char*)malloc(sizeof("0\0")); + strcpy(argv[argc+1], "0\0"); + argc += 2; + } else if (operation == "intersection") { + argv[argc] = (char*)malloc(sizeof("--op\0")); + strcpy(argv[argc], "--op\0"); + argv[argc+1] = (char*)malloc(sizeof("1\0")); + strcpy(argv[argc+1], "1\0"); + argc += 2; + } else if (operation == "difference") { + argv[argc] = (char*)malloc(sizeof("--op\0")); + strcpy(argv[argc], "--op\0"); + argv[argc+1] = (char*)malloc(sizeof("2\0")); + strcpy(argv[argc+1], "2\0"); + argc += 2; + } + if (edge_length > 0) { + argv[argc] = (char*)malloc(sizeof("-l\0")); + strcpy(argv[argc], "-l\0"); + std::string edge_length_str = to_string(edge_length); + argv[argc+1] = (char*)malloc((edge_length_str.size()+1)*sizeof(char)); + for (int i = 0; i < edge_length_str.size(); ++i) + argv[argc+1][i] = edge_length_str[i]; + argv[argc+1][edge_length_str.size()] = '\0'; + argc += 2; + } + if (epsilon > 0) { + argv[argc] = (char*)malloc(sizeof("-e\0")); + strcpy(argv[argc], "-e\0"); + std::string epsilon_str = to_string(epsilon); + argv[argc+1] = (char*)malloc((epsilon_str.size()+1)*sizeof(char)); + for (int i = 0; i < epsilon_str.size(); ++i) + argv[argc+1][i] = epsilon_str[i]; + argv[argc+1][epsilon_str.size()] = '\0'; + argc += 2; + } + if (stop_energy > 0) { + argv[argc] = (char*)malloc(sizeof("--stop-energy\0")); + strcpy(argv[argc], "--stop-energy\0"); + std::string stop_energy_str = to_string(stop_energy); + argv[argc+1] = (char*)malloc((stop_energy_str.size()+1)*sizeof(char)); + for (int i = 0; i < stop_energy_str.size(); ++i) + argv[argc+1][i] = stop_energy_str[i]; + argv[argc+1][stop_energy_str.size()] = '\0'; + argc += 2; + } + if (skip_simplify) { + argv[argc] = (char*)malloc(sizeof("--skip-simplify\0")); + strcpy(argv[argc], "--skip-simplify\0"); + argc += 1; + } + if (no_binary) { + argv[argc] = (char*)malloc(sizeof("--no-binary\0")); + strcpy(argv[argc], "--no-binary\0"); + argc += 1; + } + if (no_color) { + argv[argc] = (char*)malloc(sizeof("--no-color\0")); + strcpy(argv[argc], "--no-color\0"); + argc += 1; + } + if (smooth) { + argv[argc] = (char*)malloc(sizeof("--smooth-open-boundary\0")); + strcpy(argv[argc], "--smooth-open-boundary\0"); + argc += 1; + } + if (export_raw) { + argv[argc] = (char*)malloc(sizeof("--export-raw\0")); + strcpy(argv[argc], "--export-raw\0"); + argc += 1; + } + if (manifold) { + argv[argc] = (char*)malloc(sizeof("--manifold-surface\0")); + strcpy(argv[argc], "--manifold-surface\0"); + argc += 1; + } + if (coarsen) { + argv[argc] = (char*)malloc(sizeof("--coarsen\0")); + strcpy(argv[argc], "--coarsen\0"); + argc += 1; + } + if (csg.size() > 0) { + argv[argc] = (char*)malloc(sizeof("--csg\0")); + strcpy(argv[argc], "--csg\0"); + argv[argc+1] = (char*)malloc((csg.size()+1)*sizeof(char)); + for (int i = 0; i < csg.size(); ++i) + argv[argc+1][i] = csg[i]; + argv[argc+1][csg.size()] = '\0'; + argc += 2; + } + if (disable_filter) { + argv[argc] = (char*)malloc(sizeof("--disable-filtering\0")); + strcpy(argv[argc], "--disable-filtering\0"); + argc += 1; + } + if (floodfill) { + argv[argc] = (char*)malloc(sizeof("--use-floodfill\0")); + strcpy(argv[argc], "--use-floodfill\0"); + argc += 1; + } + if (general_wn) { + argv[argc] = (char*)malloc(sizeof("--use-general-wn\0")); + strcpy(argv[argc], "--use-general-wn\0"); + argc += 1; + } + if (input_wn) { + argv[argc] = (char*)malloc(sizeof("--use-input-for-wn\0")); + strcpy(argv[argc], "--use-input-for-wn\0"); + argc += 1; + } + if (bg_mesh.size() > 0) { + argv[argc] = (char*)malloc(sizeof("--bg-mesh\0")); + strcpy(argv[argc], "--bg-mesh\0"); + argv[argc+1] = (char*)malloc((bg_mesh.size()+1)*sizeof(char)); + for (int i = 0; i < bg_mesh.size(); ++i) + argv[argc+1][i] = bg_mesh[i]; + argv[argc+1][bg_mesh.size()] = '\0'; + argc += 2; + } + argv[argc] = (char*)malloc(sizeof("--level\0")); + strcpy(argv[argc], "--level\0"); + argv[argc+1] = (char*)malloc(sizeof("3\0")); + strcpy(argv[argc+1], "3\0"); + argc += 2; + + runFTetWild(argc, argv); + } +}; + +ZENO_DEFNODE(FTetWild) +({ + {{"readpath", "input_dir"}, + {"string", "output_dir"}, + {"readpath", "tag", " "}, + {"enum none union intersection difference", "operation", "none"}, + {"float", "edge_length", "0"}, + {"float", "epsilon", "0"}, + {"float", "stop_energy", "0"}, + {"bool", "skip_simplify", "0"}, + {"bool", "no_binary", "0"}, + {"bool", "no_color", "0"}, + {"bool", "smooth_open_boundary", "0"}, + {"bool", "export_raw", "0"}, + {"bool", "manifold_surface", "0"}, + {"bool", "coarsen", "0"}, + {"readpath", "csg", " "}, + {"bool", "disable_filtering", "0"}, + {"bool", "use_floodfill", "0"}, + {"bool", "use_general_wn", "0"}, + {"bool", "use_input_for_wn", "0"}, + {"readpath", "bg_mesh", " "}}, + {}, + {}, + {"primitive"}, +}); + + +} // namespace zeno From 3ea12a20c2e44ba8dd2ad877696bd3e306de7725 Mon Sep 17 00:00:00 2001 From: seeeagull Date: Fri, 15 Dec 2023 13:59:45 +0800 Subject: [PATCH 071/106] upd instant_meshes tbb interface --- projects/Geometry/instant_meshes | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/Geometry/instant_meshes b/projects/Geometry/instant_meshes index e43215c14d..d9d8109e4e 160000 --- a/projects/Geometry/instant_meshes +++ b/projects/Geometry/instant_meshes @@ -1 +1 @@ -Subproject commit e43215c14df47f95426c8446d27c355c5ee45f05 +Subproject commit d9d8109e4e5be4a0890e09d5d89fb132055db8ef From 86daedb2bcc4c285143209c1780e2541a93248eb Mon Sep 17 00:00:00 2001 From: YingQ Date: Fri, 15 Dec 2023 14:53:52 +0800 Subject: [PATCH 072/106] literally all string node --- zeno/src/nodes/StringNodes.cpp | 95 ++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index b7cd94a146..45f65a6463 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -9,6 +9,7 @@ #include #include #include +#include namespace zeno { namespace { @@ -666,6 +667,100 @@ ZENDEFNODE(StringLength, { {"string"}, }); +struct StringSplitPath : zeno::INode { + virtual void apply() override { + auto string = get_input2("string"); + bool SplitExtension = get_input2("SplitExtension"); + std::string directory, filename, extension; + std::filesystem::path p(string); + directory = p.parent_path().string(); + filename = p.stem().string(); + extension = p.extension().string(); + if(!SplitExtension) filename += extension;//extension output is empty if SplitExtension is false + set_output2("directory", directory); + set_output2("filename", filename); + set_output2("extension", extension); + } +}; + +ZENDEFNODE(StringSplitPath, { + { + {"multiline_string", "string", ""}, + {"bool", "SplitExtension", "true"}, + }, + {{"string", "directory"}, + {"string", "filename"}, + {"string", "extension"}, + }, + {}, + {"string"}, +}); + +struct StringInsert : zeno::INode { + virtual void apply() override { + auto string = get_input2("string"); + auto substring = get_input2("substring"); + auto start = get_input2("start"); + auto output = string; + if (start < 0) { + start = output.size() + start; + if (start < 0) { + start = 0; + } + } else if (start > output.size()) { + start = output.size(); + } + output.insert(start, substring); + set_output2("string", output); + } +}; + +ZENDEFNODE(StringInsert, { + { + {"multiline_string", "string", ""}, + {"string", "substring", ""}, + {"int", "start", "0"}, + }, + {{"string", "string"}, + }, + {}, + {"string"}, +}); + +struct StringTrim : zeno::INode { + virtual void apply() override { + auto string = get_input2("string"); + auto trimleft = get_input2("trimleft"); + auto trimright = get_input2("trimright"); + std::string output = string; + if (!output.empty()) { + if (trimleft) { + output.erase(output.begin(), std::find_if(output.begin(), output.end(), [](int ch) { + return !std::isspace(ch); + })); + } + if (trimright) { + output.erase(std::find_if(output.rbegin(), output.rend(), [](int ch) { + return !std::isspace(ch); + }).base(), output.end()); + } + } + set_output2("string", output); + + } +}; + +ZENDEFNODE(StringTrim, { + { + {"string", "string", ""}, + {"bool", "trimleft", "true"}, + {"bool", "trimright", "true"}, + }, + {{"string", "string"}, + }, + {}, + {"string"}, +}); } } From cb55cb055e5c754008521445aafb56399a63b5ac Mon Sep 17 00:00:00 2001 From: YingQ Date: Fri, 15 Dec 2023 15:14:45 +0800 Subject: [PATCH 073/106] small improve --- zeno/src/nodes/StringNodes.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 45f65a6463..9d25b054ce 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -389,7 +389,7 @@ ZENDEFNODE(EndFrame, { {"fileio"}, });*/ -struct StringToNumber : zeno::INode {//todo?::Returns 0.0 if the string does not contain a number. +struct StringToNumber : zeno::INode { virtual void apply() override { auto in_str = get_input2("str"); auto type = get_input2("type"); @@ -685,7 +685,7 @@ struct StringSplitPath : zeno::INode { ZENDEFNODE(StringSplitPath, { { - {"multiline_string", "string", ""}, + {"readpath", "string", ""}, {"bool", "SplitExtension", "true"}, }, {{"string", "directory"}, @@ -696,7 +696,7 @@ ZENDEFNODE(StringSplitPath, { {"string"}, }); -struct StringInsert : zeno::INode { +struct StringInsert : zeno::INode {//if start is greater than string length, insert at the end; if start is less than 0, reverse counting from the end virtual void apply() override { auto string = get_input2("string"); auto substring = get_input2("substring"); From 5c895d284a459ab50f97fb2cc41df0a371372893 Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Fri, 15 Dec 2023 15:21:47 +0800 Subject: [PATCH 074/106] fix bug about unique view --- ui/zenomodel/src/subgraphmodel.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ui/zenomodel/src/subgraphmodel.cpp b/ui/zenomodel/src/subgraphmodel.cpp index d1df94d5ce..5d4f3f624c 100644 --- a/ui/zenomodel/src/subgraphmodel.cpp +++ b/ui/zenomodel/src/subgraphmodel.cpp @@ -327,10 +327,12 @@ void SubGraphModel::_uniqueView(const QModelIndex& index, bool bInSocket, bool b { const QModelIndex& keyIdx = pKeyObjModel->index(_r, 0); ZASSERT_EXIT(keyIdx.isValid()); - lst << keyIdx; + PARAM_LINKS links = keyIdx.data(ROLE_PARAM_LINKS).value(); + if (!links.isEmpty()) + lst << keyIdx; } } - else + if (lst.isEmpty()) { lst << sock; } From b5ad4d0d79d3bf57afad36bf25f8d885cc7a737e Mon Sep 17 00:00:00 2001 From: luzh Date: Fri, 15 Dec 2023 17:33:08 +0800 Subject: [PATCH 075/106] update version. --- ui/zenoedit/zenoedit.rc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ui/zenoedit/zenoedit.rc b/ui/zenoedit/zenoedit.rc index 2b7a7739ab..68cceb98fa 100644 --- a/ui/zenoedit/zenoedit.rc +++ b/ui/zenoedit/zenoedit.rc @@ -48,8 +48,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,2,1,1205 - PRODUCTVERSION 1,2,1,1205 + FILEVERSION 1,2,0,1215 + PRODUCTVERSION 1,2,0,1215 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -66,12 +66,12 @@ BEGIN BEGIN VALUE "CompanyName", "ZENUSTECH" VALUE "FileDescription", "Zeno Editor" - VALUE "FileVersion", "1.2.1.1205" + VALUE "FileVersion", "1.2.0.1215" VALUE "InternalName", "zenoedit.rc" VALUE "LegalCopyright", "Copyright (C) 2023" VALUE "OriginalFilename", "zenoedit.rc" VALUE "ProductName", "Zeno" - VALUE "ProductVersion", "1.2.1.1205" + VALUE "ProductVersion", "1.2.0.1215" END END BLOCK "VarFileInfo" From 1581e2559934641ab5f930a91869204e121dc1e9 Mon Sep 17 00:00:00 2001 From: seeeagull Date: Fri, 15 Dec 2023 17:48:15 +0800 Subject: [PATCH 076/106] add submodule --- .gitmodules | 3 +++ projects/Geometry/fTetWild | 1 + 2 files changed, 4 insertions(+) create mode 160000 projects/Geometry/fTetWild diff --git a/.gitmodules b/.gitmodules index fa55b9ab10..34e43b2ef6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -28,3 +28,6 @@ [submodule "projects/Geometry/instant_meshes"] path = projects/Geometry/instant_meshes url = https://github.com/seeeagull/instant-meshes.git +[submodule "projects/Geometry/fTetWild"] + path = projects/Geometry/fTetWild + url = https://github.com/seeeagull/fTetWild.git diff --git a/projects/Geometry/fTetWild b/projects/Geometry/fTetWild new file mode 160000 index 0000000000..b20ca8700d --- /dev/null +++ b/projects/Geometry/fTetWild @@ -0,0 +1 @@ +Subproject commit b20ca8700dbe80ea4929b5cbda44367cb258bbf7 From ec26c088102d977e08e3918d1d83893f295f1ac2 Mon Sep 17 00:00:00 2001 From: YingQ Date: Fri, 15 Dec 2023 18:39:31 +0800 Subject: [PATCH 077/106] Update StringNodes.cpp --- zeno/src/nodes/StringNodes.cpp | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 9d25b054ce..2420105086 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -669,13 +669,21 @@ ZENDEFNODE(StringLength, { struct StringSplitPath : zeno::INode { virtual void apply() override { - auto string = get_input2("string"); + auto stringpath = get_input2("string"); bool SplitExtension = get_input2("SplitExtension"); std::string directory, filename, extension; - std::filesystem::path p(string); - directory = p.parent_path().string(); - filename = p.stem().string(); - extension = p.extension().string(); + std::string::size_type last_slash_pos = stringpath.find_last_of("/\\"); + std::string::size_type last_dot_pos = stringpath.find_last_of('.'); + if (last_slash_pos == std::string::npos) { + directory = ""; + filename = (last_dot_pos == std::string::npos) ? stringpath : stringpath.substr(0, last_dot_pos); + extension = (last_dot_pos == std::string::npos) ? "" : stringpath.substr(last_dot_pos + 1); + } + else { + directory = stringpath.substr(0, last_slash_pos); + filename = stringpath.substr(last_slash_pos + 1, (last_dot_pos == std::string::npos ? stringpath.length() - last_slash_pos - 1 : last_dot_pos - last_slash_pos - 1)); + extension = (last_dot_pos == std::string::npos) ? "" : stringpath.substr(last_dot_pos + 1); + } if(!SplitExtension) filename += extension;//extension output is empty if SplitExtension is false set_output2("directory", directory); set_output2("filename", filename); From e7600f62d8cd717b65fb26062677e8497b88102d Mon Sep 17 00:00:00 2001 From: YingQ Date: Fri, 15 Dec 2023 18:46:16 +0800 Subject: [PATCH 078/106] remap auto compute --- zeno/src/nodes/StringNodes.cpp | 1 - zeno/src/nodes/prim/WBErode.cpp | 66 +++++---------------------------- 2 files changed, 10 insertions(+), 57 deletions(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 2420105086..0c2329ea38 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -9,7 +9,6 @@ #include #include #include -#include namespace zeno { namespace { diff --git a/zeno/src/nodes/prim/WBErode.cpp b/zeno/src/nodes/prim/WBErode.cpp index 4459610f92..4f2fd5a33f 100644 --- a/zeno/src/nodes/prim/WBErode.cpp +++ b/zeno/src/nodes/prim/WBErode.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -2332,62 +2333,6 @@ float chramp(const float inputData) { return outputData; } -// 计算图像的梯度 -void computeGradient(std::shared_ptr & hf, std::vector>& gradientX, std::vector>& gradientY) { - auto &ud = hf->userData(); - int height = ud.get2("nx"); - int width = ud.get2("nx"); - - gradientX.resize(height, std::vector(width)); - gradientY.resize(height, std::vector(width)); - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - if (x > 0 && x < width - 1) { - gradientX[y][x] = (hf->verts.attr("heightLayer")[y * width + x + 1] - hf->verts.attr("heightLayer")[y * width + x - 1]) / 2.0f; - } else { - gradientX[y][x] = 0.0f; - } - if (y > 0 && y < height - 1) { - gradientY[y][x] = (hf->verts.attr("heightLayer")[(y+1) * width + x] - hf->verts.attr("heightLayer")[(y - 1) * width + x]) / 2.0f; - } else { - gradientY[y][x] = 0.0f; - } - } - } -} - -// 计算图像的曲率 -void computeCurvature(const std::vector>& gradientX, const std::vector>& gradientY, std::vector>& curvature) { - int height = gradientX.size(); - int width = gradientX[0].size(); - - curvature.resize(height, std::vector(width)); - - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - float dx = gradientX[y][x]; - float dy = gradientY[y][x]; - float dxx = 0.0f; - float dyy = 0.0f; - float dxy = 0.0f; - - if (x > 0 && x < width - 1) { - dxx = gradientX[y][x + 1] - 2.0f * dx + gradientX[y][x - 1]; - } - - if (y > 0 && y < height - 1) { - dyy = gradientY[y + 1][x] - 2.0f * dy + gradientY[y - 1][x]; - } - - if (x > 0 && x < width - 1 && y > 0 && y < height - 1) { - dxy = (gradientX[y + 1][x + 1] - gradientX[y + 1][x - 1] - gradientX[y - 1][x + 1] + gradientX[y - 1][x - 1]) / 4.0f; - } - - curvature[y][x] = (dxx * dyy - dxy * dxy) / ((dxx + dyy) * (dxx + dyy) + 1e-6f); - } - } -} struct HF_maskByFeature : INode { void apply() override { @@ -2634,6 +2579,7 @@ struct HF_remap : INode { remapLayer); } auto& var = terrain->verts.attr(remapLayer); + auto autoCompute = get_input2("Auto Compute input range"); auto inMin = get_input2("input min"); auto inMax = get_input2("input max"); auto outMin = get_input2("output min"); @@ -2641,6 +2587,13 @@ struct HF_remap : INode { auto curve = get_input("remap ramp"); auto clampMin = get_input2("clamp min"); auto clampMax = get_input2("clamp max"); + + if (autoCompute) { + inMin = zeno::parallel_reduce_array(var.size(), var[0], [&] (size_t i) -> float { return var[i]; }, + [&] (float i, float j) -> float { return zeno::min(i, j); }); + inMax = zeno::parallel_reduce_array(var.size(), var[0], [&] (size_t i) -> float { return var[i]; }, + [&] (float i, float j) -> float { return zeno::max(i, j); }); + } #pragma omp parallel for for (int i = 0; i < terrain->verts.size(); i++) { @@ -2686,6 +2639,7 @@ ZENDEFNODE(HF_remap, { /* inputs: */ { "prim", {"string", "remap layer", "height"}, + {"bool", "Auto Compute input range", "1"}, {"float", "input min", "0"}, {"float", "input max", "1"}, {"float", "output min", "0"}, From 46ea28026cbf94774322aab34dea7d5976318a55 Mon Sep 17 00:00:00 2001 From: littlemine Date: Fri, 15 Dec 2023 20:08:21 +0800 Subject: [PATCH 079/106] compact co-vert --- projects/CUDA/zpc | 2 +- zenovis/xinxinoptix/optixPathTracer.cpp | 48 +++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/projects/CUDA/zpc b/projects/CUDA/zpc index 2cc395e980..e029d74900 160000 --- a/projects/CUDA/zpc +++ b/projects/CUDA/zpc @@ -1 +1 @@ -Subproject commit 2cc395e980c311bc2ef04322c915124127237810 +Subproject commit e029d74900e532312763c39d78708395b018da0c diff --git a/zenovis/xinxinoptix/optixPathTracer.cpp b/zenovis/xinxinoptix/optixPathTracer.cpp index 5c60ff4e50..402c80650e 100644 --- a/zenovis/xinxinoptix/optixPathTracer.cpp +++ b/zenovis/xinxinoptix/optixPathTracer.cpp @@ -32,6 +32,8 @@ #include "magic_enum.hpp" #include "optixPathTracer.h" +#include +#include #include #include #include @@ -305,6 +307,52 @@ static std::vector g_lightMark = //TRIANGLE_COUNT 0 }; +static void compact_triangle_vertex_attribute(const std::vector& attrib, std::vector& compactAttrib, std::vector& vertIdsPerTri) { + using id_t = unsigned int; + using kv_t = std::pair; + + std::vector kvs(attrib.size()); +#pragma omp parallel for + for (id_t i = 0; i < attrib.size(); ++i) + kvs[i] = std::make_pair(attrib[i], (id_t)i); + + // sort + auto compOp = [](const kv_t &a, const kv_t &b) { + if (a.first.x < b.first.x) return true; + else if (a.first.x > b.first.x) return false; + if (a.first.y < b.first.y) return true; + else if (a.first.y > b.first.y) return false; + if (a.first.z < b.first.z) return true; + + return false; + }; + zeno::parallel_sort(std::begin(kvs), std::end(kvs), compOp); + + // excl scan + std::vector mark(kvs.size()), offset(kvs.size()); +#pragma omp parallel for + for (id_t i = /*not 0*/1; i < kvs.size(); ++i) + if (kvs[i].first.x == kvs[i - 1].first.x && + kvs[i].first.y == kvs[i - 1].first.y && + kvs[i].first.z == kvs[i - 1].first.z) + mark[i] = 1; + zeno::parallel_inclusive_scan_sum(std::begin(mark), std::end(mark), + std::begin(offset), [](const auto &v) { return v; }); + auto numNewAttribs = offset.back() + 1; + mark[0] = 1; + + compactAttrib.resize(numNewAttribs); + vertIdsPerTri.resize(attrib.size()); +#pragma omp parallel for + for (id_t i = 0; i < kvs.size(); ++i) { + auto originalIndex = kvs[i].second; + auto newIndex = offset[i]; + vertIdsPerTri[originalIndex] = newIndex; + if (mark[i]) + compactAttrib[offset[i]] = kvs[i].first; + } +} + struct LightsWrapper { std::vector _planeLightGeo; std::vector _sphereLightGeo; From 4a5c986787438d8727c2aae8bdc4ccf62f86691d Mon Sep 17 00:00:00 2001 From: HansWanglin Date: Fri, 15 Dec 2023 22:19:29 +0800 Subject: [PATCH 080/106] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 54928f169f..b4c9720fa0 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Open-source node system framework, to change your algorithmic code into useful tools to create much more complicated simulations! - + ZENO is an open-source, Node based 3D system able to produce cinematic physics effects at High Efficiency, it was designed for large scale simulations and has been tested on complex setups. Aside of its simulation Tools, ZENO provides necessary visualization nodes for users to import and run simulations if you feel that the current software you are using is too slow. From ab04fa2cb6abe8f8a4eded196ba6b4bfbf35f03a Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Fri, 15 Dec 2023 23:21:49 +0800 Subject: [PATCH 081/106] reduce mem requirement --- zenovis/xinxinoptix/optixPathTracer.cpp | 321 +++++++++++++++++------- 1 file changed, 234 insertions(+), 87 deletions(-) diff --git a/zenovis/xinxinoptix/optixPathTracer.cpp b/zenovis/xinxinoptix/optixPathTracer.cpp index 5c60ff4e50..21ac6659a4 100644 --- a/zenovis/xinxinoptix/optixPathTracer.cpp +++ b/zenovis/xinxinoptix/optixPathTracer.cpp @@ -166,6 +166,86 @@ typedef Record HitGroupRecord; //{ //float transform[12]; //}; +#ifdef USE_SHORT_COMPACT +uchar4 toRGBA8(float4 in) +{ + return make_uchar4((unsigned char)(in.x*256.0), + (unsigned char)(in.y*256.0), + (unsigned char)(in.z*256.0), + (unsigned char)(in.w*256.0)); +} +ushort2 rgba8ToUshort2(uchar4 in) +{ + uchar4 rgba = toRGBA8(in); + unsigned short x = rgba.x; + x = x<<16 + rgba.y; + unsigned short y = rgba.z<<16 + rgba.w; +} +ushort2 toHalfColor(float4 in) +{ + return make_ushort3((unsigned short)(in.x*65536.0f), + (unsigned short)(in.y*65536.0f), + (unsigned short)(in.z*65536.0f)); +} + +ushort2 toHalf(float4 in) +{ + return make_ushort3((unsigned short)(in.x*65536.0f), + (unsigned short)(in.y*65536.0f), + (unsigned short)(in.z*65536.0f)); +} + +ushort2 halfNormal(float4 in) +{ + float3 val = make_float3((in.x + 1.0f)/2.0f, + (in.y + 1.0f)/2.0f, + (in.z + 1.0f)/2.0f); + val = normalize(val); + + return make_ushort3((unsigned short)(val.x*65536.0f), + (unsigned short)(val.y*65536.0f), + (unsigned short)(val.z*65536.0f)); +} +#elifdef USE_SHORT +ushort3 toHalfColor(float4 in) +{ + return make_ushort3((unsigned short)(in.x*65536.0f), + (unsigned short)(in.y*65536.0f), + (unsigned short)(in.z*65536.0f)); +} +ushort3 toHalf(float4 in) +{ + return make_ushort3((unsigned short)(in.x*65536.0f), + (unsigned short)(in.y*65536.0f), + (unsigned short)(in.z*65536.0f)); +} + +ushort3 halfNormal(float4 in) +{ + float3 val = make_float3((in.x + 1.0f)/2.0f, + (in.y + 1.0f)/2.0f, + (in.z + 1.0f)/2.0f); + val = normalize(val); + + return make_ushort3((unsigned short)(val.x*65536.0f), + (unsigned short)(val.y*65536.0f), + (unsigned short)(val.z*65536.0f)); +} +#else +float4 toHalfColor(float4 in) +{ + return in; +} +float4 toHalf(float4 in) +{ + return in; +} + +float4 halfNormal(float4 in) +{ + return in; +} +#endif std::optional> output_buffer_o; std::optional> output_buffer_color; @@ -265,45 +345,85 @@ struct smallMesh{ //const int32_t TRIANGLE_COUNT = 32; //const int32_t MAT_COUNT = 5; - -static std::vector g_vertices= // TRIANGLE_COUNT*3 -{ - {0,0,0}, - {0,0,0}, - {0,0,0}, -}; -static std::vector g_clr= // TRIANGLE_COUNT*3 -{ - {0,0,0}, - {0,0,0}, - {0,0,0}, -}; -static std::vector g_nrm= // TRIANGLE_COUNT*3 -{ - {0,0,0}, - {0,0,0}, - {0,0,0}, -}; -static std::vector g_uv= // TRIANGLE_COUNT*3 -{ - {0,0,0}, - {0,0,0}, - {0,0,0}, -}; -static std::vector g_tan= // TRIANGLE_COUNT*3 -{ - {0,0,0}, - {0,0,0}, - {0,0,0}, -}; -static std::vector g_mat_indices= // TRIANGLE_COUNT -{ - 0,0,0, -}; -static std::vector g_lightMark = //TRIANGLE_COUNT -{ - 0 -}; +#ifdef USE_SHORT + static std::vector g_vertices= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_clr= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_nrm= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_uv= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_tan= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_mat_indices= // TRIANGLE_COUNT + { + 0,0,0, + }; + static std::vector g_lightMark = //TRIANGLE_COUNT + { + 0 + }; +#else + static std::vector g_vertices= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_clr= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_nrm= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_uv= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_tan= // TRIANGLE_COUNT*3 + { + {0,0,0}, + {0,0,0}, + {0,0,0}, + }; + static std::vector g_mat_indices= // TRIANGLE_COUNT + { + 0,0,0, + }; + static std::vector g_lightMark = //TRIANGLE_COUNT + { + 0 + }; +#endif struct LightsWrapper { std::vector _planeLightGeo; @@ -1313,10 +1433,17 @@ static void createSBT( PathTracerState& state ) hitgroup_records[sbt_idx] = {}; hitgroup_records[sbt_idx].data.uniforms = reinterpret_cast( (CUdeviceptr)state.d_uniforms ); +#ifdef USE_SHORT + hitgroup_records[sbt_idx].data.uv = reinterpret_cast( (CUdeviceptr)state.d_uv ); + hitgroup_records[sbt_idx].data.nrm = reinterpret_cast( (CUdeviceptr)state.d_nrm ); + hitgroup_records[sbt_idx].data.clr = reinterpret_cast( (CUdeviceptr)state.d_clr ); + hitgroup_records[sbt_idx].data.tan = reinterpret_cast( (CUdeviceptr)state.d_tan ); +#else hitgroup_records[sbt_idx].data.uv = reinterpret_cast( (CUdeviceptr)state.d_uv ); hitgroup_records[sbt_idx].data.nrm = reinterpret_cast( (CUdeviceptr)state.d_nrm ); hitgroup_records[sbt_idx].data.clr = reinterpret_cast( (CUdeviceptr)state.d_clr ); hitgroup_records[sbt_idx].data.tan = reinterpret_cast( (CUdeviceptr)state.d_tan ); +#endif hitgroup_records[sbt_idx].data.lightMark = reinterpret_cast( (CUdeviceptr)state.d_lightMark ); hitgroup_records[sbt_idx].data.auxOffset = reinterpret_cast( (CUdeviceptr)state.vertexAuxOffsetGlobal ); @@ -1825,10 +1952,17 @@ void CopyInstMeshToGlobalMesh() for (size_t i = 0; i < vertices.size(); ++i) { g_vertices[vertsOffset + i] = vertices[i]; +#ifdef USE_SHORT + g_clr[vertsOffset + i] = toHalf(clr[i]); + g_nrm[vertsOffset + i] = halfNormal(nrm[i]); + g_uv[vertsOffset + i] = toHalf(uv[i]); + g_tan[vertsOffset + i] = halfNormal(tan[i]); +#else g_clr[vertsOffset + i] = clr[i]; g_nrm[vertsOffset + i] = nrm[i]; g_uv[vertsOffset + i] = uv[i]; g_tan[vertsOffset + i] = tan[i]; +#endif } for (size_t i = 0; i < vertices.size() / 3; ++i) { @@ -1852,7 +1986,11 @@ void UpdateMeshGasAndIas(bool staticNeedUpdate) // no archieve inst func in using20xx if (using20xx) { +#ifdef USE_SHORT + const size_t vertices_size_in_bytes = g_vertices.size() * sizeof( ushort3 ); +#else const size_t vertices_size_in_bytes = g_vertices.size() * sizeof( Vertex ); +#endif // CUDA_CHECK( cudaMalloc( reinterpret_cast( &state.d_vertices.reset() ), vertices_size_in_bytes ) ); // CUDA_CHECK( cudaMemcpy( // reinterpret_cast( (CUdeviceptr&)state.d_vertices ), @@ -1911,8 +2049,13 @@ void UpdateMeshGasAndIas(bool staticNeedUpdate) #define WXL 1 std::cout << "begin copy\n"; timer.tick(); +#ifdef USE_SHORT + size_t vertices_size_in_bytes = g_vertices.size() * sizeof(ushort3); + size_t static_vertices_size_in_bytes = g_staticVertNum * sizeof(ushort3); +#else size_t vertices_size_in_bytes = g_vertices.size() * sizeof(Vertex); size_t static_vertices_size_in_bytes = g_staticVertNum * sizeof(Vertex); +#endif size_t dynamic_vertices_size_in_bytes = vertices_size_in_bytes - static_vertices_size_in_bytes; bool realloced; size_t offset = 0; @@ -1920,7 +2063,11 @@ void UpdateMeshGasAndIas(bool staticNeedUpdate) auto updateRange = [&vertices_size_in_bytes, &dynamic_vertices_size_in_bytes, &realloced, &offset, &numBytes]() { if (!realloced && WXL) { +#ifdef USE_SHORT + offset = g_staticVertNum * sizeof(ushort3); +#else offset = g_staticVertNum * sizeof(Vertex); +#endif numBytes = dynamic_vertices_size_in_bytes; } else { offset = 0; @@ -2775,81 +2922,81 @@ static void updateStaticDrawObjects() { 0, }; - g_clr[(n + i) * 3 + 0] = { + g_clr[(n + i) * 3 + 0] = toHalf({ dat.getAttr("clr")[dat.tris[i * 3 + 0] * 3 + 0], dat.getAttr("clr")[dat.tris[i * 3 + 0] * 3 + 1], dat.getAttr("clr")[dat.tris[i * 3 + 0] * 3 + 2], 0, - }; - g_clr[(n + i) * 3 + 1] = { + }); + g_clr[(n + i) * 3 + 1] = toHalf({ dat.getAttr("clr")[dat.tris[i * 3 + 1] * 3 + 0], dat.getAttr("clr")[dat.tris[i * 3 + 1] * 3 + 1], dat.getAttr("clr")[dat.tris[i * 3 + 1] * 3 + 2], 0, - }; - g_clr[(n + i) * 3 + 2] = { + }); + g_clr[(n + i) * 3 + 2] = toHalf({ dat.getAttr("clr")[dat.tris[i * 3 + 2] * 3 + 0], dat.getAttr("clr")[dat.tris[i * 3 + 2] * 3 + 1], dat.getAttr("clr")[dat.tris[i * 3 + 2] * 3 + 2], 0, - }; + }); - g_nrm[(n + i) * 3 + 0] = { + g_nrm[(n + i) * 3 + 0] = halfNormal({ dat.getAttr("nrm")[dat.tris[i * 3 + 0] * 3 + 0], dat.getAttr("nrm")[dat.tris[i * 3 + 0] * 3 + 1], dat.getAttr("nrm")[dat.tris[i * 3 + 0] * 3 + 2], 0, - }; - g_nrm[(n + i) * 3 + 1] = { + }); + g_nrm[(n + i) * 3 + 1] = halfNormal({ dat.getAttr("nrm")[dat.tris[i * 3 + 1] * 3 + 0], dat.getAttr("nrm")[dat.tris[i * 3 + 1] * 3 + 1], dat.getAttr("nrm")[dat.tris[i * 3 + 1] * 3 + 2], 0, - }; - g_nrm[(n + i) * 3 + 2] = { + }); + g_nrm[(n + i) * 3 + 2] = halfNormal({ dat.getAttr("nrm")[dat.tris[i * 3 + 2] * 3 + 0], dat.getAttr("nrm")[dat.tris[i * 3 + 2] * 3 + 1], dat.getAttr("nrm")[dat.tris[i * 3 + 2] * 3 + 2], 0, - }; + }); - g_uv[(n + i) * 3 + 0] = { + g_uv[(n + i) * 3 + 0] = toHalf({ dat.getAttr("uv")[dat.tris[i * 3 + 0] * 3 + 0], dat.getAttr("uv")[dat.tris[i * 3 + 0] * 3 + 1], dat.getAttr("uv")[dat.tris[i * 3 + 0] * 3 + 2], 0, - }; - g_uv[(n + i) * 3 + 1] = { + }); + g_uv[(n + i) * 3 + 1] = toHalf({ dat.getAttr("uv")[dat.tris[i * 3 + 1] * 3 + 0], dat.getAttr("uv")[dat.tris[i * 3 + 1] * 3 + 1], dat.getAttr("uv")[dat.tris[i * 3 + 1] * 3 + 2], 0, - }; - g_uv[(n + i) * 3 + 2] = { + }); + g_uv[(n + i) * 3 + 2] = toHalf({ dat.getAttr("uv")[dat.tris[i * 3 + 2] * 3 + 0], dat.getAttr("uv")[dat.tris[i * 3 + 2] * 3 + 1], dat.getAttr("uv")[dat.tris[i * 3 + 2] * 3 + 2], 0, - }; + }); - g_tan[(n + i) * 3 + 0] = { + g_tan[(n + i) * 3 + 0] = halfNormal({ dat.getAttr("tang")[dat.tris[i * 3 + 0] * 3 + 0], dat.getAttr("tang")[dat.tris[i * 3 + 0] * 3 + 1], dat.getAttr("tang")[dat.tris[i * 3 + 0] * 3 + 2], 0, - }; - g_tan[(n + i) * 3 + 1] = { + }); + g_tan[(n + i) * 3 + 1] = halfNormal({ dat.getAttr("tang")[dat.tris[i * 3 + 1] * 3 + 0], dat.getAttr("tang")[dat.tris[i * 3 + 1] * 3 + 1], dat.getAttr("tang")[dat.tris[i * 3 + 1] * 3 + 2], 0, - }; - g_tan[(n + i) * 3 + 2] = { + }); + g_tan[(n + i) * 3 + 2] = halfNormal({ dat.getAttr("tang")[dat.tris[i * 3 + 2] * 3 + 0], dat.getAttr("tang")[dat.tris[i * 3 + 2] * 3 + 1], dat.getAttr("tang")[dat.tris[i * 3 + 2] * 3 + 2], 0, - }; + }); } n += dat.tris.size() / 3; } @@ -2905,81 +3052,81 @@ static void updateDynamicDrawObjects() { 0, }; - g_clr[g_staticVertNum + (n + i) * 3 + 0] = { + g_clr[g_staticVertNum + (n + i) * 3 + 0] = toHalf({ dat.getAttr("clr")[dat.tris[i * 3 + 0] * 3 + 0], dat.getAttr("clr")[dat.tris[i * 3 + 0] * 3 + 1], dat.getAttr("clr")[dat.tris[i * 3 + 0] * 3 + 2], 0, - }; - g_clr[g_staticVertNum + (n + i) * 3 + 1] = { + }); + g_clr[g_staticVertNum + (n + i) * 3 + 1] = toHalf({ dat.getAttr("clr")[dat.tris[i * 3 + 1] * 3 + 0], dat.getAttr("clr")[dat.tris[i * 3 + 1] * 3 + 1], dat.getAttr("clr")[dat.tris[i * 3 + 1] * 3 + 2], 0, - }; - g_clr[g_staticVertNum + (n + i) * 3 + 2] = { + }); + g_clr[g_staticVertNum + (n + i) * 3 + 2] = toHalf({ dat.getAttr("clr")[dat.tris[i * 3 + 2] * 3 + 0], dat.getAttr("clr")[dat.tris[i * 3 + 2] * 3 + 1], dat.getAttr("clr")[dat.tris[i * 3 + 2] * 3 + 2], 0, - }; + }); - g_nrm[g_staticVertNum + (n + i) * 3 + 0] = { + g_nrm[g_staticVertNum + (n + i) * 3 + 0] = halfNormal({ dat.getAttr("nrm")[dat.tris[i * 3 + 0] * 3 + 0], dat.getAttr("nrm")[dat.tris[i * 3 + 0] * 3 + 1], dat.getAttr("nrm")[dat.tris[i * 3 + 0] * 3 + 2], 0, - }; - g_nrm[g_staticVertNum + (n + i) * 3 + 1] = { + }); + g_nrm[g_staticVertNum + (n + i) * 3 + 1] = halfNormal({ dat.getAttr("nrm")[dat.tris[i * 3 + 1] * 3 + 0], dat.getAttr("nrm")[dat.tris[i * 3 + 1] * 3 + 1], dat.getAttr("nrm")[dat.tris[i * 3 + 1] * 3 + 2], 0, - }; - g_nrm[g_staticVertNum + (n + i) * 3 + 2] = { + }); + g_nrm[g_staticVertNum + (n + i) * 3 + 2] = halfNormal({ dat.getAttr("nrm")[dat.tris[i * 3 + 2] * 3 + 0], dat.getAttr("nrm")[dat.tris[i * 3 + 2] * 3 + 1], dat.getAttr("nrm")[dat.tris[i * 3 + 2] * 3 + 2], 0, - }; + }); - g_uv[g_staticVertNum + (n + i) * 3 + 0] = { + g_uv[g_staticVertNum + (n + i) * 3 + 0] = toHalf({ dat.getAttr("uv")[dat.tris[i * 3 + 0] * 3 + 0], dat.getAttr("uv")[dat.tris[i * 3 + 0] * 3 + 1], dat.getAttr("uv")[dat.tris[i * 3 + 0] * 3 + 2], 0, - }; - g_uv[g_staticVertNum + (n + i) * 3 + 1] = { + }); + g_uv[g_staticVertNum + (n + i) * 3 + 1] = toHalf({ dat.getAttr("uv")[dat.tris[i * 3 + 1] * 3 + 0], dat.getAttr("uv")[dat.tris[i * 3 + 1] * 3 + 1], dat.getAttr("uv")[dat.tris[i * 3 + 1] * 3 + 2], 0, - }; - g_uv[g_staticVertNum + (n + i) * 3 + 2] = { + }); + g_uv[g_staticVertNum + (n + i) * 3 + 2] = toHalf({ dat.getAttr("uv")[dat.tris[i * 3 + 2] * 3 + 0], dat.getAttr("uv")[dat.tris[i * 3 + 2] * 3 + 1], dat.getAttr("uv")[dat.tris[i * 3 + 2] * 3 + 2], 0, - }; + }); - g_tan[g_staticVertNum + (n + i) * 3 + 0] = { + g_tan[g_staticVertNum + (n + i) * 3 + 0] = halfNormal({ dat.getAttr("tang")[dat.tris[i * 3 + 0] * 3 + 0], dat.getAttr("tang")[dat.tris[i * 3 + 0] * 3 + 1], dat.getAttr("tang")[dat.tris[i * 3 + 0] * 3 + 2], 0, - }; - g_tan[g_staticVertNum + (n + i) * 3 + 1] = { + }); + g_tan[g_staticVertNum + (n + i) * 3 + 1] = halfNormal({ dat.getAttr("tang")[dat.tris[i * 3 + 1] * 3 + 0], dat.getAttr("tang")[dat.tris[i * 3 + 1] * 3 + 1], dat.getAttr("tang")[dat.tris[i * 3 + 1] * 3 + 2], 0, - }; - g_tan[g_staticVertNum + (n + i) * 3 + 2] = { + }); + g_tan[g_staticVertNum + (n + i) * 3 + 2] = halfNormal({ dat.getAttr("tang")[dat.tris[i * 3 + 2] * 3 + 0], dat.getAttr("tang")[dat.tris[i * 3 + 2] * 3 + 1], dat.getAttr("tang")[dat.tris[i * 3 + 2] * 3 + 2], 0, - }; + }); } n += dat.tris.size() / 3; } From e800207b75df6fba4558e20e06961979afa2e51b Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Fri, 15 Dec 2023 23:23:55 +0800 Subject: [PATCH 082/106] reduce mem requirement --- zenovis/xinxinoptix/DeflMatShader.cu | 48 +++++++++++++-------------- zenovis/xinxinoptix/optixPathTracer.h | 15 ++++++++- zenovis/xinxinoptix/zxxglslvec.h | 30 +++++++++++++++++ 3 files changed, 68 insertions(+), 25 deletions(-) diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index 39662f612a..8a431e708c 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -253,11 +253,11 @@ extern "C" __global__ void __anyhit__shadow_cutout() /* MODMA */ float2 barys = optixGetTriangleBarycentrics(); - float3 n0 = normalize( *(float3*)&(rt_data->nrm[ vert_idx_offset+0 ]) ); + float3 n0 = normalize( decodeNormal(rt_data->nrm[ vert_idx_offset+0 ]) ); n0 = dot(n0, N_Local)>0.8f?n0:N_Local; - float3 n1 = normalize( *(float3*)&(rt_data->nrm[ vert_idx_offset+1 ]) ); + float3 n1 = normalize( decodeNormal(rt_data->nrm[ vert_idx_offset+1 ]) ); n1 = dot(n1, N_Local)>0.8f?n1:N_Local; - float3 n2 = normalize( *(float3*)&(rt_data->nrm[ vert_idx_offset+2 ]) ); + float3 n2 = normalize( decodeNormal(rt_data->nrm[ vert_idx_offset+2 ]) ); n2 = dot(n2, N_Local)>0.8f?n2:N_Local; N_Local = normalize(interp(barys, n0, n1, n2)); @@ -273,15 +273,15 @@ extern "C" __global__ void __anyhit__shadow_cutout() attrs.pos = P; attrs.nrm = N; - const float3& uv0 = *(float3*)&( rt_data->uv[ vert_idx_offset+0 ] ); - const float3& uv1 = *(float3*)&( rt_data->uv[ vert_idx_offset+1 ] ); - const float3& uv2 = *(float3*)&( rt_data->uv[ vert_idx_offset+2 ] ); - const float3& clr0 = *(float3*)&( rt_data->clr[ vert_idx_offset+0 ] ); - const float3& clr1 = *(float3*)&( rt_data->clr[ vert_idx_offset+1 ] ); - const float3& clr2 = *(float3*)&( rt_data->clr[ vert_idx_offset+2 ] ); - const float3& tan0 = *(float3*)&( rt_data->tan[ vert_idx_offset+0 ] ); - const float3& tan1 = *(float3*)&( rt_data->tan[ vert_idx_offset+1 ] ); - const float3& tan2 = *(float3*)&( rt_data->tan[ vert_idx_offset+2 ] ); + const float3& uv0 = decodeColor( rt_data->uv[ vert_idx_offset+0 ] ); + const float3& uv1 = decodeColor( rt_data->uv[ vert_idx_offset+1 ] ); + const float3& uv2 = decodeColor( rt_data->uv[ vert_idx_offset+2 ] ); + const float3& clr0 = decodeColor( rt_data->clr[ vert_idx_offset+0 ] ); + const float3& clr1 = decodeColor( rt_data->clr[ vert_idx_offset+1 ] ); + const float3& clr2 = decodeColor( rt_data->clr[ vert_idx_offset+2 ] ); + const float3& tan0 = decodeNormal( rt_data->tan[ vert_idx_offset+0 ] ); + const float3& tan1 = decodeNormal( rt_data->tan[ vert_idx_offset+1 ] ); + const float3& tan2 = decodeNormal( rt_data->tan[ vert_idx_offset+2 ] ); attrs.uv = interp(barys, uv0, uv1, uv2);//todo later attrs.clr = interp(barys, clr0, clr1, clr2); @@ -506,15 +506,15 @@ extern "C" __global__ void __closesthit__radiance() float3 N = N_World; attrs.nrm = N; - const float3& uv0 = *(float3*)&( rt_data->uv[ vert_idx_offset+0 ] ); - const float3& uv1 = *(float3*)&( rt_data->uv[ vert_idx_offset+1 ] ); - const float3& uv2 = *(float3*)&( rt_data->uv[ vert_idx_offset+2 ] ); - const float3& clr0 = *(float3*)&( rt_data->clr[ vert_idx_offset+0 ] ); - const float3& clr1 = *(float3*)&( rt_data->clr[ vert_idx_offset+1 ] ); - const float3& clr2 = *(float3*)&( rt_data->clr[ vert_idx_offset+2 ] ); - const float3& tan0 = *(float3*)&( rt_data->tan[ vert_idx_offset+0 ] ); - const float3& tan1 = *(float3*)&( rt_data->tan[ vert_idx_offset+1 ] ); - const float3& tan2 = *(float3*)&( rt_data->tan[ vert_idx_offset+2 ] ); + const float3& uv0 = decodeColor( rt_data->uv[ vert_idx_offset+0 ] ); + const float3& uv1 = decodeColor( rt_data->uv[ vert_idx_offset+1 ] ); + const float3& uv2 = decodeColor( rt_data->uv[ vert_idx_offset+2 ] ); + const float3& clr0 = decodeColor( rt_data->clr[ vert_idx_offset+0 ] ); + const float3& clr1 = decodeColor( rt_data->clr[ vert_idx_offset+1 ] ); + const float3& clr2 = decodeColor( rt_data->clr[ vert_idx_offset+2 ] ); + const float3& tan0 = decodeNormal( rt_data->tan[ vert_idx_offset+0 ] ); + const float3& tan1 = decodeNormal( rt_data->tan[ vert_idx_offset+1 ] ); + const float3& tan2 = decodeNormal( rt_data->tan[ vert_idx_offset+2 ] ); attrs.uv = interp(barys, uv0, uv1, uv2);//todo later attrs.clr = interp(barys, clr0, clr1, clr2); @@ -540,13 +540,13 @@ extern "C" __global__ void __closesthit__radiance() #else - float3 n0 = normalize( *(float3*)&(rt_data->nrm[ vert_idx_offset+0 ]) ); + float3 n0 = normalize( decodeNormal(rt_data->nrm[ vert_idx_offset+0 ]) ); n0 = dot(n0, N_Local)>(1-mats.smoothness)?n0:N_Local; - float3 n1 = normalize( *(float3*)&(rt_data->nrm[ vert_idx_offset+1 ]) ); + float3 n1 = normalize( decodeNormal(rt_data->nrm[ vert_idx_offset+1 ]) ); n1 = dot(n1, N_Local)>(1-mats.smoothness)?n1:N_Local; - float3 n2 = normalize( *(float3*)&(rt_data->nrm[ vert_idx_offset+2 ]) ); + float3 n2 = normalize( decodeNormal(rt_data->nrm[ vert_idx_offset+2 ]) ); n2 = dot(n2, N_Local)>(1-mats.smoothness)?n2:N_Local; N_Local = normalize(interp(barys, n0, n1, n2)); diff --git a/zenovis/xinxinoptix/optixPathTracer.h b/zenovis/xinxinoptix/optixPathTracer.h index 04b8e69488..1bcb138fcc 100644 --- a/zenovis/xinxinoptix/optixPathTracer.h +++ b/zenovis/xinxinoptix/optixPathTracer.h @@ -1,5 +1,5 @@ #pragma once - +#define USE_SHORT 1 #include #include @@ -253,13 +253,26 @@ struct MissData { float4 bg_color; }; + struct HitGroupData { //float4* vertices; +#ifdef USE_SHORT_COMPACT + ushort2* uv; + ushort2* nrm; + ushort2* clr; + ushort2* tan; +#elifdef USE_SHORT + ushort3* uv; + ushort3* nrm; + ushort3* clr; + ushort3* tan; +#else float4* uv; float4* nrm; float4* clr; float4* tan; +#endif unsigned short* lightMark; uint32_t* auxOffset; diff --git a/zenovis/xinxinoptix/zxxglslvec.h b/zenovis/xinxinoptix/zxxglslvec.h index 3c59ff024d..7071b10f0d 100644 --- a/zenovis/xinxinoptix/zxxglslvec.h +++ b/zenovis/xinxinoptix/zxxglslvec.h @@ -1329,4 +1329,34 @@ __forceinline__ __device__ vec2 shuffled_scrambled_sobol_2d(unsigned int index, p.x = nested_uniform_scramble(p.x, hash_combine(seed, 0u)); p.y = nested_uniform_scramble(p.y, hash_combine(seed, 1u)); return vec2(p.x, p.y)*exp2(-32.); +} + +__forceinline__ __device__ float3 decodeColor(uchar3 c) +{ + vec3 cout = vec3((float)(c.x), (float)(c.y), (float)(c.z)) / 255.0f; + return make_float3(cout.x, cout.y, cout.z); +} +__forceinline__ __device__ float3 decodeNormal(uchar3 c) +{ + vec3 cout = vec3((float)(c.x), (float)(c.y), (float)(c.z)) / 255.0 * 2.0f - 1.0f; + return make_float3(cout.x, cout.y, cout.z); +} + +__forceinline__ __device__ float3 decodeColor(ushort3 c) +{ + vec3 cout = vec3((float)(c.x), (float)(c.y), (float)(c.z)) / 65536.0f; + return make_float3(cout.x, cout.y, cout.z); +} +__forceinline__ __device__ float3 decodeNormal(ushort3 c) +{ + vec3 cout = vec3((float)(c.x), (float)(c.y), (float)(c.z)) / 65536.0f * 2.0f - 1.0f; + return make_float3(cout.x, cout.y, cout.z); +} +__forceinline__ __device__ float3 decodeColor(float4 c) +{ + return make_float3(c.x, c.y, c.z); +} +__forceinline__ __device__ float3 decodeNormal(float4 c) +{ + return make_float3(c.x, c.y, c.z); } \ No newline at end of file From ce5119e4ddde8b46d2e7b59760d04c711bbcc27f Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Fri, 15 Dec 2023 23:36:23 +0800 Subject: [PATCH 083/106] code fix --- zenovis/xinxinoptix/optixPathTracer.cpp | 74 +++++++++++++------------ zenovis/xinxinoptix/optixPathTracer.h | 22 +++++--- 2 files changed, 51 insertions(+), 45 deletions(-) diff --git a/zenovis/xinxinoptix/optixPathTracer.cpp b/zenovis/xinxinoptix/optixPathTracer.cpp index 21ac6659a4..b6b52d43fb 100644 --- a/zenovis/xinxinoptix/optixPathTracer.cpp +++ b/zenovis/xinxinoptix/optixPathTracer.cpp @@ -206,45 +206,47 @@ ushort2 halfNormal(float4 in) (unsigned short)(val.y*65536.0f), (unsigned short)(val.z*65536.0f)); } -#elifdef USE_SHORT -ushort3 toHalfColor(float4 in) -{ - return make_ushort3((unsigned short)(in.x*65536.0f), - (unsigned short)(in.y*65536.0f), - (unsigned short)(in.z*65536.0f)); -} -ushort3 toHalf(float4 in) -{ - return make_ushort3((unsigned short)(in.x*65536.0f), - (unsigned short)(in.y*65536.0f), - (unsigned short)(in.z*65536.0f)); -} +#else + #ifdef USE_SHORT + ushort3 toHalfColor(float4 in) + { + return make_ushort3((unsigned short)(in.x*65536.0f), + (unsigned short)(in.y*65536.0f), + (unsigned short)(in.z*65536.0f)); + } + ushort3 toHalf(float4 in) + { + return make_ushort3((unsigned short)(in.x*65536.0f), + (unsigned short)(in.y*65536.0f), + (unsigned short)(in.z*65536.0f)); + } -ushort3 halfNormal(float4 in) -{ - float3 val = make_float3((in.x + 1.0f)/2.0f, - (in.y + 1.0f)/2.0f, - (in.z + 1.0f)/2.0f); - val = normalize(val); + ushort3 halfNormal(float4 in) + { + float3 val = make_float3((in.x + 1.0f)/2.0f, + (in.y + 1.0f)/2.0f, + (in.z + 1.0f)/2.0f); + val = normalize(val); - return make_ushort3((unsigned short)(val.x*65536.0f), - (unsigned short)(val.y*65536.0f), - (unsigned short)(val.z*65536.0f)); -} -#else -float4 toHalfColor(float4 in) -{ - return in; -} -float4 toHalf(float4 in) -{ - return in; -} + return make_ushort3((unsigned short)(val.x*65536.0f), + (unsigned short)(val.y*65536.0f), + (unsigned short)(val.z*65536.0f)); + } + #else + float4 toHalfColor(float4 in) + { + return in; + } + float4 toHalf(float4 in) + { + return in; + } -float4 halfNormal(float4 in) -{ - return in; -} + float4 halfNormal(float4 in) + { + return in; + } + #endif #endif std::optional> output_buffer_o; diff --git a/zenovis/xinxinoptix/optixPathTracer.h b/zenovis/xinxinoptix/optixPathTracer.h index 1bcb138fcc..617e6db704 100644 --- a/zenovis/xinxinoptix/optixPathTracer.h +++ b/zenovis/xinxinoptix/optixPathTracer.h @@ -262,16 +262,20 @@ struct HitGroupData ushort2* nrm; ushort2* clr; ushort2* tan; -#elifdef USE_SHORT - ushort3* uv; - ushort3* nrm; - ushort3* clr; - ushort3* tan; #else - float4* uv; - float4* nrm; - float4* clr; - float4* tan; + + #ifdef USE_SHORT + ushort3* uv; + ushort3* nrm; + ushort3* clr; + ushort3* tan; + #else + float4* uv; + float4* nrm; + float4* clr; + float4* tan; + #endif + #endif unsigned short* lightMark; uint32_t* auxOffset; From a55d819f90a8cfdfb03e6a0b12880f9f8af54665 Mon Sep 17 00:00:00 2001 From: HansWanglin Date: Fri, 15 Dec 2023 23:59:24 +0800 Subject: [PATCH 084/106] Update README.md(change png to jpg) it is interesting that .png image could not be display completely in github README.md, while .jpg is fine. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b4c9720fa0..560af4c0ef 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Open-source node system framework, to change your algorithmic code into useful tools to create much more complicated simulations! - + ZENO is an open-source, Node based 3D system able to produce cinematic physics effects at High Efficiency, it was designed for large scale simulations and has been tested on complex setups. Aside of its simulation Tools, ZENO provides necessary visualization nodes for users to import and run simulations if you feel that the current software you are using is too slow. From 9a2222997576fc2f7f5b04b0d71e111c54d40e1e Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Sat, 16 Dec 2023 08:38:01 +0800 Subject: [PATCH 085/106] command params issue --- ui/zenoedit/launch/serialize.cpp | 10 ++++------ ui/zenoedit/panel/zenocommandparamspanel.cpp | 9 --------- 2 files changed, 4 insertions(+), 15 deletions(-) diff --git a/ui/zenoedit/launch/serialize.cpp b/ui/zenoedit/launch/serialize.cpp index 383a99b48e..c242edaae4 100644 --- a/ui/zenoedit/launch/serialize.cpp +++ b/ui/zenoedit/launch/serialize.cpp @@ -305,9 +305,8 @@ static void serializeGraph(IGraphsModel* pGraphsModel, const QModelIndex& subgId const QString& command = commandParams[objPath].name; if (configDoc.HasMember(command.toUtf8())) { - const auto& obj = configDoc[command.toStdString().c_str()]; - if (obj.IsObject() && obj.HasMember("value")) - defl = UiHelper::parseJsonByType(sockType, obj["value"], nullptr); + const auto& value = configDoc[command.toStdString().c_str()]; + defl = UiHelper::parseJsonByType(sockType, value, nullptr); } } else if (commandParams[objPath].bIsCommand) @@ -360,9 +359,8 @@ static void serializeGraph(IGraphsModel* pGraphsModel, const QModelIndex& subgId QString command = commandParams[objPath].name; if (!configPath.isEmpty() && commandParams.contains(objPath) && configDoc.HasMember(command.toUtf8())) { - const auto& obj = configDoc[command.toStdString().c_str()]; - if (obj.IsObject() && obj.HasMember("value")) - paramValue = UiHelper::parseJsonByType(param_info.typeDesc, obj["value"], nullptr); + const auto& value = configDoc[command.toStdString().c_str()]; + paramValue = UiHelper::parseJsonByType(param_info.typeDesc, value, nullptr); } else { diff --git a/ui/zenoedit/panel/zenocommandparamspanel.cpp b/ui/zenoedit/panel/zenocommandparamspanel.cpp index b498d43e9b..b7320ad384 100644 --- a/ui/zenoedit/panel/zenocommandparamspanel.cpp +++ b/ui/zenoedit/panel/zenocommandparamspanel.cpp @@ -140,17 +140,8 @@ void ZenoCommandParamsPanel::onExport() if (index.isValid()) { writer.Key(val.name.toUtf8()); - - writer.StartObject(); - - writer.Key("value"); const QString& sockType = index.data(ROLE_PARAM_TYPE).toString(); JsonHelper::AddVariant(val.value, sockType, writer); - - writer.Key("description"); - writer.String(val.description.toUtf8()); - - writer.EndObject(); } } From 0172ff4b1855e825b3d67a6b21350754f1e14ca3 Mon Sep 17 00:00:00 2001 From: YingQ Date: Mon, 18 Dec 2023 12:02:59 +0800 Subject: [PATCH 086/106] fix replace and remap node --- zeno/src/nodes/StringNodes.cpp | 5 +++++ zeno/src/nodes/prim/WBErode.cpp | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/zeno/src/nodes/StringNodes.cpp b/zeno/src/nodes/StringNodes.cpp index 0c2329ea38..2bb08140a7 100644 --- a/zeno/src/nodes/StringNodes.cpp +++ b/zeno/src/nodes/StringNodes.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -546,6 +547,10 @@ struct StringReplace : zeno::INode { std::string string = get_input2("string"); std::string oldstr = get_input2("old"); std::string newstr = get_input2("new"); + if (oldstr.empty()) { + zeno::log_error("[StringReplace] old string is empty."); + return; + } auto output = strreplace(string, oldstr, newstr); set_output2("string", output); } diff --git a/zeno/src/nodes/prim/WBErode.cpp b/zeno/src/nodes/prim/WBErode.cpp index 4f2fd5a33f..c0611b6b7f 100644 --- a/zeno/src/nodes/prim/WBErode.cpp +++ b/zeno/src/nodes/prim/WBErode.cpp @@ -2639,7 +2639,7 @@ ZENDEFNODE(HF_remap, { /* inputs: */ { "prim", {"string", "remap layer", "height"}, - {"bool", "Auto Compute input range", "1"}, + {"bool", "Auto Compute input range", "0"}, {"float", "input min", "0"}, {"float", "input max", "1"}, {"float", "output min", "0"}, From 54fcec56fbc33455bef99790ccbc5f76c314e791 Mon Sep 17 00:00:00 2001 From: Zhou Hang <765229842@qq.com> Date: Mon, 18 Dec 2023 12:03:20 +0800 Subject: [PATCH 087/106] Revert "New transform" --- ui/zenoedit/viewportinteraction/transform.cpp | 61 +++++++++++-------- ui/zenoedit/viewportinteraction/transform.h | 19 +++--- zeno/src/nodes/prim/TransformPrimitive.cpp | 9 +-- 3 files changed, 47 insertions(+), 42 deletions(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 9ef7058897..660c63df74 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -14,10 +14,12 @@ namespace zeno { FakeTransformer::FakeTransformer(ViewportWidget* viewport) : m_objects_center(0.0f) - , m_pivot(0.0f) , m_trans(0.0f) , m_scale(1.0f) , m_rotate({0, 0, 0, 1}) + , m_last_trans(0.0f) + , m_last_scale(1.0f) + , m_last_rotate({0, 0, 0, 1}) , m_status(false) , m_operation(NONE) , m_handler_scale(1.f) @@ -65,27 +67,16 @@ void FakeTransformer::addObject(const std::string& name) { user_data.setLiterial("_bboxMin", bmin); user_data.setLiterial("_bboxMax", bmax); } - if (!user_data.has("_pivot")) { + if (!user_data.has("_translate")) { zeno::vec3f translate = {0, 0, 0}; user_data.setLiterial("_translate", translate); zeno::vec4f rotate = {0, 0, 0, 1}; user_data.setLiterial("_rotate", rotate); zeno::vec3f scale = {1, 1, 1}; user_data.setLiterial("_scale", scale); - auto bboxCenter = (bmin + bmax) / 2; - user_data.set2("_pivot", bboxCenter); - if (object->has_attr("pos") && !object->has_attr("_origin_pos")) { - auto &pos = object->attr("pos"); - object->verts.add_attr("_origin_pos") = pos; - } - if (object->has_attr("nrm") && !object->has_attr("_origin_nrm")) { - auto &nrm = object->attr("nrm"); - object->verts.add_attr("_origin_nrm") = nrm; - } } auto m = zeno::vec_to_other(bmax); auto n = zeno::vec_to_other(bmin); - m_pivot = zeno::vec_to_other(user_data.get2("_pivot")); m_objects_center += (m + n) / 2.0f; m_objects[name] = object; m_objects_center /= m_objects.size(); @@ -324,7 +315,7 @@ void FakeTransformer::createNewTransformNode(NodeLocation& node_location, auto out_sock = node_sync.getPrimSockName(node_location); auto new_node_location = node_sync.generateNewNode(node_location, - "PrimitiveTransform", + "TransformPrimitive", out_sock, "prim"); @@ -449,7 +440,7 @@ void FakeTransformer::endTransform(bool moved) { auto& node_sync = NodeSyncMgr::GetInstance(); auto prim_node_location = node_sync.searchNodeOfPrim(obj_name); auto& prim_node = prim_node_location->node; - if (node_sync.checkNodeType(prim_node, "PrimitiveTransform") && + if (node_sync.checkNodeType(prim_node, "TransformPrimitive") && // prim comes from a exist TransformPrimitive node node_sync.checkNodeInputHasValue(prim_node, "translation") && node_sync.checkNodeInputHasValue(prim_node, "quatRotation") && @@ -459,7 +450,7 @@ void FakeTransformer::endTransform(bool moved) { else { // prim comes from another type node auto linked_transform_node = - node_sync.checkNodeLinkedSpecificNode(prim_node, "PrimitiveTransform"); + node_sync.checkNodeLinkedSpecificNode(prim_node, "TransformPrimitive"); if (linked_transform_node.has_value()) // prim links to a exist TransformPrimitive node syncToTransformNode(linked_transform_node.value(), obj_name); @@ -475,6 +466,10 @@ void FakeTransformer::endTransform(bool moved) { m_scale = {1, 1, 1}; m_rotate = {0, 0, 0, 1}; + m_last_trans = {0, 0, 0}; + m_last_scale = {1, 1, 1}; + m_last_rotate = {0, 0, 0, 1}; + m_operation_mode = zenovis::INTERACT_NONE; m_handler->setMode(zenovis::INTERACT_NONE); } @@ -637,6 +632,9 @@ void FakeTransformer::clear() { m_trans = {0, 0, 0}; m_scale = {1, 1, 1}; m_rotate = {0, 0, 0, 1}; + m_last_trans = {0, 0, 0}; + m_last_scale = {1, 1, 1}; + m_last_rotate = {0, 0, 0, 1}; m_operation = NONE; m_handler = nullptr; @@ -685,41 +683,51 @@ void FakeTransformer::doTransform() { auto translate = zeno::vec_to_other(user_data.getLiterial("_translate")); auto rotate = zeno::vec_to_other(user_data.getLiterial("_rotate")); auto scale = zeno::vec_to_other(user_data.getLiterial("_scale")); + + // inv last transform + auto pre_translate_matrix = glm::translate(translate + m_last_trans); auto pre_quaternion = glm::quat(rotate[3], rotate[0], rotate[1], rotate[2]); + auto last_quaternion = glm::quat(m_last_rotate[3], m_last_rotate[0], m_last_rotate[1], m_last_rotate[2]); auto pre_rotate_matrix = glm::toMat4(pre_quaternion); + auto pre_scale_matrix = glm::scale(scale * m_last_scale); + auto pre_transform_matrix = pre_translate_matrix * glm::toMat4(last_quaternion) * pre_rotate_matrix * pre_scale_matrix; + auto inv_pre_transform = glm::inverse(pre_transform_matrix); // do this transform auto translate_matrix = glm::translate(translate + m_trans); auto cur_quaternion = glm::quat(m_rotate[3], m_rotate[0], m_rotate[1], m_rotate[2]); auto rotate_matrix = glm::toMat4(cur_quaternion) * pre_rotate_matrix; auto scale_matrix = glm::scale(scale * m_scale); - auto transform_matrix = glm::translate(m_pivot) * translate_matrix * rotate_matrix * scale_matrix * glm::translate(-m_pivot); + auto transform_matrix = translate_matrix * + rotate_matrix * + scale_matrix * + inv_pre_transform; - if (obj->has_attr("_origin_pos")) { + if (obj->has_attr("pos")) { // transform pos auto &pos = obj->attr("pos"); - auto &opos = obj->attr("_origin_pos"); #pragma omp parallel for // for (auto &po : pos) { for (size_t i = 0; i < pos.size(); ++i) { - auto p = zeno::vec_to_other(opos[i]); + auto& po = pos[i]; + auto p = zeno::vec_to_other(po); auto t = transform_matrix * glm::vec4(p, 1.0f); auto pt = glm::vec3(t) / t.w; - pos[i] = zeno::other_to_vec<3>(pt); + po = zeno::other_to_vec<3>(pt); } } - if (obj->has_attr("_origin_nrm")) { + if (obj->has_attr("nrm")) { // transform nrm auto &nrm = obj->attr("nrm"); - auto &onrm = obj->attr("_origin_nrm"); #pragma omp parallel for // for (auto &vec : nrm) { for (size_t i = 0; i < nrm.size(); ++i) { - auto n = zeno::vec_to_other(nrm[i]); + auto& vec = nrm[i]; + auto n = zeno::vec_to_other(vec); glm::mat3 norm_matrix(transform_matrix); norm_matrix = glm::transpose(glm::inverse(norm_matrix)); auto t = glm::normalize(norm_matrix * n); - onrm[i] = zeno::other_to_vec<3>(t); + vec = zeno::other_to_vec<3>(t); } } vec3f bmin, bmax; @@ -730,6 +738,9 @@ void FakeTransformer::doTransform() { } new_objects_center += (zeno::vec_to_other(bmin) + zeno::vec_to_other(bmax)) / 2.0f; } + m_last_trans = m_trans; + m_last_rotate = m_rotate; + m_last_scale = m_scale; new_objects_center /= m_objects.size(); m_objects_center = new_objects_center; diff --git a/ui/zenoedit/viewportinteraction/transform.h b/ui/zenoedit/viewportinteraction/transform.h index a8d59a5317..d33ab546e8 100644 --- a/ui/zenoedit/viewportinteraction/transform.h +++ b/ui/zenoedit/viewportinteraction/transform.h @@ -24,7 +24,7 @@ enum { }; class FakeTransformer { -public: +public: FakeTransformer(ViewportWidget* viewport); void addObject(const std::string& name); void addObject(const std::unordered_set& names); @@ -49,15 +49,12 @@ class FakeTransformer { glm::vec3 getCenter() const; void clear(); -private: - zenovis::Scene* scene() const; +private: + zenovis::Scene* scene() const; zenovis::Session* session() const; - // 计算translate并调用doTransform void translate(glm::vec3 start, glm::vec3 end, glm::vec3 axis); - // 计算scale并调用doTransform void scale(float scale_size, vec3i axis); - // 计算rotate并调用doTransform void rotate(glm::vec3 start_vec, glm::vec3 end_vec, glm::vec3 axis); void createNewTransformNode(NodeLocation& node_location, @@ -65,7 +62,6 @@ class FakeTransformer { void syncToTransformNode(NodeLocation& node_location, const std::string& obj_name); - // 把FakeTransform上的SRT应用到primitive上 void doTransform(); static glm::vec3 QVec3ToGLMVec3(QVector3D QVec3) { @@ -106,11 +102,14 @@ class FakeTransformer { glm::vec3 m_objects_center; - glm::vec3 m_pivot; glm::vec3 m_trans; glm::vec4 m_rotate; glm::vec3 m_scale; + glm::vec3 m_last_trans; + glm::vec4 m_last_rotate; + glm::vec3 m_last_scale; + glm::vec3 m_trans_start; glm::vec3 m_rotate_start; // glm::vec3 m_scale_start; @@ -120,8 +119,8 @@ class FakeTransformer { int m_operation_mode; int m_coord_sys; float m_handler_scale; - std::shared_ptr m_handler; - ViewportWidget* m_viewport; + std::shared_ptr m_handler; + ViewportWidget* m_viewport; }; } diff --git a/zeno/src/nodes/prim/TransformPrimitive.cpp b/zeno/src/nodes/prim/TransformPrimitive.cpp index 9f0d3c3038..d3ae3d3848 100644 --- a/zeno/src/nodes/prim/TransformPrimitive.cpp +++ b/zeno/src/nodes/prim/TransformPrimitive.cpp @@ -190,7 +190,7 @@ ZENDEFNODE(TransformPrimitive, { {"enum " + EulerAngle::RotationOrderListString(), "EulerRotationOrder", "ZYX"}, {"enum " + EulerAngle::MeasureListString(), "EulerAngleMeasure", EulerAngle::MeasureDefaultString()} }, - {"deprecated"}, + {"primitive"}, }); // euler rot order: roll-pitch-yaw @@ -272,7 +272,6 @@ struct PrimitiveTransform : zeno::INode { auto prim = get_input("prim"); std::string pivotType = get_input2("pivot"); - zeno::vec3f _pivot = {}; if (pivotType == "bboxCenter") { zeno::vec3f _min; zeno::vec3f _max; @@ -281,14 +280,12 @@ struct PrimitiveTransform : zeno::INode { auto pivot_to_local = glm::translate(glm::vec3(-p[0], -p[1], -p[2])); auto pivot_to_world = glm::translate(glm::vec3(p[0], p[1], p[2])); matrix = pivot_to_world * matrix * pivot_to_local; - _pivot = p; } auto outprim = std::make_unique(*prim); if (prim->has_attr("pos")) { auto &pos = outprim->attr("pos"); - outprim->verts.add_attr("_origin_pos") = pos; #pragma omp parallel for for (int i = 0; i < pos.size(); i++) { auto p = zeno::vec_to_other(pos[i]); @@ -299,7 +296,6 @@ struct PrimitiveTransform : zeno::INode { if (prim->has_attr("nrm")) { auto &nrm = outprim->attr("nrm"); - outprim->verts.add_attr("_origin_nrm") = nrm; #pragma omp parallel for for (int i = 0; i < nrm.size(); i++) { auto n = zeno::vec_to_other(nrm[i]); @@ -313,7 +309,6 @@ struct PrimitiveTransform : zeno::INode { vec4f rotate = {myQuat.x, myQuat.y, myQuat.z, myQuat.w}; user_data.setLiterial("_rotate", rotate); user_data.setLiterial("_scale", scaling); - user_data.set2("_pivot", _pivot); //auto oMat = std::make_shared(); //oMat->m = matrix; set_output("outPrim", std::move(outprim)); @@ -323,7 +318,7 @@ struct PrimitiveTransform : zeno::INode { ZENDEFNODE(PrimitiveTransform, { { {"PrimitiveObject", "prim"}, - {"enum world bboxCenter", "pivot", "bboxCenter"}, + {"enum world bboxCenter", "pivot", "world"}, {"vec3f", "translation", "0,0,0"}, {"vec3f", "eulerXYZ", "0,0,0"}, {"vec4f", "quatRotation", "0,0,0,1"}, From 4e31e9d210ed6122178dd21c3f70e3df93390581 Mon Sep 17 00:00:00 2001 From: Zhou Hang <765229842@qq.com> Date: Mon, 18 Dec 2023 12:38:58 +0800 Subject: [PATCH 088/106] Revert "Revert "New transform"" --- ui/zenoedit/viewportinteraction/transform.cpp | 61 ++++++++----------- ui/zenoedit/viewportinteraction/transform.h | 19 +++--- zeno/src/nodes/prim/TransformPrimitive.cpp | 9 ++- 3 files changed, 42 insertions(+), 47 deletions(-) diff --git a/ui/zenoedit/viewportinteraction/transform.cpp b/ui/zenoedit/viewportinteraction/transform.cpp index 660c63df74..9ef7058897 100644 --- a/ui/zenoedit/viewportinteraction/transform.cpp +++ b/ui/zenoedit/viewportinteraction/transform.cpp @@ -14,12 +14,10 @@ namespace zeno { FakeTransformer::FakeTransformer(ViewportWidget* viewport) : m_objects_center(0.0f) + , m_pivot(0.0f) , m_trans(0.0f) , m_scale(1.0f) , m_rotate({0, 0, 0, 1}) - , m_last_trans(0.0f) - , m_last_scale(1.0f) - , m_last_rotate({0, 0, 0, 1}) , m_status(false) , m_operation(NONE) , m_handler_scale(1.f) @@ -67,16 +65,27 @@ void FakeTransformer::addObject(const std::string& name) { user_data.setLiterial("_bboxMin", bmin); user_data.setLiterial("_bboxMax", bmax); } - if (!user_data.has("_translate")) { + if (!user_data.has("_pivot")) { zeno::vec3f translate = {0, 0, 0}; user_data.setLiterial("_translate", translate); zeno::vec4f rotate = {0, 0, 0, 1}; user_data.setLiterial("_rotate", rotate); zeno::vec3f scale = {1, 1, 1}; user_data.setLiterial("_scale", scale); + auto bboxCenter = (bmin + bmax) / 2; + user_data.set2("_pivot", bboxCenter); + if (object->has_attr("pos") && !object->has_attr("_origin_pos")) { + auto &pos = object->attr("pos"); + object->verts.add_attr("_origin_pos") = pos; + } + if (object->has_attr("nrm") && !object->has_attr("_origin_nrm")) { + auto &nrm = object->attr("nrm"); + object->verts.add_attr("_origin_nrm") = nrm; + } } auto m = zeno::vec_to_other(bmax); auto n = zeno::vec_to_other(bmin); + m_pivot = zeno::vec_to_other(user_data.get2("_pivot")); m_objects_center += (m + n) / 2.0f; m_objects[name] = object; m_objects_center /= m_objects.size(); @@ -315,7 +324,7 @@ void FakeTransformer::createNewTransformNode(NodeLocation& node_location, auto out_sock = node_sync.getPrimSockName(node_location); auto new_node_location = node_sync.generateNewNode(node_location, - "TransformPrimitive", + "PrimitiveTransform", out_sock, "prim"); @@ -440,7 +449,7 @@ void FakeTransformer::endTransform(bool moved) { auto& node_sync = NodeSyncMgr::GetInstance(); auto prim_node_location = node_sync.searchNodeOfPrim(obj_name); auto& prim_node = prim_node_location->node; - if (node_sync.checkNodeType(prim_node, "TransformPrimitive") && + if (node_sync.checkNodeType(prim_node, "PrimitiveTransform") && // prim comes from a exist TransformPrimitive node node_sync.checkNodeInputHasValue(prim_node, "translation") && node_sync.checkNodeInputHasValue(prim_node, "quatRotation") && @@ -450,7 +459,7 @@ void FakeTransformer::endTransform(bool moved) { else { // prim comes from another type node auto linked_transform_node = - node_sync.checkNodeLinkedSpecificNode(prim_node, "TransformPrimitive"); + node_sync.checkNodeLinkedSpecificNode(prim_node, "PrimitiveTransform"); if (linked_transform_node.has_value()) // prim links to a exist TransformPrimitive node syncToTransformNode(linked_transform_node.value(), obj_name); @@ -466,10 +475,6 @@ void FakeTransformer::endTransform(bool moved) { m_scale = {1, 1, 1}; m_rotate = {0, 0, 0, 1}; - m_last_trans = {0, 0, 0}; - m_last_scale = {1, 1, 1}; - m_last_rotate = {0, 0, 0, 1}; - m_operation_mode = zenovis::INTERACT_NONE; m_handler->setMode(zenovis::INTERACT_NONE); } @@ -632,9 +637,6 @@ void FakeTransformer::clear() { m_trans = {0, 0, 0}; m_scale = {1, 1, 1}; m_rotate = {0, 0, 0, 1}; - m_last_trans = {0, 0, 0}; - m_last_scale = {1, 1, 1}; - m_last_rotate = {0, 0, 0, 1}; m_operation = NONE; m_handler = nullptr; @@ -683,51 +685,41 @@ void FakeTransformer::doTransform() { auto translate = zeno::vec_to_other(user_data.getLiterial("_translate")); auto rotate = zeno::vec_to_other(user_data.getLiterial("_rotate")); auto scale = zeno::vec_to_other(user_data.getLiterial("_scale")); - - // inv last transform - auto pre_translate_matrix = glm::translate(translate + m_last_trans); auto pre_quaternion = glm::quat(rotate[3], rotate[0], rotate[1], rotate[2]); - auto last_quaternion = glm::quat(m_last_rotate[3], m_last_rotate[0], m_last_rotate[1], m_last_rotate[2]); auto pre_rotate_matrix = glm::toMat4(pre_quaternion); - auto pre_scale_matrix = glm::scale(scale * m_last_scale); - auto pre_transform_matrix = pre_translate_matrix * glm::toMat4(last_quaternion) * pre_rotate_matrix * pre_scale_matrix; - auto inv_pre_transform = glm::inverse(pre_transform_matrix); // do this transform auto translate_matrix = glm::translate(translate + m_trans); auto cur_quaternion = glm::quat(m_rotate[3], m_rotate[0], m_rotate[1], m_rotate[2]); auto rotate_matrix = glm::toMat4(cur_quaternion) * pre_rotate_matrix; auto scale_matrix = glm::scale(scale * m_scale); - auto transform_matrix = translate_matrix * - rotate_matrix * - scale_matrix * - inv_pre_transform; + auto transform_matrix = glm::translate(m_pivot) * translate_matrix * rotate_matrix * scale_matrix * glm::translate(-m_pivot); - if (obj->has_attr("pos")) { + if (obj->has_attr("_origin_pos")) { // transform pos auto &pos = obj->attr("pos"); + auto &opos = obj->attr("_origin_pos"); #pragma omp parallel for // for (auto &po : pos) { for (size_t i = 0; i < pos.size(); ++i) { - auto& po = pos[i]; - auto p = zeno::vec_to_other(po); + auto p = zeno::vec_to_other(opos[i]); auto t = transform_matrix * glm::vec4(p, 1.0f); auto pt = glm::vec3(t) / t.w; - po = zeno::other_to_vec<3>(pt); + pos[i] = zeno::other_to_vec<3>(pt); } } - if (obj->has_attr("nrm")) { + if (obj->has_attr("_origin_nrm")) { // transform nrm auto &nrm = obj->attr("nrm"); + auto &onrm = obj->attr("_origin_nrm"); #pragma omp parallel for // for (auto &vec : nrm) { for (size_t i = 0; i < nrm.size(); ++i) { - auto& vec = nrm[i]; - auto n = zeno::vec_to_other(vec); + auto n = zeno::vec_to_other(nrm[i]); glm::mat3 norm_matrix(transform_matrix); norm_matrix = glm::transpose(glm::inverse(norm_matrix)); auto t = glm::normalize(norm_matrix * n); - vec = zeno::other_to_vec<3>(t); + onrm[i] = zeno::other_to_vec<3>(t); } } vec3f bmin, bmax; @@ -738,9 +730,6 @@ void FakeTransformer::doTransform() { } new_objects_center += (zeno::vec_to_other(bmin) + zeno::vec_to_other(bmax)) / 2.0f; } - m_last_trans = m_trans; - m_last_rotate = m_rotate; - m_last_scale = m_scale; new_objects_center /= m_objects.size(); m_objects_center = new_objects_center; diff --git a/ui/zenoedit/viewportinteraction/transform.h b/ui/zenoedit/viewportinteraction/transform.h index d33ab546e8..a8d59a5317 100644 --- a/ui/zenoedit/viewportinteraction/transform.h +++ b/ui/zenoedit/viewportinteraction/transform.h @@ -24,7 +24,7 @@ enum { }; class FakeTransformer { -public: +public: FakeTransformer(ViewportWidget* viewport); void addObject(const std::string& name); void addObject(const std::unordered_set& names); @@ -49,12 +49,15 @@ class FakeTransformer { glm::vec3 getCenter() const; void clear(); -private: - zenovis::Scene* scene() const; +private: + zenovis::Scene* scene() const; zenovis::Session* session() const; + // 计算translate并调用doTransform void translate(glm::vec3 start, glm::vec3 end, glm::vec3 axis); + // 计算scale并调用doTransform void scale(float scale_size, vec3i axis); + // 计算rotate并调用doTransform void rotate(glm::vec3 start_vec, glm::vec3 end_vec, glm::vec3 axis); void createNewTransformNode(NodeLocation& node_location, @@ -62,6 +65,7 @@ class FakeTransformer { void syncToTransformNode(NodeLocation& node_location, const std::string& obj_name); + // 把FakeTransform上的SRT应用到primitive上 void doTransform(); static glm::vec3 QVec3ToGLMVec3(QVector3D QVec3) { @@ -102,14 +106,11 @@ class FakeTransformer { glm::vec3 m_objects_center; + glm::vec3 m_pivot; glm::vec3 m_trans; glm::vec4 m_rotate; glm::vec3 m_scale; - glm::vec3 m_last_trans; - glm::vec4 m_last_rotate; - glm::vec3 m_last_scale; - glm::vec3 m_trans_start; glm::vec3 m_rotate_start; // glm::vec3 m_scale_start; @@ -119,8 +120,8 @@ class FakeTransformer { int m_operation_mode; int m_coord_sys; float m_handler_scale; - std::shared_ptr m_handler; - ViewportWidget* m_viewport; + std::shared_ptr m_handler; + ViewportWidget* m_viewport; }; } diff --git a/zeno/src/nodes/prim/TransformPrimitive.cpp b/zeno/src/nodes/prim/TransformPrimitive.cpp index d3ae3d3848..9f0d3c3038 100644 --- a/zeno/src/nodes/prim/TransformPrimitive.cpp +++ b/zeno/src/nodes/prim/TransformPrimitive.cpp @@ -190,7 +190,7 @@ ZENDEFNODE(TransformPrimitive, { {"enum " + EulerAngle::RotationOrderListString(), "EulerRotationOrder", "ZYX"}, {"enum " + EulerAngle::MeasureListString(), "EulerAngleMeasure", EulerAngle::MeasureDefaultString()} }, - {"primitive"}, + {"deprecated"}, }); // euler rot order: roll-pitch-yaw @@ -272,6 +272,7 @@ struct PrimitiveTransform : zeno::INode { auto prim = get_input("prim"); std::string pivotType = get_input2("pivot"); + zeno::vec3f _pivot = {}; if (pivotType == "bboxCenter") { zeno::vec3f _min; zeno::vec3f _max; @@ -280,12 +281,14 @@ struct PrimitiveTransform : zeno::INode { auto pivot_to_local = glm::translate(glm::vec3(-p[0], -p[1], -p[2])); auto pivot_to_world = glm::translate(glm::vec3(p[0], p[1], p[2])); matrix = pivot_to_world * matrix * pivot_to_local; + _pivot = p; } auto outprim = std::make_unique(*prim); if (prim->has_attr("pos")) { auto &pos = outprim->attr("pos"); + outprim->verts.add_attr("_origin_pos") = pos; #pragma omp parallel for for (int i = 0; i < pos.size(); i++) { auto p = zeno::vec_to_other(pos[i]); @@ -296,6 +299,7 @@ struct PrimitiveTransform : zeno::INode { if (prim->has_attr("nrm")) { auto &nrm = outprim->attr("nrm"); + outprim->verts.add_attr("_origin_nrm") = nrm; #pragma omp parallel for for (int i = 0; i < nrm.size(); i++) { auto n = zeno::vec_to_other(nrm[i]); @@ -309,6 +313,7 @@ struct PrimitiveTransform : zeno::INode { vec4f rotate = {myQuat.x, myQuat.y, myQuat.z, myQuat.w}; user_data.setLiterial("_rotate", rotate); user_data.setLiterial("_scale", scaling); + user_data.set2("_pivot", _pivot); //auto oMat = std::make_shared(); //oMat->m = matrix; set_output("outPrim", std::move(outprim)); @@ -318,7 +323,7 @@ struct PrimitiveTransform : zeno::INode { ZENDEFNODE(PrimitiveTransform, { { {"PrimitiveObject", "prim"}, - {"enum world bboxCenter", "pivot", "world"}, + {"enum world bboxCenter", "pivot", "bboxCenter"}, {"vec3f", "translation", "0,0,0"}, {"vec3f", "eulerXYZ", "0,0,0"}, {"vec4f", "quatRotation", "0,0,0,1"}, From 86e95e56447ba51c10759335c99529cd1aef936d Mon Sep 17 00:00:00 2001 From: seeeagull Date: Mon, 18 Dec 2023 13:12:13 +0800 Subject: [PATCH 089/106] add prim input interface --- projects/Geometry/fTetWild | 2 +- projects/Geometry/tetmesh.cpp | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/projects/Geometry/fTetWild b/projects/Geometry/fTetWild index b20ca8700d..de298344f9 160000 --- a/projects/Geometry/fTetWild +++ b/projects/Geometry/fTetWild @@ -1 +1 @@ -Subproject commit b20ca8700dbe80ea4929b5cbda44367cb258bbf7 +Subproject commit de298344f9a2181dcc34dfbad3c90b939819a651 diff --git a/projects/Geometry/tetmesh.cpp b/projects/Geometry/tetmesh.cpp index 7737f13c36..2a803adcd2 100644 --- a/projects/Geometry/tetmesh.cpp +++ b/projects/Geometry/tetmesh.cpp @@ -14,6 +14,7 @@ namespace zeno { struct FTetWild : INode { virtual void apply() override { + auto prim = get_input("prim"); auto input_dir = get_input2("input_dir"); auto output_dir = get_input2("output_dir"); auto tag = get_input2("tag"); @@ -197,13 +198,23 @@ struct FTetWild : INode { strcpy(argv[argc+1], "3\0"); argc += 2; - runFTetWild(argc, argv); + std::vector> faces(prim->tris->size(), std::vector{}); + std::vector> verts(prim->verts->size(), std::vector{}); + for (int i = 0; i < prim->tris->size(); ++i) + for (int j = 0; j < 3; ++j) + faces[i].push_back(prim->tris[i][j]); + for (int i = 0; i < prim->verts->size(); ++i) + for (int j = 0; j < 3; ++j) + verts[i].push_back(prim->verts[i][j]); + + runFTetWild(faces, verts, argc, argv); } }; ZENO_DEFNODE(FTetWild) ({ - {{"readpath", "input_dir"}, + {{"prim"}, + {"readpath", "input_dir"}, {"string", "output_dir"}, {"readpath", "tag", " "}, {"enum none union intersection difference", "operation", "none"}, From 109cc76a2ba8f70412e66aa820551a53f33a2334 Mon Sep 17 00:00:00 2001 From: seeeagull Date: Mon, 18 Dec 2023 13:12:13 +0800 Subject: [PATCH 090/106] add prim input interface --- projects/Geometry/fTetWild | 2 +- projects/Geometry/tetmesh.cpp | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/projects/Geometry/fTetWild b/projects/Geometry/fTetWild index b20ca8700d..de298344f9 160000 --- a/projects/Geometry/fTetWild +++ b/projects/Geometry/fTetWild @@ -1 +1 @@ -Subproject commit b20ca8700dbe80ea4929b5cbda44367cb258bbf7 +Subproject commit de298344f9a2181dcc34dfbad3c90b939819a651 diff --git a/projects/Geometry/tetmesh.cpp b/projects/Geometry/tetmesh.cpp index 7737f13c36..2a803adcd2 100644 --- a/projects/Geometry/tetmesh.cpp +++ b/projects/Geometry/tetmesh.cpp @@ -14,6 +14,7 @@ namespace zeno { struct FTetWild : INode { virtual void apply() override { + auto prim = get_input("prim"); auto input_dir = get_input2("input_dir"); auto output_dir = get_input2("output_dir"); auto tag = get_input2("tag"); @@ -197,13 +198,23 @@ struct FTetWild : INode { strcpy(argv[argc+1], "3\0"); argc += 2; - runFTetWild(argc, argv); + std::vector> faces(prim->tris->size(), std::vector{}); + std::vector> verts(prim->verts->size(), std::vector{}); + for (int i = 0; i < prim->tris->size(); ++i) + for (int j = 0; j < 3; ++j) + faces[i].push_back(prim->tris[i][j]); + for (int i = 0; i < prim->verts->size(); ++i) + for (int j = 0; j < 3; ++j) + verts[i].push_back(prim->verts[i][j]); + + runFTetWild(faces, verts, argc, argv); } }; ZENO_DEFNODE(FTetWild) ({ - {{"readpath", "input_dir"}, + {{"prim"}, + {"readpath", "input_dir"}, {"string", "output_dir"}, {"readpath", "tag", " "}, {"enum none union intersection difference", "operation", "none"}, From b9559839211b240400c34fffed3555268b23309f Mon Sep 17 00:00:00 2001 From: zhuohy <1445643474@qq.com> Date: Mon, 18 Dec 2023 14:05:17 +0800 Subject: [PATCH 091/106] create material subgraph api --- ui/zenomodel/include/api.h | 1 + ui/zenomodel/src/api.cpp | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/ui/zenomodel/include/api.h b/ui/zenomodel/include/api.h index e294ab2561..61e19fd774 100644 --- a/ui/zenomodel/include/api.h +++ b/ui/zenomodel/include/api.h @@ -8,6 +8,7 @@ ZENO_ERROR Zeno_NewFile(); ZENO_ERROR Zeno_OpenFile(const std::string& fn); ZENO_ERROR Zeno_SaveAs(const std::string& fn); +ZENO_HANDLE Zeno_CreateGraph(const std::string& name, int type); ZENO_HANDLE Zeno_CreateGraph(const std::string& name); ZENO_ERROR Zeno_DeleteGraph(ZENO_HANDLE hSubgraph); ZENO_HANDLE Zeno_GetGraph(const std::string& name); diff --git a/ui/zenomodel/src/api.cpp b/ui/zenomodel/src/api.cpp index 875aed3c74..c9ad1fcf01 100644 --- a/ui/zenomodel/src/api.cpp +++ b/ui/zenomodel/src/api.cpp @@ -27,6 +27,18 @@ ZENO_HANDLE Zeno_CreateGraph(const std::string& name) return subgIdx.internalId(); } +ZENO_HANDLE Zeno_CreateGraph(const std::string& name, int type) +{ + IGraphsModel* pModel = GraphsManagment::instance().currentModel(); + if (!pModel) + return Err_ModelNull; + + const QString& qsName = QString::fromStdString(name); + pModel->newSubgraph(QString::fromStdString(name), (SUBGRAPH_TYPE)type); + QModelIndex subgIdx = pModel->index(qsName); + return subgIdx.internalId(); +} + ZENO_ERROR Zeno_DeleteGraph(ZENO_HANDLE hSubgraph) { IGraphsModel* pModel = GraphsManagment::instance().currentModel(); From 2df27a2ae0c324461036191ccbe738b4201c5e2d Mon Sep 17 00:00:00 2001 From: seeeagull Date: Mon, 18 Dec 2023 15:38:09 +0800 Subject: [PATCH 092/106] add prim output --- projects/Geometry/fTetWild | 2 +- projects/Geometry/tetmesh.cpp | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/projects/Geometry/fTetWild b/projects/Geometry/fTetWild index de298344f9..5d72cc0866 160000 --- a/projects/Geometry/fTetWild +++ b/projects/Geometry/fTetWild @@ -1 +1 @@ -Subproject commit de298344f9a2181dcc34dfbad3c90b939819a651 +Subproject commit 5d72cc0866b70840a361bb66c1cbf0c09c2d0718 diff --git a/projects/Geometry/tetmesh.cpp b/projects/Geometry/tetmesh.cpp index 2a803adcd2..b4d7e41698 100644 --- a/projects/Geometry/tetmesh.cpp +++ b/projects/Geometry/tetmesh.cpp @@ -16,6 +16,7 @@ struct FTetWild : INode { virtual void apply() override { auto prim = get_input("prim"); auto input_dir = get_input2("input_dir"); + input_dir.erase(input_dir.find_last_not_of(" ")+1); auto output_dir = get_input2("output_dir"); auto tag = get_input2("tag"); tag.erase(tag.find_last_not_of(" ")+1); @@ -208,13 +209,25 @@ struct FTetWild : INode { verts[i].push_back(prim->verts[i][j]); runFTetWild(faces, verts, argc, argv); + + prim->quads.clear(); + prim->quads.resize(faces.size()); + prim->verts.clear(); + prim->verts.resize(verts.size()); + for (int i = 0; i < faces.size(); ++i) + for (int j = 0; j < 4; ++j) + prim->quads[i][j] = faces[i][j]; + for (int i = 0; i < verts.size(); ++i) + for (int j = 0; j < 3; ++j) + prim->verts[i][j] = verts[i][j]; + set_output("prim", std::move(prim)); } }; ZENO_DEFNODE(FTetWild) ({ {{"prim"}, - {"readpath", "input_dir"}, + {"readpath", "input_dir", " "}, {"string", "output_dir"}, {"readpath", "tag", " "}, {"enum none union intersection difference", "operation", "none"}, @@ -234,7 +247,7 @@ ZENO_DEFNODE(FTetWild) {"bool", "use_general_wn", "0"}, {"bool", "use_input_for_wn", "0"}, {"readpath", "bg_mesh", " "}}, - {}, + {("prim")}, {}, {"primitive"}, }); From 0888533d02763f042fc0d4eb199f6f788b2ecac3 Mon Sep 17 00:00:00 2001 From: seeeagull Date: Mon, 18 Dec 2023 16:54:22 +0800 Subject: [PATCH 093/106] add README for QuadMesh and fTetWild, disable useless param for quadmesh --- projects/Geometry/README.md | 41 ++++++++++++++++++++++++++++++++++ projects/Geometry/quadmesh.cpp | 24 ++++++++++---------- 2 files changed, 53 insertions(+), 12 deletions(-) create mode 100644 projects/Geometry/README.md diff --git a/projects/Geometry/README.md b/projects/Geometry/README.md new file mode 100644 index 0000000000..666460bcfb --- /dev/null +++ b/projects/Geometry/README.md @@ -0,0 +1,41 @@ +## QuadMesh节点参数说明 +| 参数 | 类型 | 说明 | +| --- | ---- | --- | +| prim | PrimitiveObject | 输入三角形网格。 | +| deterministic | bool | 使用较慢的确定性算法。 | +| crease | float | 判断为折痕的二面角阈值。 | +| smooth_iter | int | 平滑和光线追踪重投影的次数(默认2)。 | +| quad_dominant | bool | 生成以四边形为主的三角形-四边形混合网格。 | +| intrinsic | bool | 使用intrinsic方法(默认extrinsic方法)。 | +| boundary | bool | 对于非闭合的表面,保持边缘轮廓。(有保留边的输入时自动开启) | +| scale | float | 期望的世界坐标下边长。(与vert_num, face_num至多同时指定一项) | +| vert_num | int | 期望点数。 | +| face_num | int | 期望面数。 | +| line_pick_tag | string | 保留的边的属性名称,属性应为int类型,该属性值为1的边被保留。只能保留边方向,不能严格固定顶点位置。 | +| marked_lines | list of vec2i | 保留的边的列表。只能保留边方向,不能严格固定顶点位置。 | + + +## fTetWild节点参数说明 +| 参数 | 类型 | 说明 | +| --- | ---- | --- | +| prim | PrimitiveObject | 输入三角形网格。 | +| input_dir | readpath | 输入三角形网格文件路径。如果有prim输入则忽略此项。 | +| output_dir | string | 输出四面体网格文件路径。若为空,当以prim输入时则不输出任何文件,以文件读入时则输出到“<原路经>/<原文件名>_.msh” | +| tag | readpath | 输入用于布尔运算的面片标记的文件路径。 | +| operation | enum | 布尔运算种类 | +| edge_length | float | 期望相对边长。默认0.05。 | +| epsilon | float | 期望相对偏差。默认1e-3。 | +| stop_energy | float | 停止优化的能量阈值。默认10。 | +| skip_simplify | bool | 跳过预处理。 | +| no_binary | bool | 以ascii格式输出。(仅在有输出文件时生效) | +| no_color | bool | 不输出颜色。(仅在有输出文件时生效) | +| smooth_open_boundary | bool | 对于非闭合表面,光滑其边缘。 | +| export_raw | bool | 输出原始结果。 | +| manifold_surface | bool | 处理输出为流形。 | +| coarsen | bool | 尽可能使输出稀疏。 | +| csg | readpath | 包含csg树的json文件路径。 | +| disable_filtering | bool | 不过滤掉外部的元素。 | +| use_floodfill | bool | 使用泛洪法提取内部体积。 | +| use_general_wn | bool | 使用通常的绕数。 | +| use_input_for_wn | bool | 使用输入表面得到绕数。 | +| bg_mesh | readpath | 用于得到长度场的背景网格(.msh格式)文件路径 | \ No newline at end of file diff --git a/projects/Geometry/quadmesh.cpp b/projects/Geometry/quadmesh.cpp index 4de1aff6fa..e819fc2cea 100644 --- a/projects/Geometry/quadmesh.cpp +++ b/projects/Geometry/quadmesh.cpp @@ -23,7 +23,7 @@ struct QuadMesh : INode { float scale = get_input2("scale"); int vert_num = get_input2("vert_num"); int face_num = get_input2("face_num"); - int knn = get_input2("knn"); + // int knn = get_input2("knn"); auto line_pick_tag = get_input("line_pick_tag")->get(); if (prim->verts.size() < 4) { @@ -142,16 +142,16 @@ struct QuadMesh : INode { argv[argc+1][face_num_str.size()] = '\0'; argc += 2; } - if (knn > 0) { - argv[argc] = (char*)malloc(sizeof("--knn\0")); - strcpy(argv[argc], "--knn\0"); - std::string knn_str = to_string(knn); - argv[argc+1] = (char*)malloc((knn_str.size()+1)*sizeof(char)); - for (int i = 0; i < knn_str.size(); ++i) - argv[argc+1][i] = knn_str[i]; - argv[argc+1][knn_str.size()] = '\0'; - argc += 2; - } + // if (knn > 0) { + // argv[argc] = (char*)malloc(sizeof("--knn\0")); + // strcpy(argv[argc], "--knn\0"); + // std::string knn_str = to_string(knn); + // argv[argc+1] = (char*)malloc((knn_str.size()+1)*sizeof(char)); + // for (int i = 0; i < knn_str.size(); ++i) + // argv[argc+1][i] = knn_str[i]; + // argv[argc+1][knn_str.size()] = '\0'; + // argc += 2; + // } std::vector> faces(prim->tris->size(), std::vector{}); std::vector> verts(prim->verts->size(), std::vector{}); @@ -208,7 +208,7 @@ ZENO_DEFNODE(QuadMesh) {"float", "scale", "0"}, {"int", "vert_num", "0"}, {"int", "face_num", "0"}, - {"int", "knn", "0"}, + // {"int", "knn", "0"}, {"string", "line_pick_tag", "line_selected"}, {"marked_lines"}}, {{"prim"}}, From a777735186724b43adf52d8bd2bd0009e3fbafe0 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Mon, 18 Dec 2023 21:16:27 +0800 Subject: [PATCH 094/106] fix-transform-gizmo-bug --- ui/zenoedit/viewport/cameracontrol.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/zenoedit/viewport/cameracontrol.cpp b/ui/zenoedit/viewport/cameracontrol.cpp index d68f931eb8..0e95bba443 100644 --- a/ui/zenoedit/viewport/cameracontrol.cpp +++ b/ui/zenoedit/viewport/cameracontrol.cpp @@ -135,7 +135,7 @@ void CameraControl::fakeMousePressEvent(QMouseEvent *event) auto dir = screenToWorldRay(event->x() / res().x(), event->y() / res().y()); if (m_transformer) { - if (!scene->selected.empty() && m_transformer->isTransformMode() && + if (event->buttons() & Qt::LeftButton && !scene->selected.empty() && m_transformer->isTransformMode() && m_transformer->clickedAnyHandler(realPos(), dir, front)) { bTransform = true; From 152b38fdec084c5d0d49e984ed7628c5ebfb6a04 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Tue, 19 Dec 2023 02:28:33 +0800 Subject: [PATCH 095/106] data compression, normal conversion bug fix --- zeno/src/nodes/mtl/ShaderAttrs.cpp | 2 +- zenovis/xinxinoptix/DeflMatShader.cu | 17 +++++++++---- zenovis/xinxinoptix/DisneyBSDF.h | 32 ++++++++++++++++++------- zenovis/xinxinoptix/IOMat.h | 1 + zenovis/xinxinoptix/PTKernel.cu | 1 + zenovis/xinxinoptix/TraceStuff.h | 2 +- zenovis/xinxinoptix/optixPathTracer.cpp | 2 +- 7 files changed, 42 insertions(+), 15 deletions(-) diff --git a/zeno/src/nodes/mtl/ShaderAttrs.cpp b/zeno/src/nodes/mtl/ShaderAttrs.cpp index bb59105d4e..80060c7f63 100644 --- a/zeno/src/nodes/mtl/ShaderAttrs.cpp +++ b/zeno/src/nodes/mtl/ShaderAttrs.cpp @@ -33,7 +33,7 @@ struct ShaderInputAttr : ShaderNodeClone { ZENDEFNODE(ShaderInputAttr, { { - {"enum pos clr nrm uv tang bitang NoL LoV N T L V H reflectance fresnel instPos instNrm instUv instClr instTang prd.rndf() attrs.localPosLazy() attrs.uniformPosLazy()", "attr", "pos"}, + {"enum pos clr nrm uv tang bitang NoL LoV N T L V H reflectance fresnel instPos instNrm instUv instClr instTang prd.rndf() attrs.localPosLazy() attrs.uniformPosLazy() rayLength", "attr", "pos"}, {"enum float vec2 vec3 vec4", "type", "vec3"}, }, { diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index 8a431e708c..08fce62a0b 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -31,6 +31,7 @@ static __inline__ __device__ MatOutput evalMat(cudaTextureObject_t zenotex[], fl auto att_instUv = attrs.instUv; auto att_instClr = attrs.instClr; auto att_instTang = attrs.instTang; + auto att_rayLength = attrs.rayLength; auto att_NoL = attrs.NoL; auto att_LoV = attrs.LoV; auto att_N = attrs.N; @@ -287,6 +288,7 @@ extern "C" __global__ void __anyhit__shadow_cutout() attrs.clr = interp(barys, clr0, clr1, clr2); attrs.tang = interp(barys, tan0, tan1, tan2); attrs.tang = optixTransformVectorFromObjectToWorldSpace(attrs.tang); + attrs.rayLength = optixGetRayTmax(); attrs.instPos = rt_data->instPos[inst_idx]; attrs.instNrm = rt_data->instNrm[inst_idx]; @@ -440,7 +442,7 @@ extern "C" __global__ void __closesthit__radiance() HitGroupData* rt_data = (HitGroupData*)optixGetSbtDataPointer(); MatInput attrs{}; - + float estimation = 0; #if (_SPHERE_) unsigned short isLight = 0; @@ -496,6 +498,7 @@ extern "C" __global__ void __closesthit__radiance() float3 N_Local = normalize( cross( normalize(_vertices_[1]-_vertices_[0]), normalize(_vertices_[2]-_vertices_[1]) ) ); // this value has precision issue for big float float3 N_World = normalize(optixTransformNormalFromObjectToWorldSpace(N_Local)); + if (isBadVector(N_World)) { N_World = normalize(DisneyBSDF::SampleScatterDirection(prd->seed)); @@ -515,8 +518,10 @@ extern "C" __global__ void __closesthit__radiance() const float3& tan0 = decodeNormal( rt_data->tan[ vert_idx_offset+0 ] ); const float3& tan1 = decodeNormal( rt_data->tan[ vert_idx_offset+1 ] ); const float3& tan2 = decodeNormal( rt_data->tan[ vert_idx_offset+2 ] ); - - attrs.uv = interp(barys, uv0, uv1, uv2);//todo later + float tri_area = length(cross(_vertices_[1]-_vertices_[0], _vertices_[2]-_vertices_[1])); + float uv_area = length(cross(uv1 - uv0, uv2-uv0)); + estimation = uv_area * 4096.0f*4096.0f / (tri_area + 1e-6); + attrs.uv = interp(barys, uv0, uv1, uv2);//todo later attrs.clr = interp(barys, clr0, clr1, clr2); attrs.tang = normalize(interp(barys, tan0, tan1, tan2)); attrs.tang = optixTransformVectorFromObjectToWorldSpace(attrs.tang); @@ -526,7 +531,7 @@ extern "C" __global__ void __closesthit__radiance() attrs.instUv = rt_data->instUv[inst_idx]; attrs.instClr = rt_data->instClr[inst_idx]; attrs.instTang = rt_data->instTang[inst_idx]; - + attrs.rayLength = optixGetRayTmax(); #endif MatOutput mats = evalMaterial(rt_data->textures, rt_data->uniforms, attrs); @@ -561,6 +566,10 @@ extern "C" __global__ void __closesthit__radiance() #endif attrs.nrm = N; + float term = log2(optixGetRayTmax()*prd->pixel_area*sqrt(estimation))/2.5f; +// printf("rayDist:%f, tex_per_area:%f, term:%f, pixel_area:%f\n", optixGetRayTmax(), +// sqrt(estimation), term, prd->pixel_area); + mats.nrm = normalize(mix(mats.nrm, vec3(0,0,1), clamp(term,0.0f,1.0f))); //end of material computation //mats.metallic = clamp(mats.metallic,0.01, 0.99); mats.roughness = clamp(mats.roughness, 0.01f,0.99f); diff --git a/zenovis/xinxinoptix/DisneyBSDF.h b/zenovis/xinxinoptix/DisneyBSDF.h index f93fec323a..9525dece9e 100644 --- a/zenovis/xinxinoptix/DisneyBSDF.h +++ b/zenovis/xinxinoptix/DisneyBSDF.h @@ -281,7 +281,7 @@ namespace DisneyBSDF{ world2local(wo, T, B, N); world2local(N2, T, B, N); - bool reflect = wi.z * wo.z > 0.0f; + bool reflect = (dot(wi, N2) * dot(wo, N2) > 0.0f) ; vec3 Csheen, Cspec0; float F0; @@ -345,7 +345,7 @@ namespace DisneyBSDF{ float ax, ay; BRDFBasics::CalculateAnisotropicParams(mat.roughness,mat.anisotropic,ax,ay); vec3 s = BRDFBasics::EvalMicrofacetReflection(ax, ay, wo, wi, wm, - mix(Cspec0, vec3(1.0f), F) * mat.specular * 0.5f, tmpPdf) * dielectricWt * illum; + mix(Cspec0, vec3(1.0f), F) * mat.specular, tmpPdf) * dielectricWt * illum; sterm = sterm + s; f = f + s; fPdf += tmpPdf * dielectricPr; @@ -615,6 +615,13 @@ namespace DisneyBSDF{ wi = BRDFBasics::UniformSampleHemisphere(r1, r2); flag = transmissionEvent; isSS = false; + tbn.inverse_transform(wi); + wi = normalize(wi); + + if(dot(wi, N2)<0) + { + wi = normalize(wi - 1.01f * dot(wi, N2) * N2); + } } else{ //switch between scattering or diffuse reflection @@ -624,6 +631,14 @@ namespace DisneyBSDF{ prd->fromDiff = true; wi = BRDFBasics::CosineSampleHemisphere(r1, r2); isSS = false; + wi = normalize(reflect(-wo, wm)); + tbn.inverse_transform(wi); + wi = normalize(wi); + + if(dot(wi, N2)<0) + { + wi = normalize(wi - 1.01f * dot(wi, N2) * N2); + } }else { @@ -643,17 +658,18 @@ namespace DisneyBSDF{ CalculateExtinction2(color, sssRadius, prd->sigma_t, prd->ss_alpha, 1.4f); } + tbn.inverse_transform(wi); + wi = normalize(wi); + + bool sameside2 = (dot(wi, N) * dot(wi, N2)) > 0.0f; + if (sameside == false) { + wi = normalize(wi - 1.01f * dot(wi, N2) * N2); + } } } - tbn.inverse_transform(wi); - wi = normalize(wi); - bool sameside2 = (dot(wi, N) * dot(wi, N2)) > 0.0f; - if (sameside == false) { - wi = normalize(wi - 1.01f * dot(wi, N2) * N2); - } if(dot(wi, N2)>0) { isSS = false; diff --git a/zenovis/xinxinoptix/IOMat.h b/zenovis/xinxinoptix/IOMat.h index 9af9677126..fedd3af7e7 100644 --- a/zenovis/xinxinoptix/IOMat.h +++ b/zenovis/xinxinoptix/IOMat.h @@ -62,6 +62,7 @@ struct MatInput { vec3 instTang; float NoL; float LoV; + float rayLength; vec3 reflectance; vec3 N; vec3 T; diff --git a/zenovis/xinxinoptix/PTKernel.cu b/zenovis/xinxinoptix/PTKernel.cu index 6390d750ff..9140c2f054 100644 --- a/zenovis/xinxinoptix/PTKernel.cu +++ b/zenovis/xinxinoptix/PTKernel.cu @@ -159,6 +159,7 @@ extern "C" __global__ void __raygen__rg() ray_direction = normalize(ray_direction); RadiancePRD prd; + prd.pixel_area = cam.height/(float)(h)/(cam.focal_length); prd.adepth = 0; prd.camPos = cam.eye; prd.emission = make_float3(0.f); diff --git a/zenovis/xinxinoptix/TraceStuff.h b/zenovis/xinxinoptix/TraceStuff.h index c8306a1454..4a3f53e7f1 100644 --- a/zenovis/xinxinoptix/TraceStuff.h +++ b/zenovis/xinxinoptix/TraceStuff.h @@ -75,7 +75,7 @@ struct RadiancePRD bool isSS; float scatterStep; int nonThinTransHit; - + float pixel_area; float Lweight; vec3 sigma_t_queue[8]; vec3 ss_alpha_queue[8]; diff --git a/zenovis/xinxinoptix/optixPathTracer.cpp b/zenovis/xinxinoptix/optixPathTracer.cpp index 684647474a..8b6da53c0c 100644 --- a/zenovis/xinxinoptix/optixPathTracer.cpp +++ b/zenovis/xinxinoptix/optixPathTracer.cpp @@ -228,7 +228,7 @@ ushort2 halfNormal(float4 in) float3 val = make_float3((in.x + 1.0f)/2.0f, (in.y + 1.0f)/2.0f, (in.z + 1.0f)/2.0f); - val = normalize(val); + //val = normalize(val); return make_ushort3((unsigned short)(val.x*65536.0f), (unsigned short)(val.y*65536.0f), From 3afe8a5fd3be8eef523eef90d860af9515fc8e1f Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Tue, 19 Dec 2023 03:34:41 +0800 Subject: [PATCH 096/106] disabling normal mip mapping for now --- zenovis/xinxinoptix/DeflMatShader.cu | 2 +- zenovis/xinxinoptix/optixPathTracer.cpp | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index 08fce62a0b..321873d8d9 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -566,7 +566,7 @@ extern "C" __global__ void __closesthit__radiance() #endif attrs.nrm = N; - float term = log2(optixGetRayTmax()*prd->pixel_area*sqrt(estimation))/2.5f; + float term = log2(optixGetRayTmax()*prd->pixel_area*sqrt(estimation))/4.0f; // printf("rayDist:%f, tex_per_area:%f, term:%f, pixel_area:%f\n", optixGetRayTmax(), // sqrt(estimation), term, prd->pixel_area); mats.nrm = normalize(mix(mats.nrm, vec3(0,0,1), clamp(term,0.0f,1.0f))); diff --git a/zenovis/xinxinoptix/optixPathTracer.cpp b/zenovis/xinxinoptix/optixPathTracer.cpp index 8b6da53c0c..06e7ed61c5 100644 --- a/zenovis/xinxinoptix/optixPathTracer.cpp +++ b/zenovis/xinxinoptix/optixPathTracer.cpp @@ -202,7 +202,6 @@ ushort2 halfNormal(float4 in) float3 val = make_float3((in.x + 1.0f)/2.0f, (in.y + 1.0f)/2.0f, (in.z + 1.0f)/2.0f); - val = normalize(val); return make_ushort3((unsigned short)(val.x*65536.0f), (unsigned short)(val.y*65536.0f), From 16185a00c42120caff384d8cf94c52e9ab15deac Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Tue, 19 Dec 2023 12:46:32 +0800 Subject: [PATCH 097/106] disabling normal filtering, offset clamp, background hit fix --- zenovis/xinxinoptix/DeflMatShader.cu | 7 +++++-- zenovis/xinxinoptix/PTKernel.cu | 8 ++++++-- zenovis/xinxinoptix/TraceStuff.h | 4 +++- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index 321873d8d9..0b52322d49 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -569,7 +569,7 @@ extern "C" __global__ void __closesthit__radiance() float term = log2(optixGetRayTmax()*prd->pixel_area*sqrt(estimation))/4.0f; // printf("rayDist:%f, tex_per_area:%f, term:%f, pixel_area:%f\n", optixGetRayTmax(), // sqrt(estimation), term, prd->pixel_area); - mats.nrm = normalize(mix(mats.nrm, vec3(0,0,1), clamp(term,0.0f,1.0f))); + //mats.nrm = normalize(mix(mats.nrm, vec3(0,0,1), clamp(term,0.0f,1.0f))); //end of material computation //mats.metallic = clamp(mats.metallic,0.01, 0.99); mats.roughness = clamp(mats.roughness, 0.01f,0.99f); @@ -636,6 +636,7 @@ extern "C" __global__ void __closesthit__radiance() //prd->origin = P + 1e-5 * ray_dir; if(prd->maxDistance>optixGetRayTmax()) prd->maxDistance-=optixGetRayTmax(); + prd->alphaHit = true; prd->offsetUpdateRay(P, ray_dir); return; } @@ -678,7 +679,8 @@ extern "C" __global__ void __closesthit__radiance() prd->adepth++; //prd->samplePdf = 0.0f; prd->radiance = make_float3(0.0f); - //prd->origin = P + 1e-5 * ray_dir; + //prd->origin = P + 1e-5 * ray_dir; + prd->alphaHit = true; prd->offsetUpdateRay(P, ray_dir); return; } @@ -707,6 +709,7 @@ extern "C" __global__ void __closesthit__radiance() prd->origin = P; prd->direction = ray_dir; + prd->alphaHit = true; prd->offsetUpdateRay(P, ray_dir); prd->prob *= 1; diff --git a/zenovis/xinxinoptix/PTKernel.cu b/zenovis/xinxinoptix/PTKernel.cu index 9140c2f054..7eb53111ab 100644 --- a/zenovis/xinxinoptix/PTKernel.cu +++ b/zenovis/xinxinoptix/PTKernel.cu @@ -200,8 +200,11 @@ extern "C" __global__ void __raygen__rg() } // Primary Ray + unsigned char background_trace = 0; + prd.alphaHit = false; traceRadiance(params.handle, ray_origin, ray_direction, _tmin_, prd.maxDistance, &prd, _mask_); const auto primary_hit_type = prd.hit_type; + background_trace = primary_hit_type; if(primary_hit_type > 0) { result_d = prd.radiance_d * prd.attenuation2; @@ -267,13 +270,14 @@ extern "C" __global__ void __raygen__rg() prd.radiance_d = make_float3(0); prd.radiance_s = make_float3(0); prd.radiance_t = make_float3(0); - + prd.alphaHit = false; traceRadiance(params.handle, ray_origin, ray_direction, _tmin_, prd.maxDistance, &prd, _mask_); + background_trace = prd.hit_type; } seed = prd.seed; - if (primary_hit_type > 0) { + if (background_trace > 0) { result_b += make_float3(1); } } diff --git a/zenovis/xinxinoptix/TraceStuff.h b/zenovis/xinxinoptix/TraceStuff.h index 4a3f53e7f1..d1dfdb5c51 100644 --- a/zenovis/xinxinoptix/TraceStuff.h +++ b/zenovis/xinxinoptix/TraceStuff.h @@ -83,6 +83,7 @@ struct RadiancePRD float samplePdf; bool fromDiff; unsigned char adepth; + bool alphaHit; __forceinline__ float rndf() { return rnd(this->seed); @@ -128,7 +129,8 @@ struct RadiancePRD auto dir = forward? geometryNormal:-geometryNormal; auto offset = rtgems::offset_ray(P, dir); float l = length( offset - P ); - P = l>1e-4? offset : (P + 1e-4 * dir); + float l2 = this->alphaHit? clamp(l, 1e-4, 1e-3) : clamp(l, 1e-5, 1e-4); + P = P + l2 * dir; } void offsetUpdateRay(float3& P, float3 new_dir) { From 7aca7d774be001def2dd65613ad144ea40d0a14f Mon Sep 17 00:00:00 2001 From: YingQ Date: Tue, 19 Dec 2023 15:38:19 +0800 Subject: [PATCH 098/106] add hf softclip --- projects/CuEulerian/swe/Erode.cu | 102 +++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/projects/CuEulerian/swe/Erode.cu b/projects/CuEulerian/swe/Erode.cu index b7fd02d28c..76cd95fb67 100644 --- a/projects/CuEulerian/swe/Erode.cu +++ b/projects/CuEulerian/swe/Erode.cu @@ -3718,4 +3718,106 @@ namespace zeno { "erode", } }); + + struct zs_HF_Clip : INode { + void apply() override { + + auto terrain = get_input("HeightField"); + auto Minclip = get_input2("MinClip"); + auto Maxclip = get_input2("MaxClip"); + auto MinclipValue = get_input2("Minclipheight"); + auto MaxclipValue = get_input2("Maxclipheight"); + auto SoftClip = get_input2("SoftClip"); + auto SoftClipStrength = get_input2("SoftClip Strength"); + auto SoftClipScale = get_input2("SoftClip Scale"); + + size_t nx, nz; + auto &ud = terrain->userData(); + if ((!ud.has("nx")) || (!ud.has("nz"))) + zeno::log_error("no such UserData named '{}' and '{}'.", "nx", "nz"); + nx = ud.get2("nx"); + nz = ud.get2("nz"); + + + auto &height = terrain->verts.attr("height"); + if (!terrain->verts.has_attr("mask")) { + auto &mask = terrain->verts.add_attr("mask"); + std::fill(mask.begin(), mask.end(), 0.0); + } + auto &mask = terrain->verts.attr("mask"); + //////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////// + using namespace zs; + constexpr auto space = execspace_e::cuda; + auto pol = cuda_exec(); + auto zs_height = to_device_vector(height); + auto zs_mask = to_device_vector(mask, false); + pol(range(nz * nx), [=, _height = view(zs_height), _mask = view(zs_mask)] __device__(std::size_t idx) mutable { + float i_height = _height[idx]; + if(Minclip && i_height < MinclipValue){ + if(SoftClip){ + float f = (MinclipValue - i_height) / SoftClipScale; + float compression = SoftClipScale * SoftClipStrength; + float out = f; + if(f>0 && compression>0) + { + float ki = 1.0 / compression; + float w = 1.0 / (compression * zs::log(10.0)); + float k = log10(zs::pow(w,ki)); + out = log10(zs::pow((f+w), ki)) - k; + } + _height[idx] = MinclipValue - out; + }else{ + _height[idx] = MinclipValue; + } + _mask[idx] = 1.0f; + } + if(Maxclip && i_height > MaxclipValue){ + if(SoftClip){ + float f = (i_height - MaxclipValue) / SoftClipScale; + float compression = SoftClipScale * SoftClipStrength; + float out = f; + if(f>0 && compression>0) + { + float ki = 1.0 / compression; + float w = 1.0 / (compression * zs::log(10.0)); + float k = log10(zs::pow(w,ki)); + out = log10(zs::pow((f+w), ki)) - k; + } + _height[idx] = MaxclipValue + out; + }else{ + _height[idx] = MaxclipValue; + } + _mask[idx] = 1.0f; + } + + }); + retrieve_device_vector(height, zs_height); + retrieve_device_vector(mask, zs_mask); + + set_output("HeightField", get_input("HeightField")); + } + }; + ZENDEFNODE(zs_HF_Clip, { + /* inputs: */ + { + "HeightField", + {"bool", "MinClip", "0"}, + {"float", "Minclipheight", "0"}, + {"bool", "MaxClip", "1"}, + {"float", "Maxclipheight", "100"}, + {"bool", "SoftClip", "1"}, + {"float", "SoftClip Strength", "0.1"}, + {"float", "SoftClip Scale", "1"}, + }, + /* outputs: */ + { + "HeightField", + }, + /* params: */ + {}, + /* category: */ + { + "erode", + }}); } // namespace zeno \ No newline at end of file From e037dff3ce3b2690da3ed6fd08221da67600cd24 Mon Sep 17 00:00:00 2001 From: littlemine Date: Tue, 19 Dec 2023 15:47:29 +0800 Subject: [PATCH 099/106] temp node for rearrange seq ids --- projects/CUDA/utils/Primitives.cpp | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/projects/CUDA/utils/Primitives.cpp b/projects/CUDA/utils/Primitives.cpp index 7986074625..b1a1c36316 100644 --- a/projects/CUDA/utils/Primitives.cpp +++ b/projects/CUDA/utils/Primitives.cpp @@ -1302,6 +1302,39 @@ ZENDEFNODE(PrimitiveUnmerge, { {"primitive"}, }); +struct GatherPrimIds : INode { + virtual void apply() override { + auto prim = get_input("prim"); + auto refPrim = get_input("refPrim"); + auto tag = get_input2("tagAttr"); + auto indexTag = get_input2("refIndexTagAttr"); + + const auto &targetIndices = prim->attr("target_index"); + const auto &refAttr = refPrim->attr(tag); + auto &attr = prim->attr(tag); + + using namespace zs; + auto pol = omp_exec(); + pol(range(prim->size()), [&](int vi) { attr[vi] = refAttr[targetIndices[vi]]; }); + + set_output("prim", std::move(prim)); + } +}; + +ZENDEFNODE(GatherPrimIds, { + { + {"primitive", "prim"}, + {"primitive", "refPrim"}, + {"string", "tagAttr", "id"}, + {"string", "refIndexTagAttr", "target_index"}, + }, + { + {"primitive", "prim"}, + }, + {}, + {"primitive"}, + }); + struct MarkSelectedVerts : INode { void apply() override { auto prim = get_input("prim"); From 79c91f3a73b1bd79343ff377d4a001c613ec93f3 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Tue, 19 Dec 2023 16:46:53 +0800 Subject: [PATCH 100/106] thin transmission not using right color --- zenovis/xinxinoptix/DisneyBSDF.h | 2 +- zenovis/xinxinoptix/TraceStuff.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/zenovis/xinxinoptix/DisneyBSDF.h b/zenovis/xinxinoptix/DisneyBSDF.h index 9525dece9e..2b91cc7433 100644 --- a/zenovis/xinxinoptix/DisneyBSDF.h +++ b/zenovis/xinxinoptix/DisneyBSDF.h @@ -379,7 +379,7 @@ namespace DisneyBSDF{ } else { if(thin) { - vec3 t = sqrt(mat.sssColor) * glassWt; + vec3 t = sqrt(mat.transColor) * glassWt; tterm = tterm + t; f = f + t; fPdf += 1.0f * glassPr; diff --git a/zenovis/xinxinoptix/TraceStuff.h b/zenovis/xinxinoptix/TraceStuff.h index d1dfdb5c51..3ce1cecbed 100644 --- a/zenovis/xinxinoptix/TraceStuff.h +++ b/zenovis/xinxinoptix/TraceStuff.h @@ -129,7 +129,7 @@ struct RadiancePRD auto dir = forward? geometryNormal:-geometryNormal; auto offset = rtgems::offset_ray(P, dir); float l = length( offset - P ); - float l2 = this->alphaHit? clamp(l, 1e-4, 1e-3) : clamp(l, 1e-5, 1e-4); + float l2 = this->alphaHit? clamp(l, 1e-4, 1e-3) : clamp(l, 1e-6, 1e-5); P = P + l2 * dir; } From 72aa792fad6bee7a4ea527f44b3564c534a9105a Mon Sep 17 00:00:00 2001 From: seeeagull Date: Tue, 19 Dec 2023 17:47:51 +0800 Subject: [PATCH 101/106] enable use float --- projects/Geometry/fTetWild | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/Geometry/fTetWild b/projects/Geometry/fTetWild index 5d72cc0866..bca0cf5c8a 160000 --- a/projects/Geometry/fTetWild +++ b/projects/Geometry/fTetWild @@ -1 +1 @@ -Subproject commit 5d72cc0866b70840a361bb66c1cbf0c09c2d0718 +Subproject commit bca0cf5c8a7b686431a1b186efea02699b7e72fa From 89510c99a275ef8e3a08e9d5e126da9b742ce625 Mon Sep 17 00:00:00 2001 From: seeeagull Date: Tue, 19 Dec 2023 17:52:02 +0800 Subject: [PATCH 102/106] add Eigen:: --- projects/Geometry/fTetWild | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/projects/Geometry/fTetWild b/projects/Geometry/fTetWild index bca0cf5c8a..3dd9ab9b80 160000 --- a/projects/Geometry/fTetWild +++ b/projects/Geometry/fTetWild @@ -1 +1 @@ -Subproject commit bca0cf5c8a7b686431a1b186efea02699b7e72fa +Subproject commit 3dd9ab9b80ff474581c6ec9ae100a9a445757f2f From 955c09bc2a364658efdb96b102070e776fd1a043 Mon Sep 17 00:00:00 2001 From: zhxx1987 Date: Wed, 20 Dec 2023 02:34:30 +0800 Subject: [PATCH 103/106] aov fix 90% --- zenovis/xinxinoptix/DeflMatShader.cu | 12 ++++++----- zenovis/xinxinoptix/DisneyBSDF.h | 4 ---- zenovis/xinxinoptix/Light.h | 22 ++++++++++++-------- zenovis/xinxinoptix/PTKernel.cu | 31 ++++++++++++++++++++-------- 4 files changed, 42 insertions(+), 27 deletions(-) diff --git a/zenovis/xinxinoptix/DeflMatShader.cu b/zenovis/xinxinoptix/DeflMatShader.cu index 0b52322d49..81033727f7 100644 --- a/zenovis/xinxinoptix/DeflMatShader.cu +++ b/zenovis/xinxinoptix/DeflMatShader.cu @@ -966,18 +966,20 @@ extern "C" __global__ void __closesthit__radiance() if(prd->depth>=3) mats.roughness = clamp(mats.roughness, 0.5f,0.99f); - vec3 rd, rs, rt; // captured by lambda auto evalBxDF = [&](const float3& _wi_, const float3& _wo_, float& thisPDF, vec3 illum = vec3(1.0f)) -> float3 { const auto& L = _wi_; // pre-normalized const vec3& V = _wo_; // pre-normalized + vec3 rd, rs, rt; // captured by lambda float3 lbrdf = DisneyBSDF::EvaluateDisney2(illum,mats, L, V, T, B, N,prd->geometryNormal, mats.thin > 0.5f, flag == DisneyBSDF::transmissionEvent ? inToOut : next_ray_is_going_inside, thisPDF, rrPdf, dot(N, L), rd, rs, rt); - + prd->radiance_d = rd; + prd->radiance_s = rs; + prd->radiance_t = rt; // MatOutput mat2; // if(mats.thin>0.5f){ // vec3 H = normalize(vec3(normalize(L)) + V); @@ -996,9 +998,9 @@ extern "C" __global__ void __closesthit__radiance() }; auto taskAux = [&](const vec3& weight) { - prd->radiance_d = rd * weight; - prd->radiance_s = rs * weight; - prd->radiance_t = rt * weight; + prd->radiance_d *= weight; + prd->radiance_s *= weight; + prd->radiance_t *= weight; }; RadiancePRD shadow_prd {}; diff --git a/zenovis/xinxinoptix/DisneyBSDF.h b/zenovis/xinxinoptix/DisneyBSDF.h index 2b91cc7433..e9519c6043 100644 --- a/zenovis/xinxinoptix/DisneyBSDF.h +++ b/zenovis/xinxinoptix/DisneyBSDF.h @@ -419,10 +419,6 @@ namespace DisneyBSDF{ float term = wo.z>0?FV:FL; float tmpPdf = trans? 1.0f : 0.0f;//0.5/M_PIf:0.0f; -// auto wo2 = wo; -// wo2.z *= -1.0f; -// vec3 d2 = BRDFBasics::EvalDisneyDiffuse(mix(mat.basecolor,mat.sssColor,mat.subsurface), mat.subsurface, mat.roughness, mat.sheen, -// Csheen, wo2, wi, wm, tmpPdf) * illum; // vec3 d = 1.0f/M_PIf * (1.0f - 0.5f * term) * (trans?vec3(1.0f):vec3(0.0f)) * dielectricWt * subsurface; diff --git a/zenovis/xinxinoptix/Light.h b/zenovis/xinxinoptix/Light.h index 2619d3af9f..4e9fa609c5 100644 --- a/zenovis/xinxinoptix/Light.h +++ b/zenovis/xinxinoptix/Light.h @@ -404,9 +404,10 @@ void DirectLighting(RadiancePRD *prd, RadiancePRD& shadow_prd, const float3& sha light_attenuation = shadow_prd.shadowAttanuation; if (nullptr==RadianceWithoutShadow && lengthSquared(light_attenuation) == 0.0f) return; - - auto bxdf_value = evalBxDF(lsr.dir, wo, scatterPDF); - auto misWeight = 1.0f; + + emission *= lsr.intensity; + auto bxdf_value = evalBxDF(lsr.dir, wo, scatterPDF, vec3(emission)); + auto misWeight = 1.0f; if constexpr(_MIS_) { if (!light.isDeltaLight() && !lsr.isDelta) { @@ -414,21 +415,24 @@ void DirectLighting(RadiancePRD *prd, RadiancePRD& shadow_prd, const float3& sha } } - emission *= lsr.intensity; - float3 radianceNoShadow = emission * bxdf_value; + + float3 radianceNoShadow = bxdf_value; radianceNoShadow *= misWeight / lsr.PDF; if (nullptr != RadianceWithoutShadow) { *RadianceWithoutShadow = radianceNoShadow; } - if constexpr (!detail::is_void::value) { - auto tmp = light_attenuation * misWeight / lsr.PDF; - (*taskAux)(tmp); - }// TypeAux + //if constexpr (!detail::is_void::value) { + //auto tmp = light_attenuation * misWeight / lsr.PDF; + //(*taskAux)(vec3(tmp)); + //}// TypeAux prd->radiance = radianceNoShadow * light_attenuation; // with shadow + prd->radiance_d *= light_attenuation * misWeight / lsr.PDF; + prd->radiance_s *= light_attenuation * misWeight / lsr.PDF; + prd->radiance_t *= light_attenuation * misWeight / lsr.PDF; } } else { diff --git a/zenovis/xinxinoptix/PTKernel.cu b/zenovis/xinxinoptix/PTKernel.cu index 7eb53111ab..ca591dc34c 100644 --- a/zenovis/xinxinoptix/PTKernel.cu +++ b/zenovis/xinxinoptix/PTKernel.cu @@ -91,6 +91,7 @@ extern "C" __global__ void __raygen__rg() float3 result_s = make_float3( 0.0f ); float3 result_t = make_float3( 0.0f ); float3 result_b = make_float3( 0.0f ); + float3 aov[4]; int i = params.samples_per_launch; float3 tmp_albedo{}; @@ -203,7 +204,7 @@ extern "C" __global__ void __raygen__rg() unsigned char background_trace = 0; prd.alphaHit = false; traceRadiance(params.handle, ray_origin, ray_direction, _tmin_, prd.maxDistance, &prd, _mask_); - const auto primary_hit_type = prd.hit_type; + auto primary_hit_type = prd.hit_type; background_trace = primary_hit_type; if(primary_hit_type > 0) { @@ -218,7 +219,10 @@ extern "C" __global__ void __raygen__rg() prd.trace_denoise_albedo = false; prd.trace_denoise_normal = false; - float3* aov[4] = {&result_b, &result_d, &result_s, &result_t}; + aov[0] = result_b; + aov[1] = result_d; + aov[2] = result_s; + aov[3] = result_t; for(;;) { @@ -226,7 +230,7 @@ extern "C" __global__ void __raygen__rg() _mask_ = prd._mask_; prd._tmin_ = 0; - prd._mask_ = EverythingMask; + prd._mask_ = EverythingMask; ray_origin = prd.origin; ray_direction = prd.direction; @@ -240,7 +244,7 @@ extern "C" __global__ void __raygen__rg() result += prd.depth>1?clampped:temp_radiance; if(primary_hit_type > 0 && ( prd.depth>1 || (prd.depth==1 && prd.hit_type == 0) )) { - *aov[primary_hit_type] += clampped; + aov[primary_hit_type] += prd.depth>1?clampped:temp_radiance; } } @@ -271,13 +275,22 @@ extern "C" __global__ void __raygen__rg() prd.radiance_s = make_float3(0); prd.radiance_t = make_float3(0); prd.alphaHit = false; + traceRadiance(params.handle, ray_origin, ray_direction, _tmin_, prd.maxDistance, &prd, _mask_); - background_trace = prd.hit_type; + + + if(prd.hit_type>0 && primary_hit_type==0) + { + primary_hit_type = prd.hit_type; + aov[primary_hit_type] += (prd.hit_type==1?prd.radiance_d:(prd.hit_type==2?prd.radiance_s:prd.radiance_t))*prd.attenuation2; + } + background_trace += prd.hit_type>0?1:0; + } seed = prd.seed; - if (background_trace > 0) { + if (!(background_trace == 0)) { result_b += make_float3(1); } } @@ -286,9 +299,9 @@ extern "C" __global__ void __raygen__rg() auto samples_per_launch = static_cast( params.samples_per_launch ); float3 accum_color = result / samples_per_launch; - float3 accum_color_d = result_d / samples_per_launch; - float3 accum_color_s = result_s / samples_per_launch; - float3 accum_color_t = result_t / samples_per_launch; + float3 accum_color_d = aov[1] / samples_per_launch; + float3 accum_color_s = aov[2] / samples_per_launch; + float3 accum_color_t = aov[3] / samples_per_launch; float3 accum_color_b = result_b / samples_per_launch; if( subframe_index > 0 ) From 30fde95de05d04bde4a23b64e98625d86557f0d5 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Fri, 22 Dec 2023 14:14:11 +0800 Subject: [PATCH 104/106] fix-for-ctrl-key-press-miss --- ui/zenoedit/viewport/viewportwidget.cpp | 5 +++++ ui/zenoedit/viewport/viewportwidget.h | 1 + 2 files changed, 6 insertions(+) diff --git a/ui/zenoedit/viewport/viewportwidget.cpp b/ui/zenoedit/viewport/viewportwidget.cpp index 8c4442d4e0..db0866c991 100644 --- a/ui/zenoedit/viewport/viewportwidget.cpp +++ b/ui/zenoedit/viewport/viewportwidget.cpp @@ -409,3 +409,8 @@ void ViewportWidget::keyReleaseEvent(QKeyEvent *event) { return; } } + +void ViewportWidget::enterEvent(QEvent *event) { + setFocus(); + QWidget::enterEvent(event); +} diff --git a/ui/zenoedit/viewport/viewportwidget.h b/ui/zenoedit/viewport/viewportwidget.h index c34eac44d0..3a40259b1f 100644 --- a/ui/zenoedit/viewport/viewportwidget.h +++ b/ui/zenoedit/viewport/viewportwidget.h @@ -61,6 +61,7 @@ class ViewportWidget : public QGLWidget void mouseReleaseEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void mouseDoubleClickEvent(QMouseEvent* event) override; + void enterEvent(QEvent * event) override; void wheelEvent(QWheelEvent* event) override; void keyPressEvent(QKeyEvent* event) override; void keyReleaseEvent(QKeyEvent* event) override; From 13b569983a8fdc699fb0ae98f2496599dfada773 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Fri, 22 Dec 2023 16:57:32 +0800 Subject: [PATCH 105/106] path-PrimitiveTransform --- zeno/src/nodes/prim/TransformPrimitive.cpp | 137 ++++++++++++++------- 1 file changed, 93 insertions(+), 44 deletions(-) diff --git a/zeno/src/nodes/prim/TransformPrimitive.cpp b/zeno/src/nodes/prim/TransformPrimitive.cpp index 9f0d3c3038..6474f4eb29 100644 --- a/zeno/src/nodes/prim/TransformPrimitive.cpp +++ b/zeno/src/nodes/prim/TransformPrimitive.cpp @@ -1,5 +1,7 @@ #include "zeno/types/UserData.h" #include "zeno/funcs/ObjectGeometryInfo.h" +#include "zeno/types/ListObject.h" +#include "zeno/utils/log.h" #include #include #include @@ -11,6 +13,7 @@ #include #include #include +#include namespace zeno { namespace { @@ -208,6 +211,89 @@ struct PrimitiveTransform : zeno::INode { return glm::normalize(vector3); } + static std::optional> get_from_list(std::string path, std::shared_ptr iObject) { + if (path.empty() || path == "/") { + return iObject; + } + auto cur_root = iObject; + auto idxs = split_str(path, '/'); + std::vector idxs_int; + for (const auto &idx: idxs) { + if (idx.empty()) { + continue; + } + auto i = std::stoi(idx); + if (auto list = std::dynamic_pointer_cast(cur_root)) { + if (i >= list->arr.size()) { + zeno::log_info("out of range"); + return std::nullopt; + } + cur_root = list->arr[i]; + } + else { + return cur_root; + } + } + zeno::log_info("missing"); + return cur_root; + } + + static void transformObj( + std::shared_ptr iObject + , glm::mat4 matrix + , std::string pivotType + , vec3f translate + , vec4f rotation + , vec3f scaling + ) { + if (auto prim = std::dynamic_pointer_cast(iObject)) { + + zeno::vec3f _pivot = {}; + if (pivotType == "bboxCenter") { + zeno::vec3f _min; + zeno::vec3f _max; + objectGetBoundingBox(prim.get(), _min, _max); + auto p = (_min + _max) / 2; + auto pivot_to_local = glm::translate(glm::vec3(-p[0], -p[1], -p[2])); + auto pivot_to_world = glm::translate(glm::vec3(p[0], p[1], p[2])); + matrix = pivot_to_world * matrix * pivot_to_local; + _pivot = p; + } + + if (prim->has_attr("pos")) { + auto &pos = prim->attr("pos"); + prim->verts.add_attr("_origin_pos") = pos; + #pragma omp parallel for + for (int i = 0; i < pos.size(); i++) { + auto p = zeno::vec_to_other(pos[i]); + p = mapplypos(matrix, p); + pos[i] = zeno::other_to_vec<3>(p); + } + } + + if (prim->has_attr("nrm")) { + auto &nrm = prim->attr("nrm"); + prim->verts.add_attr("_origin_nrm") = nrm; + #pragma omp parallel for + for (int i = 0; i < nrm.size(); i++) { + auto n = zeno::vec_to_other(nrm[i]); + n = mapplynrm(matrix, n); + nrm[i] = zeno::other_to_vec<3>(n); + } + } + + auto& user_data = prim->userData(); + user_data.setLiterial("_translate", translate); + user_data.setLiterial("_rotate", rotation); + user_data.setLiterial("_scale", scaling); + user_data.set2("_pivot", _pivot); + } + else if (auto list = std::dynamic_pointer_cast(iObject)) { + for (auto &item : list->arr) { + transformObj(item, matrix, pivotType, translate, rotation, scaling); + } + } + } virtual void apply() override { zeno::vec3f translate = {0,0,0}; zeno::vec4f rotation = {0,0,0,1}; @@ -269,59 +355,22 @@ struct PrimitiveTransform : zeno::INode { auto matrix = pre_mat*local*matTrans*matRotate*matQuat*matScal*matShearZ*matShearY*matShearX*glm::translate(glm::vec3(offset[0], offset[1], offset[2]))*glm::inverse(local)*pre_apply; - auto prim = get_input("prim"); + auto iObject = get_input2("prim"); + auto path = get_input2("path"); std::string pivotType = get_input2("pivot"); - zeno::vec3f _pivot = {}; - if (pivotType == "bboxCenter") { - zeno::vec3f _min; - zeno::vec3f _max; - objectGetBoundingBox(prim.get(), _min, _max); - auto p = (_min + _max) / 2; - auto pivot_to_local = glm::translate(glm::vec3(-p[0], -p[1], -p[2])); - auto pivot_to_world = glm::translate(glm::vec3(p[0], p[1], p[2])); - matrix = pivot_to_world * matrix * pivot_to_local; - _pivot = p; - } - - auto outprim = std::make_unique(*prim); - - if (prim->has_attr("pos")) { - auto &pos = outprim->attr("pos"); - outprim->verts.add_attr("_origin_pos") = pos; -#pragma omp parallel for - for (int i = 0; i < pos.size(); i++) { - auto p = zeno::vec_to_other(pos[i]); - p = mapplypos(matrix, p); - pos[i] = zeno::other_to_vec<3>(p); - } + auto select = get_from_list(path, iObject); + if (select.has_value()) { + transformObj(select.value(), matrix, pivotType, translate, rotation, scaling); } - if (prim->has_attr("nrm")) { - auto &nrm = outprim->attr("nrm"); - outprim->verts.add_attr("_origin_nrm") = nrm; -#pragma omp parallel for - for (int i = 0; i < nrm.size(); i++) { - auto n = zeno::vec_to_other(nrm[i]); - n = mapplynrm(matrix, n); - nrm[i] = zeno::other_to_vec<3>(n); - } - } - - auto& user_data = outprim->userData(); - user_data.setLiterial("_translate", translate); - vec4f rotate = {myQuat.x, myQuat.y, myQuat.z, myQuat.w}; - user_data.setLiterial("_rotate", rotate); - user_data.setLiterial("_scale", scaling); - user_data.set2("_pivot", _pivot); - //auto oMat = std::make_shared(); - //oMat->m = matrix; - set_output("outPrim", std::move(outprim)); + set_output("outPrim", std::move(iObject)); } }; ZENDEFNODE(PrimitiveTransform, { { + {"string", "path"}, {"PrimitiveObject", "prim"}, {"enum world bboxCenter", "pivot", "bboxCenter"}, {"vec3f", "translation", "0,0,0"}, From 36fd6da318be4f0a23cc94a6f0089c5bab53cf81 Mon Sep 17 00:00:00 2001 From: zhouhang95 <765229842@qq.com> Date: Fri, 22 Dec 2023 17:01:46 +0800 Subject: [PATCH 106/106] remove log --- zeno/src/nodes/prim/TransformPrimitive.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/zeno/src/nodes/prim/TransformPrimitive.cpp b/zeno/src/nodes/prim/TransformPrimitive.cpp index 6474f4eb29..52a5c992f6 100644 --- a/zeno/src/nodes/prim/TransformPrimitive.cpp +++ b/zeno/src/nodes/prim/TransformPrimitive.cpp @@ -225,7 +225,7 @@ struct PrimitiveTransform : zeno::INode { auto i = std::stoi(idx); if (auto list = std::dynamic_pointer_cast(cur_root)) { if (i >= list->arr.size()) { - zeno::log_info("out of range"); + zeno::log_warn("out of range"); return std::nullopt; } cur_root = list->arr[i]; @@ -234,7 +234,6 @@ struct PrimitiveTransform : zeno::INode { return cur_root; } } - zeno::log_info("missing"); return cur_root; }