From 5cff7b96b5d28755d5d82e8b203c831adddeaab9 Mon Sep 17 00:00:00 2001
From: Franz Beaune <franz@appleseedhq.net>
Date: Thu, 1 Nov 2018 15:18:00 +0100
Subject: [PATCH] Fix small bug when updating projects from rev. 9 to 10

When two Specular BTDFs were almost paired but not quite (because the IORs wouldn't match, for instance) then both were inserted into the assembly but potentially with the same name.

When this happens, we now skip the insertion of the second one.
---
 .../modeling/project/projectfileupdater.cpp      | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)

diff --git a/src/appleseed/renderer/modeling/project/projectfileupdater.cpp b/src/appleseed/renderer/modeling/project/projectfileupdater.cpp
index 5ef581599d..e1ecdceca5 100644
--- a/src/appleseed/renderer/modeling/project/projectfileupdater.cpp
+++ b/src/appleseed/renderer/modeling/project/projectfileupdater.cpp
@@ -864,10 +864,15 @@ namespace
                         // Extract mat1 from the assembly.
                         auto_release_ptr<Material> mat1_owner = assembly.materials().remove(mat1.m_material);
 
+                        // Extract mat1's BSDF from the assembly.
+                        auto_release_ptr<BSDF> bsdf_owner = assembly.bsdfs().remove(mat1.m_bsdf);
+
                         // Update mat1's BSDF.
                         // todo: make sure the BSDF is not used in another material.
-                        auto_release_ptr<BSDF> bsdf_owner = assembly.bsdfs().remove(mat1.m_bsdf);
                         update_bsdf(mat1);
+                        assert(assembly.bsdfs().get_by_name(bsdf_owner->get_name()) == nullptr);
+
+                        // Insert mat1's BSDF back into the assembly.
                         assembly.bsdfs().insert(bsdf_owner);
 
                         // Rename mat1.
@@ -897,11 +902,16 @@ namespace
 
                 if (!i->m_updated)
                 {
+                    // Extract the material's BSDF from the assembly.
+                    auto_release_ptr<BSDF> bsdf_owner = assembly.bsdfs().remove(i->m_bsdf);
+
                     // Update the material's BSDF.
                     // todo: make sure the BSDF is not used in another material.
-                    auto_release_ptr<BSDF> bsdf_owner = assembly.bsdfs().remove(i->m_bsdf);
                     update_bsdf(*i);
-                    assembly.bsdfs().insert(bsdf_owner);
+
+                    // Insert the material's BSDF back into the assembly.
+                    if (assembly.bsdfs().get_by_name(bsdf_owner->get_name()) == nullptr)
+                        assembly.bsdfs().insert(bsdf_owner);
 
                     i->m_updated = true;
                 }