Path: blob/master/modules/gltf/extensions/physics/gltf_document_extension_physics.cpp
10279 views
/**************************************************************************/1/* gltf_document_extension_physics.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "gltf_document_extension_physics.h"3132#include "scene/3d/physics/area_3d.h"33#include "scene/3d/physics/rigid_body_3d.h"34#include "scene/3d/physics/static_body_3d.h"3536using GLTFShapeIndex = int64_t;3738// Import process.39Error GLTFDocumentExtensionPhysics::import_preflight(Ref<GLTFState> p_state, Vector<String> p_extensions) {40if (!p_extensions.has("OMI_collider") && !p_extensions.has("OMI_physics_body") && !p_extensions.has("OMI_physics_shape")) {41return ERR_SKIP;42}43Dictionary state_json = p_state->get_json();44if (state_json.has("extensions")) {45Dictionary state_extensions = state_json["extensions"];46if (state_extensions.has("OMI_physics_shape")) {47Dictionary omi_physics_shape_ext = state_extensions["OMI_physics_shape"];48if (omi_physics_shape_ext.has("shapes")) {49Array state_shape_dicts = omi_physics_shape_ext["shapes"];50if (state_shape_dicts.size() > 0) {51Array state_shapes;52for (int i = 0; i < state_shape_dicts.size(); i++) {53state_shapes.push_back(GLTFPhysicsShape::from_dictionary(state_shape_dicts[i]));54}55p_state->set_additional_data(StringName("GLTFPhysicsShapes"), state_shapes);56}57}58#ifndef DISABLE_DEPRECATED59} else if (state_extensions.has("OMI_collider")) {60Dictionary omi_collider_ext = state_extensions["OMI_collider"];61if (omi_collider_ext.has("colliders")) {62Array state_collider_dicts = omi_collider_ext["colliders"];63if (state_collider_dicts.size() > 0) {64Array state_colliders;65for (int i = 0; i < state_collider_dicts.size(); i++) {66state_colliders.push_back(GLTFPhysicsShape::from_dictionary(state_collider_dicts[i]));67}68p_state->set_additional_data(StringName("GLTFPhysicsShapes"), state_colliders);69}70}71#endif // DISABLE_DEPRECATED72}73}74return OK;75}7677Vector<String> GLTFDocumentExtensionPhysics::get_supported_extensions() {78Vector<String> ret;79ret.push_back("OMI_collider");80ret.push_back("OMI_physics_body");81ret.push_back("OMI_physics_shape");82return ret;83}8485Error GLTFDocumentExtensionPhysics::parse_node_extensions(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &p_extensions) {86#ifndef DISABLE_DEPRECATED87if (p_extensions.has("OMI_collider")) {88Dictionary node_collider_ext = p_extensions["OMI_collider"];89if (node_collider_ext.has("collider")) {90// "collider" is the index of the collider in the state colliders array.91int node_collider_index = node_collider_ext["collider"];92Array state_colliders = p_state->get_additional_data(StringName("GLTFPhysicsShapes"));93ERR_FAIL_INDEX_V_MSG(node_collider_index, state_colliders.size(), Error::ERR_FILE_CORRUPT, "glTF Physics: On node " + p_gltf_node->get_name() + ", the collider index " + itos(node_collider_index) + " is not in the state colliders (size: " + itos(state_colliders.size()) + ").");94p_gltf_node->set_additional_data(StringName("GLTFPhysicsShape"), state_colliders[node_collider_index]);95} else {96p_gltf_node->set_additional_data(StringName("GLTFPhysicsShape"), GLTFPhysicsShape::from_dictionary(node_collider_ext));97}98}99#endif // DISABLE_DEPRECATED100if (p_extensions.has("OMI_physics_body")) {101Dictionary physics_body_ext = p_extensions["OMI_physics_body"];102if (physics_body_ext.has("collider")) {103Dictionary node_collider = physics_body_ext["collider"];104// "shape" is the index of the shape in the state shapes array.105int node_shape_index = node_collider.get("shape", -1);106if (node_shape_index != -1) {107Array state_shapes = p_state->get_additional_data(StringName("GLTFPhysicsShapes"));108ERR_FAIL_INDEX_V_MSG(node_shape_index, state_shapes.size(), Error::ERR_FILE_CORRUPT, "glTF Physics: On node " + p_gltf_node->get_name() + ", the shape index " + itos(node_shape_index) + " is not in the state shapes (size: " + itos(state_shapes.size()) + ").");109p_gltf_node->set_additional_data(StringName("GLTFPhysicsColliderShape"), state_shapes[node_shape_index]);110p_gltf_node->set_additional_data(StringName("GLTFPhysicsColliderShapeIndex"), node_shape_index);111} else {112// If this node is a collider but does not have a collider113// shape, then it only serves to combine together shapes.114p_gltf_node->set_additional_data(StringName("GLTFPhysicsCompoundCollider"), true);115}116}117if (physics_body_ext.has("trigger")) {118Dictionary node_trigger = physics_body_ext["trigger"];119// "shape" is the index of the shape in the state shapes array.120int node_shape_index = node_trigger.get("shape", -1);121if (node_shape_index != -1) {122Array state_shapes = p_state->get_additional_data(StringName("GLTFPhysicsShapes"));123ERR_FAIL_INDEX_V_MSG(node_shape_index, state_shapes.size(), Error::ERR_FILE_CORRUPT, "glTF Physics: On node " + p_gltf_node->get_name() + ", the shape index " + itos(node_shape_index) + " is not in the state shapes (size: " + itos(state_shapes.size()) + ").");124p_gltf_node->set_additional_data(StringName("GLTFPhysicsTriggerShape"), state_shapes[node_shape_index]);125p_gltf_node->set_additional_data(StringName("GLTFPhysicsTriggerShapeIndex"), node_shape_index);126} else {127// If this node is a trigger but does not have a trigger shape,128// then it's a trigger body, what Godot calls an Area3D node.129Ref<GLTFPhysicsBody> trigger_body;130trigger_body.instantiate();131trigger_body->set_body_type("trigger");132p_gltf_node->set_additional_data(StringName("GLTFPhysicsBody"), trigger_body);133}134// If this node defines explicit member shape nodes, save this information.135if (node_trigger.has("nodes")) {136Array compound_trigger_nodes = node_trigger["nodes"];137p_gltf_node->set_additional_data(StringName("GLTFPhysicsCompoundTriggerNodes"), compound_trigger_nodes);138}139}140if (physics_body_ext.has("motion") || physics_body_ext.has("type")) {141p_gltf_node->set_additional_data(StringName("GLTFPhysicsBody"), GLTFPhysicsBody::from_dictionary(physics_body_ext));142}143}144return OK;145}146147bool _will_gltf_shape_become_subnode(Ref<GLTFState> p_state, const Ref<GLTFNode> p_gltf_node, GLTFNodeIndex p_gltf_node_index) {148if (p_gltf_node->has_additional_data(StringName("GLTFPhysicsBody"))) {149return true;150}151const TypedArray<GLTFNode> state_gltf_nodes = p_state->get_nodes();152const GLTFNodeIndex parent_index = p_gltf_node->get_parent();153if (parent_index == -1 || parent_index >= state_gltf_nodes.size()) {154return true;155}156const Ref<GLTFNode> parent_gltf_node = state_gltf_nodes[parent_index];157const Variant parent_body_maybe = parent_gltf_node->get_additional_data(StringName("GLTFPhysicsBody"));158if (parent_body_maybe.get_type() != Variant::NIL) {159Ref<GLTFPhysicsBody> parent_body = parent_body_maybe;160// If the parent matches the triggerness, then this node will be generated as a shape (CollisionShape3D).161// Otherwise, if there is a mismatch, a body will be generated for this node, and a subnode will also be generated for the shape.162if (parent_body->get_body_type() == "trigger") {163return p_gltf_node->has_additional_data(StringName("GLTFPhysicsColliderShape"));164} else {165return p_gltf_node->has_additional_data(StringName("GLTFPhysicsTriggerShape"));166}167}168if (parent_gltf_node->has_additional_data(StringName("GLTFPhysicsColliderShape"))) {169return false;170}171if (parent_gltf_node->has_additional_data(StringName("GLTFPhysicsTriggerShape"))) {172return false;173}174Variant compound_trigger_maybe = parent_gltf_node->has_additional_data(StringName("GLTFPhysicsCompoundTriggerNodes"));175if (compound_trigger_maybe.get_type() != Variant::NIL) {176Array compound_trigger_nodes = compound_trigger_maybe;177// Remember, JSON only has numbers, not integers, so must cast to double.178return !compound_trigger_nodes.has((double)p_gltf_node_index);179}180return true;181}182183NodePath _get_scene_node_path_for_shape_index(Ref<GLTFState> p_state, const GLTFNodeIndex p_shape_index) {184TypedArray<GLTFNode> state_gltf_nodes = p_state->get_nodes();185for (GLTFNodeIndex node_index = 0; node_index < state_gltf_nodes.size(); node_index++) {186const Ref<GLTFNode> gltf_node = state_gltf_nodes[node_index];187ERR_CONTINUE(gltf_node.is_null());188// Check if this node has a shape index and if it matches the one we are looking for.189Variant shape_index_maybe = gltf_node->get_additional_data(StringName("GLTFPhysicsColliderShapeIndex"));190if (shape_index_maybe.get_type() != Variant::INT) {191shape_index_maybe = gltf_node->get_additional_data(StringName("GLTFPhysicsTriggerShapeIndex"));192if (shape_index_maybe.get_type() != Variant::INT) {193continue;194}195}196const GLTFShapeIndex shape_index = shape_index_maybe;197if (shape_index != p_shape_index) {198continue;199}200NodePath node_path = gltf_node->get_scene_node_path(p_state);201// At this point, we have found a node with the shape index we were looking for.202if (_will_gltf_shape_become_subnode(p_state, gltf_node, node_index)) {203Vector<StringName> sname_path = node_path.get_names();204sname_path.append(gltf_node->get_name() + "Shape");205node_path = NodePath(sname_path, false);206}207return node_path;208}209return NodePath();210}211212Ref<GLTFObjectModelProperty> GLTFDocumentExtensionPhysics::import_object_model_property(Ref<GLTFState> p_state, const PackedStringArray &p_split_json_pointer, const TypedArray<NodePath> &p_partial_paths) {213Ref<GLTFObjectModelProperty> ret;214if (p_split_json_pointer.size() != 6) {215// The only properties this class cares about are exactly 6 levels deep.216return ret;217}218ret.instantiate();219const String &prop_name = p_split_json_pointer[5];220if (p_split_json_pointer[0] == "extensions" && p_split_json_pointer[2] == "shapes") {221if (p_split_json_pointer[1] == "OMI_physics_shape" || p_split_json_pointer[1] == "KHR_collision_shapes") {222const GLTFNodeIndex shape_index = p_split_json_pointer[3].to_int();223NodePath node_path = _get_scene_node_path_for_shape_index(p_state, shape_index);224if (node_path.is_empty()) {225return ret;226}227String godot_prop_name = prop_name;228if (prop_name == "size") {229ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);230} else if (prop_name == "height" || prop_name == "radius") {231ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);232} else if (prop_name == "radiusBottom" || prop_name == "radiusTop") {233godot_prop_name = "radius";234ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);235} else {236// Not something we handle, return without appending a NodePath.237return ret;238}239// Example: `A/B/C/CollisionShape3D:shape:radius`.240Vector<StringName> subnames;241subnames.append("shape");242subnames.append(godot_prop_name);243node_path = NodePath(node_path.get_names(), subnames, false);244ret->append_node_path(node_path);245}246} else if (p_split_json_pointer[0] == "nodes" && p_split_json_pointer[2] == "extensions" && p_split_json_pointer[4] == "motion") {247if (p_split_json_pointer[3] == "OMI_physics_body" || p_split_json_pointer[3] == "KHR_physics_rigid_bodies") {248const GLTFNodeIndex node_index = p_split_json_pointer[1].to_int();249const TypedArray<GLTFNode> all_gltf_nodes = p_state->get_nodes();250ERR_FAIL_INDEX_V_MSG(node_index, all_gltf_nodes.size(), ret, "GLTF Physics: The node index " + itos(node_index) + " is not in the state nodes (size: " + itos(all_gltf_nodes.size()) + ").");251const Ref<GLTFNode> gltf_node = all_gltf_nodes[node_index];252NodePath node_path;253if (p_partial_paths.is_empty()) {254node_path = gltf_node->get_scene_node_path(p_state);255} else {256// The path is already computed for us, just grab it.257node_path = p_partial_paths[0];258}259if (prop_name == "mass") {260ret->append_path_to_property(node_path, "mass");261ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);262} else if (prop_name == "linearVelocity") {263ret->append_path_to_property(node_path, "linear_velocity");264ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);265} else if (prop_name == "angularVelocity") {266ret->append_path_to_property(node_path, "angular_velocity");267ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);268} else if (prop_name == "centerOfMass") {269ret->append_path_to_property(node_path, "center_of_mass");270ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);271} else if (prop_name == "inertiaDiagonal") {272ret->append_path_to_property(node_path, "inertia");273ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);274} else if (prop_name == "inertiaOrientation") {275WARN_PRINT("GLTF Physics: The 'inertiaOrientation' property is not supported by Godot.");276} else {277// Not something we handle, return without appending a NodePath.278return ret;279}280}281}282return ret;283}284285void _setup_shape_mesh_resource_from_index_if_needed(Ref<GLTFState> p_state, Ref<GLTFPhysicsShape> p_gltf_shape) {286GLTFMeshIndex shape_mesh_index = p_gltf_shape->get_mesh_index();287if (shape_mesh_index == -1) {288return; // No mesh for this shape.289}290Ref<ImporterMesh> importer_mesh = p_gltf_shape->get_importer_mesh();291if (importer_mesh.is_valid()) {292return; // The mesh resource is already set up.293}294TypedArray<GLTFMesh> state_meshes = p_state->get_meshes();295ERR_FAIL_INDEX_MSG(shape_mesh_index, state_meshes.size(), "glTF Physics: When importing '" + p_state->get_scene_name() + "', the shape mesh index " + itos(shape_mesh_index) + " is not in the state meshes (size: " + itos(state_meshes.size()) + ").");296Ref<GLTFMesh> gltf_mesh = state_meshes[shape_mesh_index];297ERR_FAIL_COND(gltf_mesh.is_null());298importer_mesh = gltf_mesh->get_mesh();299ERR_FAIL_COND(importer_mesh.is_null());300p_gltf_shape->set_importer_mesh(importer_mesh);301}302303#ifndef DISABLE_DEPRECATED304CollisionObject3D *_generate_shape_with_body(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Ref<GLTFPhysicsShape> p_physics_shape, Ref<GLTFPhysicsBody> p_physics_body) {305print_verbose("glTF: Creating shape with body for: " + p_gltf_node->get_name());306bool is_trigger = p_physics_shape->get_is_trigger();307// This method is used for the case where we must generate a parent body.308// This is can happen for multiple reasons. One possibility is that this309// glTF file is using OMI_collider but not OMI_physics_body, or at least310// this particular node is not using it. Another possibility is that the311// physics body information is set up on the same glTF node, not a parent.312CollisionObject3D *body;313if (p_physics_body.is_valid()) {314// This code is run when the physics body is on the same glTF node.315body = p_physics_body->to_node();316if (is_trigger && (p_physics_body->get_body_type() != "trigger")) {317// Edge case: If the body's trigger and the collider's trigger318// are in disagreement, we need to create another new body.319CollisionObject3D *child = _generate_shape_with_body(p_state, p_gltf_node, p_physics_shape, nullptr);320child->set_name(p_gltf_node->get_name() + (is_trigger ? String("Trigger") : String("Solid")));321body->add_child(child);322return body;323}324} else if (is_trigger) {325body = memnew(Area3D);326} else {327body = memnew(StaticBody3D);328}329CollisionShape3D *shape = p_physics_shape->to_node();330shape->set_name(p_gltf_node->get_name() + "Shape");331body->add_child(shape);332return body;333}334#endif // DISABLE_DEPRECATED335336CollisionObject3D *_get_ancestor_collision_object(Node *p_scene_parent) {337// Note: Despite the name of the method, at the moment this only checks338// the direct parent. Only check more later if Godot adds support for it.339if (p_scene_parent) {340CollisionObject3D *co = Object::cast_to<CollisionObject3D>(p_scene_parent);341if (likely(co)) {342return co;343}344}345return nullptr;346}347348Node3D *_generate_shape_node_and_body_if_needed(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Ref<GLTFPhysicsShape> p_physics_shape, CollisionObject3D *p_col_object, bool p_is_trigger) {349// If we need to generate a body node, do so.350CollisionObject3D *body_node = nullptr;351if (p_is_trigger || p_physics_shape->get_is_trigger()) {352// If the shape wants to be a trigger but it doesn't353// have an Area3D parent, we need to make one.354if (!Object::cast_to<Area3D>(p_col_object)) {355body_node = memnew(Area3D);356}357} else {358if (!Object::cast_to<PhysicsBody3D>(p_col_object)) {359body_node = memnew(StaticBody3D);360}361}362// Generate the shape node.363_setup_shape_mesh_resource_from_index_if_needed(p_state, p_physics_shape);364CollisionShape3D *shape_node = p_physics_shape->to_node(true);365if (body_node) {366shape_node->set_name(p_gltf_node->get_name() + "Shape");367body_node->add_child(shape_node);368return body_node;369}370return shape_node;371}372373// Either add the child to the parent, or return the child if there is no parent.374Node3D *_add_physics_node_to_given_node(Node3D *p_current_node, Node3D *p_child, Ref<GLTFNode> p_gltf_node) {375if (!p_current_node) {376return p_child;377}378String suffix;379if (Object::cast_to<CollisionShape3D>(p_child)) {380suffix = "Shape";381} else if (Object::cast_to<Area3D>(p_child)) {382suffix = "Trigger";383} else {384suffix = "Collider";385}386p_child->set_name(p_gltf_node->get_name() + suffix);387p_current_node->add_child(p_child);388return p_current_node;389}390391Array _get_ancestor_compound_trigger_nodes(Ref<GLTFState> p_state, TypedArray<GLTFNode> p_state_nodes, CollisionObject3D *p_ancestor_col_obj) {392GLTFNodeIndex ancestor_index = p_state->get_node_index(p_ancestor_col_obj);393ERR_FAIL_INDEX_V(ancestor_index, p_state_nodes.size(), Array());394Ref<GLTFNode> ancestor_gltf_node = p_state_nodes[ancestor_index];395Variant compound_trigger_nodes = ancestor_gltf_node->get_additional_data(StringName("GLTFPhysicsCompoundTriggerNodes"));396if (compound_trigger_nodes.is_array()) {397return compound_trigger_nodes;398}399Array ret;400ancestor_gltf_node->set_additional_data(StringName("GLTFPhysicsCompoundTriggerNodes"), ret);401return ret;402}403404Node3D *GLTFDocumentExtensionPhysics::generate_scene_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Node *p_scene_parent) {405Ref<GLTFPhysicsBody> gltf_physics_body = p_gltf_node->get_additional_data(StringName("GLTFPhysicsBody"));406#ifndef DISABLE_DEPRECATED407// This deprecated code handles OMI_collider (which we internally name "GLTFPhysicsShape").408Ref<GLTFPhysicsShape> gltf_physics_shape = p_gltf_node->get_additional_data(StringName("GLTFPhysicsShape"));409if (gltf_physics_shape.is_valid()) {410_setup_shape_mesh_resource_from_index_if_needed(p_state, gltf_physics_shape);411// If this glTF node specifies both a shape and a body, generate both.412if (gltf_physics_body.is_valid()) {413return _generate_shape_with_body(p_state, p_gltf_node, gltf_physics_shape, gltf_physics_body);414}415CollisionObject3D *ancestor_col_obj = _get_ancestor_collision_object(p_scene_parent);416if (gltf_physics_shape->get_is_trigger()) {417// If the shape wants to be a trigger and it already has a418// trigger parent, we only need to make the shape node.419if (Object::cast_to<Area3D>(ancestor_col_obj)) {420return gltf_physics_shape->to_node(true);421}422} else if (ancestor_col_obj != nullptr) {423// If the shape has a valid parent, only make the shape node.424return gltf_physics_shape->to_node(true);425}426// Otherwise, we need to create a new body.427return _generate_shape_with_body(p_state, p_gltf_node, gltf_physics_shape, nullptr);428}429#endif // DISABLE_DEPRECATED430Node3D *ret = nullptr;431CollisionObject3D *ancestor_col_obj = nullptr;432Ref<GLTFPhysicsShape> gltf_physics_collider_shape = p_gltf_node->get_additional_data(StringName("GLTFPhysicsColliderShape"));433Ref<GLTFPhysicsShape> gltf_physics_trigger_shape = p_gltf_node->get_additional_data(StringName("GLTFPhysicsTriggerShape"));434if (gltf_physics_body.is_valid()) {435ancestor_col_obj = gltf_physics_body->to_node();436ret = ancestor_col_obj;437} else {438ancestor_col_obj = _get_ancestor_collision_object(p_scene_parent);439if (Object::cast_to<Area3D>(ancestor_col_obj) && gltf_physics_trigger_shape.is_valid()) {440// At this point, we found an ancestor Area3D node. But do we want to use it for this trigger shape?441TypedArray<GLTFNode> state_nodes = p_state->get_nodes();442GLTFNodeIndex self_index = state_nodes.find(p_gltf_node);443Array compound_trigger_nodes = _get_ancestor_compound_trigger_nodes(p_state, state_nodes, ancestor_col_obj);444// Check if the ancestor specifies compound trigger nodes, and if this node is in there.445// Remember that JSON does not have integers, only "number", aka double-precision floats.446if (compound_trigger_nodes.size() > 0 && !compound_trigger_nodes.has(double(self_index))) {447// If the compound trigger we found is not the intended user of448// this shape node, then we need to create a new Area3D node.449ancestor_col_obj = memnew(Area3D);450ret = ancestor_col_obj;451}452} else if (!Object::cast_to<PhysicsBody3D>(ancestor_col_obj)) {453if (p_gltf_node->get_additional_data(StringName("GLTFPhysicsCompoundCollider"))) {454// If the glTF file wants this node to group solid shapes together,455// and there is no parent body, we need to create a static body.456ancestor_col_obj = memnew(StaticBody3D);457ret = ancestor_col_obj;458}459}460}461// Add the shapes to the tree. When an ancestor body is present, use it.462// If an explicit body was specified, it has already been generated and463// set above. If there is no ancestor body, we will either generate an464// Area3D or StaticBody3D implicitly, so prefer an Area3D as the base465// node for best compatibility with signal connections to this node.466bool is_ancestor_col_obj_solid = Object::cast_to<PhysicsBody3D>(ancestor_col_obj);467if (is_ancestor_col_obj_solid && gltf_physics_collider_shape.is_valid()) {468Node3D *child = _generate_shape_node_and_body_if_needed(p_state, p_gltf_node, gltf_physics_collider_shape, ancestor_col_obj, false);469ret = _add_physics_node_to_given_node(ret, child, p_gltf_node);470}471if (gltf_physics_trigger_shape.is_valid()) {472Node3D *child = _generate_shape_node_and_body_if_needed(p_state, p_gltf_node, gltf_physics_trigger_shape, ancestor_col_obj, true);473ret = _add_physics_node_to_given_node(ret, child, p_gltf_node);474}475if (!is_ancestor_col_obj_solid && gltf_physics_collider_shape.is_valid()) {476Node3D *child = _generate_shape_node_and_body_if_needed(p_state, p_gltf_node, gltf_physics_collider_shape, ancestor_col_obj, false);477ret = _add_physics_node_to_given_node(ret, child, p_gltf_node);478}479return ret;480}481482// Export process.483bool _are_all_faces_equal(const Vector<Face3> &p_a, const Vector<Face3> &p_b) {484if (p_a.size() != p_b.size()) {485return false;486}487for (int i = 0; i < p_a.size(); i++) {488const Vector3 *a_vertices = p_a[i].vertex;489const Vector3 *b_vertices = p_b[i].vertex;490for (int j = 0; j < 3; j++) {491if (!a_vertices[j].is_equal_approx(b_vertices[j])) {492return false;493}494}495}496return true;497}498499GLTFMeshIndex _get_or_insert_mesh_in_state(Ref<GLTFState> p_state, Ref<ImporterMesh> p_mesh) {500ERR_FAIL_COND_V(p_mesh.is_null(), -1);501TypedArray<GLTFMesh> state_meshes = p_state->get_meshes();502Vector<Face3> mesh_faces = p_mesh->get_faces();503// De-duplication: If the state already has the mesh we need, use that one.504for (GLTFMeshIndex i = 0; i < state_meshes.size(); i++) {505Ref<GLTFMesh> state_gltf_mesh = state_meshes[i];506ERR_CONTINUE(state_gltf_mesh.is_null());507Ref<ImporterMesh> state_importer_mesh = state_gltf_mesh->get_mesh();508ERR_CONTINUE(state_importer_mesh.is_null());509if (state_importer_mesh == p_mesh) {510return i;511}512if (_are_all_faces_equal(state_importer_mesh->get_faces(), mesh_faces)) {513return i;514}515}516// After the loop, we have checked that the mesh is not equal to any of the517// meshes in the state. So we insert a new mesh into the state mesh array.518Ref<GLTFMesh> gltf_mesh;519gltf_mesh.instantiate();520gltf_mesh->set_mesh(p_mesh);521GLTFMeshIndex mesh_index = state_meshes.size();522state_meshes.push_back(gltf_mesh);523p_state->set_meshes(state_meshes);524return mesh_index;525}526527void GLTFDocumentExtensionPhysics::convert_scene_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Node *p_scene_node) {528if (cast_to<CollisionShape3D>(p_scene_node)) {529CollisionShape3D *godot_shape = Object::cast_to<CollisionShape3D>(p_scene_node);530Ref<GLTFPhysicsShape> gltf_shape = GLTFPhysicsShape::from_node(godot_shape);531ERR_FAIL_COND_MSG(gltf_shape.is_null(), "glTF Physics: Could not convert CollisionShape3D to GLTFPhysicsShape. Does it have a valid Shape3D?");532{533Ref<ImporterMesh> importer_mesh = gltf_shape->get_importer_mesh();534if (importer_mesh.is_valid()) {535gltf_shape->set_mesh_index(_get_or_insert_mesh_in_state(p_state, importer_mesh));536}537}538CollisionObject3D *ancestor_col_obj = _get_ancestor_collision_object(p_scene_node->get_parent());539if (cast_to<Area3D>(ancestor_col_obj)) {540p_gltf_node->set_additional_data(StringName("GLTFPhysicsTriggerShape"), gltf_shape);541// Write explicit member shape nodes to the ancestor compound trigger node.542TypedArray<GLTFNode> state_nodes = p_state->get_nodes();543GLTFNodeIndex self_index = state_nodes.size(); // The current p_gltf_node will be inserted next.544Array compound_trigger_nodes = _get_ancestor_compound_trigger_nodes(p_state, p_state->get_nodes(), ancestor_col_obj);545compound_trigger_nodes.push_back(double(self_index));546} else {547p_gltf_node->set_additional_data(StringName("GLTFPhysicsColliderShape"), gltf_shape);548}549} else if (cast_to<CollisionObject3D>(p_scene_node)) {550CollisionObject3D *godot_body = Object::cast_to<CollisionObject3D>(p_scene_node);551p_gltf_node->set_additional_data(StringName("GLTFPhysicsBody"), GLTFPhysicsBody::from_node(godot_body));552}553}554555Array _get_or_create_state_shapes_in_state(Ref<GLTFState> p_state) {556Dictionary state_json = p_state->get_json();557Dictionary state_extensions;558if (state_json.has("extensions")) {559state_extensions = state_json["extensions"];560} else {561state_json["extensions"] = state_extensions;562}563Dictionary omi_physics_shape_ext;564if (state_extensions.has("OMI_physics_shape")) {565omi_physics_shape_ext = state_extensions["OMI_physics_shape"];566} else {567state_extensions["OMI_physics_shape"] = omi_physics_shape_ext;568p_state->add_used_extension("OMI_physics_shape");569}570Array state_shapes;571if (omi_physics_shape_ext.has("shapes")) {572state_shapes = omi_physics_shape_ext["shapes"];573} else {574omi_physics_shape_ext["shapes"] = state_shapes;575}576return state_shapes;577}578579GLTFShapeIndex _export_node_shape(Ref<GLTFState> p_state, Ref<GLTFPhysicsShape> p_physics_shape) {580Array state_shapes = _get_or_create_state_shapes_in_state(p_state);581GLTFShapeIndex size = state_shapes.size();582Dictionary shape_property;583Dictionary shape_dict = p_physics_shape->to_dictionary();584for (GLTFShapeIndex i = 0; i < size; i++) {585Dictionary other = state_shapes[i];586if (other == shape_dict) {587// De-duplication: If we already have an identical shape,588// set the shape index to the existing one and return.589return i;590}591}592// If we don't have an identical shape, add it to the array.593state_shapes.push_back(shape_dict);594return size;595}596597Error GLTFDocumentExtensionPhysics::export_preserialize(Ref<GLTFState> p_state) {598// Note: Need to do _export_node_shape before exporting animations, so export_node is too late.599TypedArray<GLTFNode> state_gltf_nodes = p_state->get_nodes();600for (Ref<GLTFNode> gltf_node : state_gltf_nodes) {601Ref<GLTFPhysicsShape> collider_shape = gltf_node->get_additional_data(StringName("GLTFPhysicsColliderShape"));602if (collider_shape.is_valid()) {603GLTFShapeIndex collider_shape_index = _export_node_shape(p_state, collider_shape);604gltf_node->set_additional_data(StringName("GLTFPhysicsColliderShapeIndex"), collider_shape_index);605}606Ref<GLTFPhysicsShape> trigger_shape = gltf_node->get_additional_data(StringName("GLTFPhysicsTriggerShape"));607if (trigger_shape.is_valid()) {608GLTFShapeIndex trigger_shape_index = _export_node_shape(p_state, trigger_shape);609gltf_node->set_additional_data(StringName("GLTFPhysicsTriggerShapeIndex"), trigger_shape_index);610}611}612return OK;613}614615Ref<GLTFObjectModelProperty> GLTFDocumentExtensionPhysics::export_object_model_property(Ref<GLTFState> p_state, const NodePath &p_node_path, const Node *p_godot_node, GLTFNodeIndex p_gltf_node_index, const Object *p_target_object, int p_target_depth) {616Ref<GLTFObjectModelProperty> ret;617const Vector<StringName> &path_subnames = p_node_path.get_subnames();618if (path_subnames.is_empty()) {619return ret;620}621ret.instantiate();622const StringName &node_prop = path_subnames[0];623if (Object::cast_to<RigidBody3D>(p_target_object)) {624if (path_subnames.size() != 1) {625return ret;626}627// Example: `/nodes/0/extensions/OMI_physics_body/motion/mass`628PackedStringArray split_json_pointer;629split_json_pointer.append("nodes");630split_json_pointer.append(itos(p_gltf_node_index));631split_json_pointer.append("extensions");632split_json_pointer.append("OMI_physics_body");633split_json_pointer.append("motion");634if (node_prop == StringName("mass")) {635split_json_pointer.append("mass");636ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);637} else if (node_prop == StringName("linear_velocity")) {638split_json_pointer.append("linearVelocity");639ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);640} else if (node_prop == StringName("angular_velocity")) {641split_json_pointer.append("angularVelocity");642ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);643} else if (node_prop == StringName("center_of_mass")) {644split_json_pointer.append("centerOfMass");645ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);646} else if (node_prop == StringName("inertia")) {647split_json_pointer.append("inertiaDiagonal");648ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);649} else {650// Not something we handle, return without setting the JSON pointer.651return ret;652}653ret->set_json_pointers({ split_json_pointer });654} else if (Object::cast_to<CollisionShape3D>(p_godot_node)) {655if (path_subnames.size() != 2) {656return ret;657}658// Example: `/extensions/OMI_physics_shape/shapes/0/box/size`659PackedStringArray split_json_pointer;660split_json_pointer.append("extensions");661split_json_pointer.append("OMI_physics_shape");662split_json_pointer.append("shapes");663TypedArray<GLTFNode> state_gltf_nodes = p_state->get_nodes();664ERR_FAIL_INDEX_V(p_gltf_node_index, state_gltf_nodes.size(), ret);665Ref<GLTFNode> gltf_node = state_gltf_nodes[p_gltf_node_index];666Variant shape_index_maybe = gltf_node->get_additional_data(StringName("GLTFPhysicsColliderShapeIndex"));667String shape_type;668if (shape_index_maybe.get_type() == Variant::INT) {669Ref<GLTFPhysicsShape> collider_shape = gltf_node->get_additional_data(StringName("GLTFPhysicsColliderShape"));670shape_type = collider_shape->get_shape_type();671} else {672shape_index_maybe = gltf_node->get_additional_data(StringName("GLTFPhysicsTriggerShapeIndex"));673if (shape_index_maybe.get_type() == Variant::INT) {674Ref<GLTFPhysicsShape> trigger_shape = gltf_node->get_additional_data(StringName("GLTFPhysicsTriggerShape"));675shape_type = trigger_shape->get_shape_type();676}677}678ERR_FAIL_COND_V(shape_index_maybe.get_type() != Variant::INT, ret);679GLTFShapeIndex shape_index = shape_index_maybe;680split_json_pointer.append(itos(shape_index));681split_json_pointer.append(shape_type);682const StringName &shape_prop = path_subnames[1];683if (shape_prop == StringName("size")) {684split_json_pointer.append("size");685ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);686} else if (shape_prop == StringName("radius")) {687split_json_pointer.append("radius");688ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);689} else if (shape_prop == StringName("height")) {690split_json_pointer.append("height");691ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);692} else {693// Not something we handle, return without setting the JSON pointer.694return ret;695}696ret->set_json_pointers({ split_json_pointer });697}698return ret;699}700701Error GLTFDocumentExtensionPhysics::export_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_node_json, Node *p_node) {702Dictionary physics_body_ext;703Ref<GLTFPhysicsBody> physics_body = p_gltf_node->get_additional_data(StringName("GLTFPhysicsBody"));704if (physics_body.is_valid()) {705physics_body_ext = physics_body->to_dictionary();706Variant compound_trigger_nodes = p_gltf_node->get_additional_data(StringName("GLTFPhysicsCompoundTriggerNodes"));707if (compound_trigger_nodes.is_array()) {708Dictionary trigger_property = physics_body_ext.get_or_add("trigger", {});709trigger_property["nodes"] = compound_trigger_nodes;710}711}712Variant collider_shape_index = p_gltf_node->get_additional_data(StringName("GLTFPhysicsColliderShapeIndex"));713if (collider_shape_index.get_type() == Variant::INT) {714Dictionary collider_dict;715collider_dict["shape"] = collider_shape_index;716physics_body_ext["collider"] = collider_dict;717}718Variant trigger_shape_index = p_gltf_node->get_additional_data(StringName("GLTFPhysicsTriggerShapeIndex"));719if (trigger_shape_index.get_type() == Variant::INT) {720Dictionary trigger_dict = physics_body_ext.get_or_add("trigger", {});721trigger_dict["shape"] = trigger_shape_index;722}723if (!physics_body_ext.is_empty()) {724Dictionary node_extensions = r_node_json["extensions"];725node_extensions["OMI_physics_body"] = physics_body_ext;726p_state->add_used_extension("OMI_physics_body");727}728return OK;729}730731732