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 #include "Raycast.h"
17
18 #include <meta/interface/intf_object.h>
19 #include <napi_api.h>
20 #include <scene/interface/component_util.h>
21 #include <scene/interface/intf_raycast.h>
22
23 #include "BaseObjectJS.h"
24 #include "Vec3Proxy.h"
25
CreateRaycastResult(NapiApi::StrongRef scene,napi_env env,SCENE_NS::NodeHit hitResult)26 NapiApi::Object CreateRaycastResult(NapiApi::StrongRef scene, napi_env env, SCENE_NS::NodeHit hitResult)
27 {
28 auto result = NapiApi::Object { env };
29
30 napi_value args[] = { scene.GetValue(), NapiApi::Object { env }.ToNapiValue() };
31 const auto jsNode = CreateFromNativeInstance(env, hitResult.node, PtrType::WEAK, args);
32
33 auto centerDistance = napi_value {};
34 auto distance = napi_value {};
35 napi_create_double(env, hitResult.distance, &distance);
36 napi_create_double(env, hitResult.distanceToCenter, ¢erDistance);
37
38 result.Set("node", jsNode);
39 result.Set("centerDistance", centerDistance);
40 result.Set("distance", distance);
41 result.Set("hitPosition", Vec3Proxy::ToNapiObject(hitResult.position, env));
42 return result;
43 }
44
ToNativeOptions(napi_env env,NapiApi::Object raycastParameters)45 SCENE_NS::RayCastOptions ToNativeOptions(napi_env env, NapiApi::Object raycastParameters)
46 {
47 auto layerMask = uint64_t {};
48 auto jsObj = NapiApi::Object { env, raycastParameters.Get("layerMask") };
49 if (auto rootObject = jsObj.GetRoot()) {
50 // Layer masks are served as Node objects to the JS side.
51 if (auto nativeNode = interface_pointer_cast<SCENE_NS::INode>(rootObject->GetNativeObject())) {
52 if (auto layerComponent = SCENE_NS::GetComponent<SCENE_NS::ILayer>(nativeNode)) {
53 layerMask = layerComponent->LayerMask()->GetValue();
54 }
55 }
56 }
57
58 auto rootNode = SCENE_NS::INode::ConstPtr {};
59 auto anotherjsObj = NapiApi::Object { env, raycastParameters.Get("rootNode") };
60 if (auto rootObject = anotherjsObj.GetRoot()) {
61 rootNode = interface_pointer_cast<SCENE_NS::INode>(rootObject->GetNativeObject());
62 }
63 return { layerMask, rootNode };
64 }
65