1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef SCENE_EXT_COMPONENT_UTIL_H 17 #define SCENE_EXT_COMPONENT_UTIL_H 18 19 #include <scene/ext/intf_component_factory.h> 20 #include <scene/ext/intf_ecs_context.h> 21 #include <scene/ext/intf_ecs_object_access.h> 22 #include <scene/ext/intf_internal_scene.h> 23 SCENE_BEGIN_NAMESPACE()24SCENE_BEGIN_NAMESPACE() 25 26 template<typename Manager> 27 bool AddComponent(INode::Ptr node) 28 { 29 auto acc = interface_cast<IEcsObjectAccess>(node); 30 if (!acc) { 31 CORE_LOG_E("Invalid node, no ecs access"); 32 return false; 33 } 34 auto ecsObj = acc->GetEcsObject(); 35 if (!ecsObj) { 36 CORE_LOG_E("Invalid node, ecs object is null"); 37 return false; 38 } 39 auto entity = ecsObj->GetEntity(); 40 41 auto is = node->GetScene()->GetInternalScene(); 42 auto m = CORE_NS::GetManager<Manager>(*is->GetEcsContext().GetNativeEcs()); 43 44 if (!m->HasComponent(entity)) { 45 m->Create(entity); 46 } 47 48 auto fac = is->FindComponentFactory(Manager::UID); 49 if (!fac) { 50 CORE_LOG_E("Failed to create component factory"); 51 return false; 52 } 53 54 auto c = fac->CreateComponent(ecsObj); 55 if (!c) { 56 CORE_LOG_E("Failed to create component"); 57 return false; 58 } 59 60 auto obj = interface_cast<META_NS::IAttach>(node); 61 if (!obj) { 62 CORE_LOG_E("Failed to attach component to node"); 63 return false; 64 } 65 66 obj->Attach(c); 67 return true; 68 } 69 70 SCENE_END_NAMESPACE() 71 72 #endif