16 Commits
Author SHA1 Message Date
ActualHorse a2c0d299d4 draw_debug_polygons() now handles parenting the line mesh all on its own. 2026-09-13 00:52:11 -04:00
ActualHorse bd78ca9046 PlayerSpawn now *actually* uses the new print macros. 2026-09-13 00:50:54 -04:00
ActualHorse 36c7f87dc0 - Hurtboxes now create their own collision shape nodes automatically.
- Character3D prevent crashes on _ready by checking for a valid skeleton.
- Fixed deadzone reading as cleared for all axes when only one has done so.
- Singletons once again deregistered, since it seems to now cause less crashes.
- PlayerSpawn now uses the new error-printing macro.
2026-09-13 00:02:40 -04:00
ActualHorse ef761713b7 - Mesh slicing now works properly when a cut crosses through multiple surfaces.
- Added a debug feature to show polygon lines that can't form a closed shape.
2026-09-12 23:55:22 -04:00
ActualHorse 004c845af7 - Increased minimum version to 4.3 for compatibility with physics bones.
- Added an interface for nodes that can be damaged.
- Character3D implements the above interface to make itself sliceable.
- Added a hurtbox base class.
- MeshEditingLibrary::slice_mesh now uses Godot references when possible.
- Removed semicolon from print macros to enforce placing them in code.
2026-09-07 13:49:13 -04:00
ActualHorse c91a539a26 Number of mouse inputs is now tracked, and mouse mode is changed more reliably. 2026-09-03 11:24:38 -04:00
ActualHorse 1e43a2433c - Inputs no longer fire continuously when the axis is in a resting position.
- Fixed an error that caused a signal that doesn't exist to disconnect.
2026-08-29 15:52:58 -04:00
ActualHorse ad7281a47a - Added Character3D as a C++ class.
- PlayerOrigin now loads a preview of the player scene in the editor.
- LevelScene now executes a signal when a Character3D falls out of the world.
- SublevelScene no longer crashes when the extension is reloaded.
- slice_mesh() now transforms the slice cap normals to match the vertices.
- InputResource now sends mouse axis inputs to a separate callback.
- Added debug log macros.
2026-08-28 15:54:17 -04:00
ActualHorse 431b7c2f8a get_skinned_vertex_positions now returns skin transform array. 2026-08-23 23:26:33 -04:00
ActualHorse 3119b17bd6 - Removed superfluous check for a valid skeleton.
- Fixed getting mesh vertices on meshes with no skeleton.
2026-08-23 22:53:53 -04:00
ActualHorse bbaa3d01d2 - Implemented a much more efficient bone weight calculation.
- Added debug messages for measuring the time each step of a mesh slice takes.
2026-08-23 22:18:47 -04:00
ActualHorse 814299e449 Fixed signal/function name confusion when adding and removing input resources. 2026-08-23 17:48:44 -04:00
ActualHorse 323e55c3fd Signals are no longer double-connected when a resource is added twice. 2026-08-20 01:51:56 -04:00
ActualHorse acdd9f104e - Added a method to retrieve actions and axes from a resource by name.
- InputResources call their signals with default values before disconnecting.
2026-08-19 19:14:07 -04:00
ActualHorse fb0293ac14 Fixed axes mapped to buttons creating an input for each axis value change. 2026-08-17 21:12:57 -04:00
ActualHorse 05a680cc5b Added static functions that allow slicing meshes, including skinned meshes. 2026-08-13 04:11:54 -04:00
26 changed files with 3035 additions and 144 deletions
+2 -1
View File
@@ -24,6 +24,7 @@
*.la *.la
*.a *.a
*.lib *.lib
*.ilk
# Executables # Executables
*.exe *.exe
@@ -34,4 +35,4 @@
# ---> Platform Files # ---> Platform Files
*.sh *.sh
*.*.dblite *.dblite
+1 -1
View File
@@ -1,7 +1,7 @@
[configuration] [configuration]
entry_symbol = "orng_library_init" entry_symbol = "orng_library_init"
compatibility_minimum = "4.2" compatibility_minimum = "4.3"
reloadable = true reloadable = true
[libraries] [libraries]
Binary file not shown.
+7
View File
@@ -1,5 +1,12 @@
env = SConscript("godot-cpp/SConstruct") env = SConscript("godot-cpp/SConstruct")
env.Append(CPPPATH="liborng/") env.Append(CPPPATH="liborng/")
env.Append(CPPPATH="liborng/data_assets")
env.Append(CPPPATH="liborng/nodes/interfaces")
env.Append(CPPPATH="liborng/nodes")
env.Append(CPPPATH="liborng/nodes/character_nodes")
env.Append(CPPPATH="liborng/resources")
env.Append(CPPPATH="liborng/singletons")
env.Append(CPPPATH="liborng/singletons/vendor_service")
src = Glob('liborng/*.cpp') src = Glob('liborng/*.cpp')
src += Glob('liborng/**/*.cpp') src += Glob('liborng/**/*.cpp')
+8
View File
@@ -0,0 +1,8 @@
/*
* ©2023 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "i_damageable.h"
+18
View File
@@ -0,0 +1,18 @@
/*
* ©2023 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include <godot_cpp/variant/dictionary.hpp>
using namespace godot;
class IDamageable
{
public:
virtual void take_damage(const Dictionary &hit_data) = 0;
};
@@ -0,0 +1,86 @@
/*
* ©2023 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "character_3d.h"
#include "orng_macros.h"
#include "nodes/mesh_editing_library.h"
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/physical_bone3d.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
using namespace godot;
void Character3D::_ready()
{
if (this->skeleton)
{
TypedArray<Node> child_mesh_candidates = this->skeleton->get_children();
const uint32_t num_children = child_mesh_candidates.size();
for (uint32_t i = 0; i < num_children; i++)
{
if (MeshInstance3D *mesh = cast_to<MeshInstance3D>(child_mesh_candidates[i]))
{
this->meshes.emplace_back(mesh);
}
}
}
#ifdef DEBUG_ENABLED
else
{
PRINT_ERROR(CHARACTER3D_TAG, "No skeleton has been set, and there is currently no way to seek one out in the hierarchy. This will be a problem.");
}
#endif // DEBUG_ENABLED
}
void Character3D::take_damage(const Dictionary &hit_data)
{
PRINT_LOG(CHARACTER3D_TAG, "Taking damage: ", hit_data["hit_points"]);
PRINT_LOG(CHARACTER3D_TAG, "Hit bones: ", hit_data["bone_hits"]);
const Transform3D &global_hit_transform = (Transform3D)hit_data["hit_transform"];
const Plane &slice_plane = this->skeleton->get_global_transform().inverse().xform(Plane(global_hit_transform.get_basis().get_column(1), global_hit_transform.origin));
const uint32_t num_meshes = this->meshes.size();
for (uint32_t i = 0; i < num_meshes; i++)
{
MeshInstance3D *original_mesh_instance = this->meshes[i];
Ref<ArrayMesh> first_half; first_half.instantiate();
Ref<ArrayMesh> other_half; other_half.instantiate();
PackedVector3Array &impact_points = MeshEditingLibrary::slice_mesh(original_mesh_instance, this->skeleton, slice_plane, first_half, other_half, MeshEditingLibrary::CAP_UV_FILL_MESH_BOUNDS, original_mesh_instance->get_active_material(0));
if (other_half.is_valid())
original_mesh_instance->set_mesh(other_half);
}
}
void Character3D::_activate_ragdoll()
{
if (this->physical_bone_simulator)
{
const TypedArray<Node> &physical_bones = this->physical_bone_simulator->get_children();
const uint32_t num_physical_bones = physical_bones.size();
for (uint32_t i = 0; i < num_physical_bones; i++)
{
if (PhysicalBone3D *bone = cast_to<PhysicalBone3D>(physical_bones[i]))
{
bone->set_collision_layer(0);
}
}
this->physical_bone_simulator->physical_bones_start_simulation();
}
}
void Character3D::_on_fell_out_of_world()
{
this->emit_signal("fell_out_of_world");
}
@@ -0,0 +1,75 @@
/*
* ©2023 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include "orng_macros.h"
#include "interfaces/i_damageable.h"
#include <map>
#include <godot_cpp/classes/animation_tree.hpp>
#include <godot_cpp/classes/character_body3d.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/physical_bone_simulator3d.hpp>
#include <godot_cpp/classes/skeleton3d.hpp>
#include <godot_cpp/variant/dictionary.hpp>
using namespace godot;
#define CHARACTER3D_TAG "Character3D"
class Character3D : public CharacterBody3D, public IDamageable
{
GDCLASS(Character3D, CharacterBody3D);
public:
virtual void _ready() override;
virtual void take_damage(const Dictionary &hit_data) override;
Skeleton3D *get_skeleton() const { return this->skeleton; }
PhysicalBoneSimulator3D *get_physical_bone_simulator() const { return this->physical_bone_simulator; }
AnimationTree *get_animation_tree() const { return this->animation_tree; }
virtual void _on_fell_out_of_world();
protected:
void set_skeleton(Skeleton3D *s) { this->skeleton = s; }
void set_physical_bone_simulator(PhysicalBoneSimulator3D *pbs) { this->physical_bone_simulator = pbs; }
void set_animation_tree(AnimationTree *at) { this->animation_tree = at; }
private:
void _activate_ragdoll();
Skeleton3D *skeleton = nullptr;
PhysicalBoneSimulator3D *physical_bone_simulator = nullptr;
AnimationTree *animation_tree = nullptr;
std::vector<MeshInstance3D*> meshes;
// Godot boilerplate below
protected:
static void _bind_methods()
{
BIND_METHOD(Character3D, _on_fell_out_of_world);
ADD_SIGNAL(MethodInfo("fell_out_of_world"));
ClassDB::bind_method(D_METHOD("get_skeleton"), &Character3D::get_skeleton);
ClassDB::bind_method(D_METHOD("set_skeleton", "skeleton"), &Character3D::set_skeleton);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "skeleton", PROPERTY_HINT_NODE_TYPE, "Skeleton3D"), "set_skeleton", "get_skeleton");
ClassDB::bind_method(D_METHOD("get_physical_bone_simulator"), &Character3D::get_physical_bone_simulator);
ClassDB::bind_method(D_METHOD("set_physical_bone_simulator", "physical_bone_simulator"), &Character3D::set_physical_bone_simulator);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physical_bone_simulator", PROPERTY_HINT_NODE_TYPE, "PhysicalBoneSimulator3D"), "set_physical_bone_simulator", "get_physical_bone_simulator");
ClassDB::bind_method(D_METHOD("get_animation_tree"), &Character3D::get_animation_tree);
ClassDB::bind_method(D_METHOD("set_animation_tree", "animation_tree"), &Character3D::set_animation_tree);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "animation_tree", PROPERTY_HINT_NODE_TYPE, "AnimationTree"), "set_animation_tree", "get_animation_tree");
}
};
File diff suppressed because it is too large Load Diff
+123
View File
@@ -0,0 +1,123 @@
/*
* ©2023 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "hurtbox_base.h"
#include "orng_macros.h"
#include "character_3d.h"
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/physical_bone3d.hpp>
#include <godot_cpp/classes/scene_tree.hpp>
#include <godot_cpp/classes/scene_tree_timer.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
using namespace godot;
void HurtboxBase::_enter_tree()
{
if (!this->collision_shape)
{
this->collision_shape = memnew(CollisionShape3D);
this->collision_shape->set_shape(this->shape);
this->add_child(this->collision_shape);
}
Area3D::_enter_tree();
}
void HurtboxBase::_exit_tree()
{
if (this->collision_shape)
{
this->collision_shape->set_shape(this->shape);
this->remove_child(this->collision_shape);
this->collision_shape->queue_free();
}
Area3D::_exit_tree();
}
void HurtboxBase::_ready()
{
#ifdef DEBUG_ENABLED
if(Engine::get_singleton()->is_editor_hint()) { this->set_physics_process(false); return; }
#endif // DEBUG_ENABLED
this->set_process(false);
this->remaining_life = this->lifetime;
CALL_NEXT_FRAME(callable_mp(this, &HurtboxBase::_send_next_in_queue));
}
void HurtboxBase::_physics_process(double delta)
{
TypedArray<Character3D> characters_hit_this_frame;
const TypedArray<Node3D> &bodies = this->get_overlapping_bodies();
const uint32_t num_bodies = bodies.size();
for (uint32_t i = 0; i < num_bodies; i++)
{
if (Character3D *body = cast_to<Character3D>(bodies[i]))
{
if (!this->hit_character_bodies.has(body))
{
characters_hit_this_frame.append(body);
TypedArray<int32_t> bone_hits;
for (uint32_t bone_index = 0; bone_index < num_bodies; bone_index++)
{
if (PhysicalBone3D *bone = cast_to<PhysicalBone3D>(bodies[bone_index]))
{
if (String(bone->get_path()).begins_with(String(body->get_path())))
{
bone_hits.append(bone->get_bone_id());
PRINT_LOG(HURTBOX_BASE_TAG, "Bone hit: ", bone->get_name(), " (", bone->get_class(), " : ", bone->get_rid(), ")");
}
}
}
PRINT_LOG(HURTBOX_BASE_TAG, "Character hit: ", body->get_name(), " (", body->get_class(), " : ", body->get_rid(), ")");
Dictionary hit_data;
hit_data["body"] = body;
hit_data["bone_hits"] = bone_hits;
hit_data["hit_points"] = this->hit_points;
hit_data["hit_transform"] = this->get_global_transform();
this->hit_data_queue.emplace_back(hit_data);
}
}
}
this->hit_character_bodies.append_array(characters_hit_this_frame);
if (this->remaining_life <= 0.0f)
this->collision_shape->set_disabled(true);
else
this->remaining_life -= delta;
}
void HurtboxBase::_send_next_in_queue()
{
if (!this->hit_data_queue.empty())
{
const Dictionary &hit_data = this->hit_data_queue.front();
Character3D *body = cast_to<Character3D>(hit_data["body"]);
body->take_damage(hit_data);
this->hit_data_queue.erase(this->hit_data_queue.begin());
}
if (this->remaining_life > 0.0f)
{
CALL_NEXT_FRAME(callable_mp(this, &HurtboxBase::_send_next_in_queue));
}
else if (this->hit_data_queue.empty())
{
this->queue_free();
}
}
+69
View File
@@ -0,0 +1,69 @@
/*
* ©2023 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include "orng_macros.h"
#include "character_3d.h"
#include <godot_cpp/classes/collision_shape3d.hpp>
#include <godot_cpp/classes/shape3d.hpp>
#include <godot_cpp/classes/area3d.hpp>
using namespace godot;
#define HURTBOX_BASE_TAG "HurtboxBase"
class HurtboxBase : public Area3D
{
GDCLASS(HurtboxBase, Area3D);
public:
virtual void _enter_tree() override;
virtual void _exit_tree() override;
virtual void _ready() override;
virtual void _physics_process(double delta) override;
void set_shape(Ref<Shape3D> s) { this->shape = s; }
Ref<Shape3D> get_shape() const { return this->shape; }
void set_lifetime(const float lt) { this->lifetime = lt; }
float get_lifetime() const { return this->lifetime; }
void set_hit_points(const int32_t points) { this->hit_points = points; }
int32_t get_hit_points() const { return this->hit_points; }
protected:
std::vector<Dictionary> hit_data_queue;
private:
Dictionary _create_hit_data_struct() const;
void _send_next_in_queue();
Ref<Shape3D> shape = nullptr;
CollisionShape3D *collision_shape = nullptr;
float lifetime = 0.05f;
float remaining_life = 0.0f;
int32_t hit_points = 0;
TypedArray<Character3D> hit_character_bodies;
// Godot boilerplate below
protected:
static void _bind_methods()
{
ADD_GETTER_SETTER_HINTED(HurtboxBase, shape, Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "Shape3D");
ADD_GETTER_SETTER(HurtboxBase, lifetime, Variant::FLOAT);
ADD_GETTER_SETTER(HurtboxBase, hit_points, Variant::INT);
ClassDB::bind_method(D_METHOD("_send_next_in_queue"), &HurtboxBase::_send_next_in_queue);
}
};
+8 -7
View File
@@ -7,6 +7,7 @@
#include "level_scene.h" #include "level_scene.h"
#include "character_3d.h"
#include "nodes/player_spawn.h" #include "nodes/player_spawn.h"
#include "singletons/save_manager.h" #include "singletons/save_manager.h"
@@ -38,11 +39,11 @@ void LevelScene::_scene_ready()
#ifdef DEBUG_ENABLED #ifdef DEBUG_ENABLED
if (!this->game_classes.is_valid()) if (!this->game_classes.is_valid())
{ {
UtilityFunctions::push_error("No GameClasses resource attached to level."); PRINT_ERROR(LEVEL_SCENE_TAG, "No GameClasses resource attached to level.");
return; return;
} }
#endif #endif
this->level_death_plane_node = cast_to<Area3D>(this->get_node_or_null(this->level_death_plane)); this->level_death_plane_node = cast_to<Area3D>(this->get_node_or_null(this->level_death_plane));
if (this->level_death_plane_node) if (this->level_death_plane_node)
{ {
@@ -62,7 +63,7 @@ void LevelScene::_scene_ready()
#ifdef DEBUG_ENABLED #ifdef DEBUG_ENABLED
if (!spawn_point) if (!spawn_point)
{ {
UtilityFunctions::push_error("Could not find a spawn point named ", current_checkpoint, "; defaulting to origin..."); PRINT_ERROR(LEVEL_SCENE_TAG, "Could not find a spawn point named ", current_checkpoint, "; defaulting to origin...");
spawn_point = spawn_points[PLAYER_ORIGIN_TAG]; spawn_point = spawn_points[PLAYER_ORIGIN_TAG];
DEV_ASSERT(spawn_point); DEV_ASSERT(spawn_point);
} }
@@ -97,12 +98,12 @@ void LevelScene::_find_player_spawns_recursive(const Node *node, SpawnPointMap &
void LevelScene::_body_fell_out_of_world(Node3D *body) void LevelScene::_body_fell_out_of_world(Node3D *body)
{ {
if (body->has_method("on_fell_out_of_world")) if (Character3D *character3d = cast_to<Character3D>(body))
{ {
body->call("on_fell_out_of_world"); character3d->emit_signal(FELL_OUT_OF_WORLD_SIGNAL);
} }
else else if (body->has_method(FELL_OUT_OF_WORLD_METHOD))
{ {
body->queue_free(); body->call(FELL_OUT_OF_WORLD_METHOD);
} }
} }
+5
View File
@@ -15,6 +15,11 @@
#include <godot_cpp/classes/resource.hpp> #include <godot_cpp/classes/resource.hpp>
using namespace godot; using namespace godot;
#define LEVEL_SCENE_TAG "LevelScene"
#define FELL_OUT_OF_WORLD_SIGNAL "fell_out_of_world"
#define FELL_OUT_OF_WORLD_METHOD "_on_fell_out_of_world"
typedef std::map<const class StringName, const class PlayerOrigin*> SpawnPointMap; typedef std::map<const class StringName, const class PlayerOrigin*> SpawnPointMap;
+915
View File
@@ -0,0 +1,915 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "mesh_editing_library.h"
#include "orng_macros.h"
#include "earcut.hpp"
#include <map>
#include "godot_cpp/classes/immediate_mesh.hpp"
#include "godot_cpp/classes/time.hpp"
#include "godot_cpp/variant/utility_functions.hpp"
using namespace godot;
MeshEditingLibrary::MeshEditingLibrary()
{
}
MeshEditingLibrary::~MeshEditingLibrary()
{
}
PackedVector3Array MeshEditingLibrary::slice_mesh(MeshInstance3D *original_mesh_instance, const Skeleton3D *original_skeleton, const Plane &local_plane, Ref<ArrayMesh> out_first_half, Ref<ArrayMesh> out_other_half, const MeshEditCapUV cap_option, const Ref<StandardMaterial3D> cap_material)
{
const Time *time = Time::get_singleton();
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Started slicing mesh at ", time->get_ticks_msec(), "ms");
const Mesh *original_mesh = original_mesh_instance->get_mesh().ptr();
const uint8_t num_surfaces = original_mesh->get_surface_count();
std::vector<std::vector<Transform3D>> skinned_vertex_transforms;
const SkinnedSurfaces &skinned_vertex_positions = MeshEditingLibrary::get_skinned_vertex_positions(original_mesh, original_skeleton, skinned_vertex_transforms);
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Got skinned vertices at ", time->get_ticks_msec(), "ms");
PackedVector3Array impact_points;
std::vector<bool> surface_has_normal; surface_has_normal.resize(num_surfaces);
std::vector<bool> surface_has_tangent; surface_has_tangent.resize(num_surfaces);
std::vector<bool> surface_has_uv; surface_has_uv.resize(num_surfaces);
std::vector<bool> surface_has_uv2; surface_has_uv2.resize(num_surfaces);
std::vector<bool> surface_has_colour; surface_has_colour.resize(num_surfaces);
std::vector<bool> surface_has_bone; surface_has_bone.resize(num_surfaces);
std::vector<bool> surface_has_weight; surface_has_weight.resize(num_surfaces);
std::vector<uint32_t> surface_bone_array_size; surface_bone_array_size.resize(num_surfaces);
std::vector<uint8_t> surface_num_bones_per_vertex; surface_num_bones_per_vertex.resize(num_surfaces);
std::vector<PackedVector3Array> first_half_vertices; first_half_vertices.resize(num_surfaces);
std::vector<PackedVector3Array> first_half_normals; first_half_normals.resize(num_surfaces);
std::vector<PackedFloat32Array> first_half_tangents; first_half_tangents.resize(num_surfaces);
std::vector<PackedVector2Array> first_half_uvs; first_half_uvs.resize(num_surfaces);
std::vector<PackedVector2Array> first_half_uv2s; first_half_uv2s.resize(num_surfaces);
std::vector<PackedColorArray> first_half_colours; first_half_colours.resize(num_surfaces);
std::vector<PackedInt32Array> first_half_bones; first_half_bones.resize(num_surfaces);
std::vector<PackedFloat32Array> first_half_weights; first_half_weights.resize(num_surfaces);
std::vector<PackedVector3Array> other_half_vertices; other_half_vertices.resize(num_surfaces);
std::vector<PackedVector3Array> other_half_normals; other_half_normals.resize(num_surfaces);
std::vector<PackedFloat32Array> other_half_tangents; other_half_tangents.resize(num_surfaces);
std::vector<PackedVector2Array> other_half_uvs; other_half_uvs.resize(num_surfaces);
std::vector<PackedVector2Array> other_half_uv2s; other_half_uv2s.resize(num_surfaces);
std::vector<PackedColorArray> other_half_colours; other_half_colours.resize(num_surfaces);
std::vector<PackedInt32Array> other_half_bones; other_half_bones.resize(num_surfaces);
std::vector<PackedFloat32Array> other_half_weights; other_half_weights.resize(num_surfaces);
std::vector<PackedInt32Array> first_half_indices; first_half_indices.resize(num_surfaces);
std::vector<PackedInt32Array> other_half_indices; other_half_indices.resize(num_surfaces);
PackedVector3Array cap_section_vertices;
PackedVector3Array cap_section_normals;
PackedVector3Array cap_section_flipped_normals;
PackedFloat32Array cap_section_tangents;
PackedFloat32Array cap_section_flipped_tangents;
PackedVector2Array cap_section_uvs;
PackedVector2Array cap_section_uv2s;
PackedColorArray cap_section_colours;
PackedInt32Array cap_section_bones;
PackedFloat32Array cap_section_weights;
PackedInt32Array cap_section_indices;
std::vector<MeshEditEdge3D> clip_edges;
for (uint8_t surface = 0; surface < num_surfaces; surface++)
{
const SkinnedVertices &surface_skinned_vertex_positions = skinned_vertex_positions[surface];
const Array &surface_arrays = original_mesh->surface_get_arrays(surface);
const PackedVector3Array &surface_vertex_array = surface_arrays[ArrayMesh::ARRAY_VERTEX];
const PackedVector3Array &surface_normal_array = surface_arrays[ArrayMesh::ARRAY_NORMAL];
const PackedFloat32Array &surface_tangent_array = surface_arrays[ArrayMesh::ARRAY_TANGENT];
const PackedVector2Array &surface_uv_array = surface_arrays[ArrayMesh::ARRAY_TEX_UV];
const PackedVector2Array &surface_uv2_array = surface_arrays[ArrayMesh::ARRAY_TEX_UV2];
const PackedColorArray &surface_colour_array = surface_arrays[ArrayMesh::ARRAY_COLOR];
const PackedInt32Array &surface_bone_array = surface_arrays[ArrayMesh::ARRAY_BONES];
const PackedFloat32Array &surface_weight_array = surface_arrays[ArrayMesh::ARRAY_WEIGHTS];
const Vector3 *surface_vertex_array_ptr = surface_vertex_array.ptr();
const uint32_t num_vertices = surface_vertex_array.size();
std::vector<float> vertex_distance;
vertex_distance.resize(num_vertices);
std::map<uint32_t, uint32_t> base_to_sliced_vert_index;
std::map<uint32_t, uint32_t> base_to_other_sliced_vert_index;
const bool has_normal = surface_normal_array.size() >= num_vertices; surface_has_normal[surface] = has_normal;
const bool has_tangent = surface_tangent_array.size() >= num_vertices * 4; surface_has_tangent[surface] = has_tangent;
const bool has_uv = surface_uv_array.size() >= num_vertices; surface_has_uv[surface] = has_uv;
const bool has_uv2 = surface_uv2_array.size() >= num_vertices; surface_has_uv2[surface] = has_uv2;
const bool has_colour = surface_colour_array.size() >= num_vertices; surface_has_colour[surface] = has_colour;
const bool has_bone = surface_bone_array.size() >= num_vertices * 4; surface_has_bone[surface] = has_bone;
const bool has_weight = surface_weight_array.size() >= num_vertices * 4; surface_has_weight[surface] = has_weight;
const uint32_t bone_array_size = surface_bone_array.size();
surface_bone_array_size[surface] = bone_array_size;
const uint8_t num_bones_per_vertex = surface_bone_array_size[surface] / num_vertices;
surface_num_bones_per_vertex[surface] = num_bones_per_vertex;
for (uint32_t vertex = 0; vertex < num_vertices; vertex++)
{
vertex_distance[vertex] = local_plane.distance_to(surface_skinned_vertex_positions[vertex]);
if (vertex_distance[vertex] >= 0.0f)
{
base_to_sliced_vert_index[vertex] = first_half_vertices[surface].size();
first_half_vertices[surface].append(surface_vertex_array_ptr[vertex]);
if (has_normal) { first_half_normals[surface].append(surface_normal_array.ptr()[vertex]); }
if (has_uv) { first_half_uvs[surface].append(surface_uv_array.ptr()[vertex]); }
if (has_uv2) { first_half_uv2s[surface].append(surface_uv2_array.ptr()[vertex]); }
if (has_colour) { first_half_colours[surface].append(surface_colour_array.ptr()[vertex]); }
if (has_tangent)
{
first_half_tangents[surface].append(surface_tangent_array.ptr()[vertex * 4]);
first_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 1]);
first_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 2]);
first_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 3]);
}
if (has_bone)
{
for (uint8_t i = 0; i < num_bones_per_vertex; i++)
{
first_half_bones[surface].append(surface_bone_array.ptr()[(vertex * num_bones_per_vertex) + i]);
first_half_weights[surface].append(surface_weight_array.ptr()[(vertex * num_bones_per_vertex) + i]);
}
}
}
else
{
base_to_other_sliced_vert_index[vertex] = other_half_vertices[surface].size();
other_half_vertices[surface].append(surface_vertex_array_ptr[vertex]);
if (has_normal) { other_half_normals[surface].append(surface_normal_array.ptr()[vertex]); }
if (has_uv) { other_half_uvs[surface].append(surface_uv_array.ptr()[vertex]); }
if (has_uv2) { other_half_uv2s[surface].append(surface_uv2_array.ptr()[vertex]); }
if (has_colour) { other_half_colours[surface].append(surface_colour_array.ptr()[vertex]); }
if (has_tangent)
{
other_half_tangents[surface].append(surface_tangent_array.ptr()[vertex * 4]);
other_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 1]);
other_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 2]);
other_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 3]);
}
if (has_bone)
{
for (uint8_t i = 0; i < num_bones_per_vertex; i++)
{
other_half_bones[surface].append(surface_bone_array.ptr()[(vertex * num_bones_per_vertex) + i]);
other_half_weights[surface].append(surface_weight_array.ptr()[(vertex * num_bones_per_vertex) + i]);
}
}
}
}
const PackedInt32Array &surface_index_array = surface_arrays[ArrayMesh::ARRAY_INDEX];
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Surface ", surface, " sorted by plane distance at ", time->get_ticks_msec(), "ms");
if (!(first_half_vertices[surface].size() > 0 && other_half_vertices[surface].size() > 0))
{
if (first_half_vertices[surface].size() > 0)
{
first_half_indices[surface] = surface_index_array;
}
else if (other_half_vertices[surface].size() > 0)
{
other_half_indices[surface] = surface_index_array;
}
}
else
{
const uint32_t num_triangles = surface_index_array.size();
for (uint32_t triangle_index = 0; triangle_index < num_triangles; triangle_index += 3)
{
uint32_t base_v[3];
std::map<uint32_t, uint32_t>::iterator sliced_v[3];
std::map<uint32_t, uint32_t>::iterator sliced_other_v[3];
const std::map<uint32_t, uint32_t>::iterator base_to_sliced_end = base_to_sliced_vert_index.end();
const std::map<uint32_t, uint32_t>::iterator base_to_other_sliced_end = base_to_other_sliced_vert_index.end();
for (uint32_t i = 0; i < 3; i++)
{
base_v[i] = surface_index_array.ptr()[triangle_index + i];
sliced_v[i] = base_to_sliced_vert_index.find(base_v[i]);
sliced_other_v[i] = base_to_other_sliced_vert_index.find(base_v[i]);
// All vertex indices must be represented by one of the two slice index maps.
assert((sliced_v[i] != base_to_sliced_vert_index.end()) != (sliced_other_v[i] != base_to_other_sliced_vert_index.end()));
}
if (sliced_v[0] != base_to_sliced_end && sliced_v[1] != base_to_sliced_end && sliced_v[2] != base_to_sliced_end)
{ // If the triangle is entirely in the first slice, send all the vertices to the first slice.
first_half_indices[surface].append(sliced_v[0]->second);
first_half_indices[surface].append(sliced_v[1]->second);
first_half_indices[surface].append(sliced_v[2]->second);
}
else if (sliced_other_v[0] != base_to_other_sliced_end && sliced_other_v[1] != base_to_other_sliced_end && sliced_other_v[2] != base_to_other_sliced_end)
{ // If the triangle is entirely in the second slice, send all the vertices to the second slice.
other_half_indices[surface].append(sliced_other_v[0]->second);
other_half_indices[surface].append(sliced_other_v[1]->second);
other_half_indices[surface].append(sliced_other_v[2]->second);
}
else
{ // If the triangle is split by the slice plane, then slice the overlapping edges.
uint32_t final_verts[4] = { 0, 0, 0, 0 };
uint8_t num_final_verts = 0;
uint32_t other_final_verts[4] = { 0, 0, 0, 0 };
uint8_t num_other_final_verts = 0;
MeshEditEdge3D new_clip_edge;
uint8_t clipped_edges = 0;
float plane_distance[3] = {
vertex_distance[base_v[0]],
vertex_distance[base_v[1]],
vertex_distance[base_v[2]]
};
for (uint32_t this_vert = 0; this_vert < 3; this_vert++)
{
if (sliced_v[this_vert] != base_to_sliced_end)
{
final_verts[num_final_verts] = sliced_v[this_vert]->second;
num_final_verts++;
}
else
{
other_final_verts[num_other_final_verts] = sliced_other_v[this_vert]->second;
num_other_final_verts++;
}
uint32_t next_vert = (this_vert + 1) % 3;
if ((sliced_v[this_vert] == base_to_sliced_end) != (sliced_v[next_vert] == base_to_sliced_end))
{
const float alpha = UtilityFunctions::clampf(-plane_distance[this_vert] / (plane_distance[next_vert] - plane_distance[this_vert]), 0.0f, 1.0f);
const Vector3 &interp_vert = surface_vertex_array[base_v[this_vert]].lerp(
surface_vertex_array[base_v[next_vert]], alpha);
final_verts[num_final_verts++] = first_half_vertices[surface].size();
other_final_verts[num_other_final_verts++] = other_half_vertices[surface].size();
const Vector3 &skinned_interp_vert = surface_skinned_vertex_positions[base_v[this_vert]].lerp(
surface_skinned_vertex_positions[base_v[next_vert]], alpha);
MeshEditVert3D edge_vertex;
edge_vertex.surface = surface;
edge_vertex.index = first_half_vertices[surface].size();
edge_vertex.position = skinned_interp_vert;
if (clipped_edges == 0)
{
new_clip_edge.v0 = edge_vertex;
}
else
{
new_clip_edge.v1 = edge_vertex;
}
clipped_edges++;
assert(clipped_edges <= 2);
first_half_vertices[surface].append(interp_vert);
other_half_vertices[surface].append(interp_vert);
if (has_normal)
{
const Vector3 interp_normal = surface_normal_array.ptr()[base_v[this_vert]].slerp(surface_normal_array.ptr()[base_v[next_vert]], alpha);
first_half_normals[surface].append(interp_normal);
other_half_normals[surface].append(interp_normal);
}
if (has_tangent)
{
const float *this_tangent_start = (surface_tangent_array.ptr() + (base_v[this_vert] * 4));
const float *next_tangent_start = (surface_tangent_array.ptr() + (base_v[next_vert] * 4));
const Vector3 &this_tangent = Vector3(*this_tangent_start, *(this_tangent_start + 1), *(this_tangent_start + 2));
const Vector3 &next_tangent = Vector3(*next_tangent_start, *(next_tangent_start + 1), *(next_tangent_start + 2));
const float this_binormal = *(this_tangent_start + 3);
const float next_binormal = *(next_tangent_start + 3);
const Vector3 &interp_tangent = this_tangent.slerp(next_tangent, alpha);
const uint8_t &interp_binormal = UtilityFunctions::roundi(UtilityFunctions::lerpf(this_binormal, next_binormal, alpha));
first_half_tangents[surface].append(interp_tangent.x);
first_half_tangents[surface].append(interp_tangent.y);
first_half_tangents[surface].append(interp_tangent.z);
first_half_tangents[surface].append(interp_binormal);
other_half_tangents[surface].append(interp_tangent.x);
other_half_tangents[surface].append(interp_tangent.y);
other_half_tangents[surface].append(interp_tangent.z);
other_half_tangents[surface].append(interp_binormal);
}
if (has_uv)
{
const Vector2 &interp_uv = surface_uv_array.ptr()[base_v[this_vert]].lerp(surface_uv_array.ptr()[base_v[next_vert]], alpha);
first_half_uvs[surface].append(interp_uv);
other_half_uvs[surface].append(interp_uv);
}
if (has_uv2)
{
const Vector2 &interp_uv2 = surface_uv2_array.ptr()[base_v[this_vert]].lerp(surface_uv2_array.ptr()[base_v[next_vert]], alpha);
first_half_uv2s[surface].append(interp_uv2);
other_half_uv2s[surface].append(interp_uv2);
}
if (has_colour)
{
const Color &interp_colour = surface_colour_array.ptr()[base_v[this_vert]].lerp(surface_colour_array.ptr()[base_v[next_vert]], alpha);
first_half_colours[surface].append(interp_colour);
other_half_colours[surface].append(interp_colour);
}
if (has_bone && has_weight)
{
std::map<int32_t, float> positive_side_bones_and_weights;
float normalisation_value = 0.0f;
// First pack all active bones and weights into a list of pairs
uint8_t vertex_bone = 0;
for (vertex_bone = 0; vertex_bone < num_bones_per_vertex; vertex_bone++)
{
const int32_t bone = surface_bone_array[(base_v[this_vert] * num_bones_per_vertex) + vertex_bone];
const float weight = surface_weight_array[(base_v[this_vert] * num_bones_per_vertex) + vertex_bone];
if (weight > TINY_NUMBER) { positive_side_bones_and_weights[bone] = weight; }
}
// Next, find each second half bone that matches one in the first half, and interpolate between them.
// If the second half has a unique bone, interpolate a new value from 0 for it.
// Delete any matches from the first half, leaving only unique bones to add later.
std::map<int32_t, float> negative_side_bones_and_weights;
std::vector<std::pair<int32_t, float>> bone_weight_pairs;
for (uint32_t other_bone_index = 0; other_bone_index < num_bones_per_vertex; other_bone_index++)
{
const uint32_t other_bone = surface_bone_array[(base_v[next_vert] * num_bones_per_vertex) + other_bone_index];
const float other_weight = surface_weight_array[(base_v[next_vert] * num_bones_per_vertex) + other_bone_index];
if (negative_side_bones_and_weights.find(other_bone) != negative_side_bones_and_weights.end())
{
continue;
}
std::map<int32_t, float>::iterator matching_bone_iterator = positive_side_bones_and_weights.find(other_bone);
if (matching_bone_iterator == positive_side_bones_and_weights.end())
{
const float lerped_weight = (float)UtilityFunctions::lerpf(0.0f, other_weight, alpha);
bone_weight_pairs.emplace_back(other_bone, lerped_weight);
normalisation_value += lerped_weight;
}
else
{
const float lerped_weight = (float)UtilityFunctions::lerpf(matching_bone_iterator->second, other_weight, alpha);
bone_weight_pairs.emplace_back(matching_bone_iterator->first, lerped_weight);
positive_side_bones_and_weights.erase(matching_bone_iterator);
normalisation_value += lerped_weight;
}
negative_side_bones_and_weights[other_bone] = other_weight;
}
// Interpolate all remaining bones in the first half and add them to the pairs list.
for (std::map<int32_t, float>::iterator i = positive_side_bones_and_weights.begin(); i != positive_side_bones_and_weights.end(); i++)
{
const float lerped_weight = (float)UtilityFunctions::lerpf(i->second, 0.0f, alpha);
bone_weight_pairs.emplace_back(i->first, lerped_weight);
normalisation_value += lerped_weight;
}
// Sort the list of bones and weights from highest weight to lowest weight
std::sort(bone_weight_pairs.begin(), bone_weight_pairs.end(),
[=](std::pair<int32_t, float> &a, std::pair<int32_t, float> &b) { return a.second > b.second; });
// Finally, add all our new interpolated bones and weights to the arrays
for (vertex_bone = 0; vertex_bone < num_bones_per_vertex; vertex_bone++)
{
if (vertex_bone < bone_weight_pairs.size())
{
const float normalised_weight = bone_weight_pairs[vertex_bone].second / normalisation_value;
first_half_bones[surface].append(bone_weight_pairs[vertex_bone].first);
first_half_weights[surface].append(normalised_weight);
other_half_bones[surface].append(bone_weight_pairs[vertex_bone].first);
other_half_weights[surface].append(normalised_weight);
}
else
{
first_half_bones[surface].append(0);
first_half_weights[surface].append(0.0f);
other_half_bones[surface].append(0);
other_half_weights[surface].append(0.0f);
}
}
}
}
}
// There should always be exactly two sliced edges per triangle
assert(clipped_edges == 2);
clip_edges.emplace_back(new_clip_edge);
for (uint32_t vertex_index = 2; vertex_index < num_final_verts; vertex_index++)
{
first_half_indices[surface].append(final_verts[0]);
first_half_indices[surface].append(final_verts[vertex_index - 1]);
first_half_indices[surface].append(final_verts[vertex_index]);
}
for (uint32_t vertex_index = 2; vertex_index < num_other_final_verts; vertex_index++)
{
other_half_indices[surface].append(other_final_verts[0]);
other_half_indices[surface].append(other_final_verts[vertex_index - 1]);
other_half_indices[surface].append(other_final_verts[vertex_index]);
}
}
}
}
if (first_half_vertices[surface].size() > 0 && first_half_indices[surface].size() > 0)
{
Array first_half_section;
first_half_section.resize(ArrayMesh::ARRAY_MAX);
first_half_section[ArrayMesh::ARRAY_VERTEX] = first_half_vertices[surface];
if (has_normal) first_half_section[ArrayMesh::ARRAY_NORMAL] = first_half_normals[surface];
if (has_tangent) first_half_section[ArrayMesh::ARRAY_TANGENT] = first_half_tangents[surface];
if (has_uv) first_half_section[ArrayMesh::ARRAY_TEX_UV] = first_half_uvs[surface];
if (has_uv2) first_half_section[ArrayMesh::ARRAY_TEX_UV2] = first_half_uv2s[surface];
if (has_colour) first_half_section[ArrayMesh::ARRAY_COLOR] = first_half_colours[surface];
if (has_bone) first_half_section[ArrayMesh::ARRAY_BONES] = first_half_bones[surface];
if (has_weight) first_half_section[ArrayMesh::ARRAY_WEIGHTS] = first_half_weights[surface];
first_half_section[ArrayMesh::ARRAY_INDEX] = first_half_indices[surface];
out_first_half->add_surface_from_arrays(ArrayMesh::PRIMITIVE_TRIANGLES, first_half_section);
out_first_half->surface_set_material(surface, original_mesh->surface_get_material(surface));
}
if (other_half_vertices[surface].size() > 0 && other_half_indices[surface].size() > 0)
{
Array other_half_section;
other_half_section.resize(ArrayMesh::ARRAY_MAX);
other_half_section[ArrayMesh::ARRAY_VERTEX] = other_half_vertices[surface];
if (has_normal) other_half_section[ArrayMesh::ARRAY_NORMAL] = other_half_normals[surface];
if (has_tangent) other_half_section[ArrayMesh::ARRAY_TANGENT] = other_half_tangents[surface];
if (has_uv) other_half_section[ArrayMesh::ARRAY_TEX_UV] = other_half_uvs[surface];
if (has_uv2) other_half_section[ArrayMesh::ARRAY_TEX_UV2] = other_half_uv2s[surface];
if (has_colour) other_half_section[ArrayMesh::ARRAY_COLOR] = other_half_colours[surface];
if (has_bone) other_half_section[ArrayMesh::ARRAY_BONES] = other_half_bones[surface];
if (has_weight) other_half_section[ArrayMesh::ARRAY_WEIGHTS] = other_half_weights[surface];
other_half_section[ArrayMesh::ARRAY_INDEX] = other_half_indices[surface];
out_other_half->add_surface_from_arrays(ArrayMesh::PRIMITIVE_TRIANGLES, other_half_section);
out_other_half->surface_set_material(surface, original_mesh->surface_get_material(surface));
}
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Surface ", surface, " split edges at ", time->get_ticks_msec(), "ms");
}
if (clip_edges.size() > 0)
{
std::vector<MeshEditEdge2D> edges_2d;
std::vector<MeshEditPolygon2D> polygon_set;
std::vector<MeshEditPolygon2D> error_polygons;
const Transform3D &plane_inverse_transform = MeshEditingLibrary::project_edges(edges_2d, original_mesh_instance->get_transform(), clip_edges, local_plane);
MeshEditingLibrary::build_2d_polygons_from_edges(polygon_set, edges_2d, error_polygons);
MeshEditingLibrary::draw_debug_polygons(original_mesh_instance, error_polygons, plane_inverse_transform, Color(1.0f, 0.0f, 0.0f, 1.0f));
MeshSlicePlaneOrientation uv_plane = MeshSlicePlaneOrientation::Z;
const Basis &mesh_instance_basis = original_mesh_instance->get_basis();
const Vector3 &local_plane_normal = local_plane.get_normal();
if (UtilityFunctions::absf(local_plane_normal.dot(mesh_instance_basis.xform(Vector3(0.0f, 1.0f, 0.0f)))) > 0.5f)
{
uv_plane = MeshSlicePlaneOrientation::Y;
}
else if (UtilityFunctions::absf(local_plane_normal.dot(mesh_instance_basis.xform(Vector3(1.0f, 0.0f, 0.0f)))) > 0.5f)
{
uv_plane = MeshSlicePlaneOrientation::X;
}
const Vector3 &mesh_bounds = original_mesh->get_aabb().get_size();
const uint32_t num_polygons = polygon_set.size();
for (uint32_t polygon_index = 0; polygon_index < num_polygons; polygon_index++)
{
using Point = std::array<float,2>;
using Polygon = std::vector<std::vector<Point>>;
Polygon earcut_polygon;
std::vector<Point> sub_polygon;
Vector3 polygon_centroid;
const uint32_t polygon_vertex_base = cap_section_vertices.size();
for (const MeshEditVert2D &vertex : polygon_set[polygon_index].vertices)
{
const Vector3 &position = first_half_vertices[vertex.surface][vertex.index];
const Vector3 &local_plane_transformed_normal = skinned_vertex_transforms[vertex.surface][vertex.index].xform(local_plane_normal).normalized();
cap_section_vertices.append(position);
if (surface_has_normal[vertex.surface])
{
cap_section_normals.append(local_plane_transformed_normal);
cap_section_flipped_normals.append(local_plane_transformed_normal * -1.0f);
}
if (surface_has_colour[vertex.surface]) { cap_section_colours.append(first_half_colours[vertex.surface][vertex.index]); }
if (surface_has_uv[vertex.surface]) { cap_section_uvs.append(MeshEditingLibrary::calculate_planar_uv(position, mesh_bounds, uv_plane)); }
if (surface_has_uv2[vertex.surface]) { cap_section_uv2s.append(first_half_uv2s[vertex.surface][vertex.index]); }
if (surface_has_tangent[vertex.surface])
{
for (uint8_t i = 0; i < 4; i++)
{
cap_section_tangents.append(first_half_tangents[vertex.surface][(vertex.index * 4) + i] * -1.0f);
cap_section_flipped_tangents.append(first_half_tangents[vertex.surface][(vertex.index * 4) + i]);
}
}
if (surface_has_bone[vertex.surface])
{
for (uint8_t i = 0; i < surface_num_bones_per_vertex[vertex.surface]; i++)
{
cap_section_bones.append(first_half_bones[vertex.surface][(vertex.index * surface_num_bones_per_vertex[vertex.surface]) + i]);
}
}
if (surface_has_weight[vertex.surface])
{
for (uint8_t i = 0; i < surface_num_bones_per_vertex[vertex.surface]; i++)
{
cap_section_weights.append(first_half_weights[vertex.surface][(vertex.index * surface_num_bones_per_vertex[vertex.surface]) + i]);
}
}
sub_polygon.push_back({vertex.position.x, vertex.position.y});
polygon_centroid += position;
}
polygon_centroid /= polygon_set[polygon_index].vertices.size();
impact_points.append(polygon_centroid);
earcut_polygon.push_back(sub_polygon);
std::vector<uint32_t> indices = mapbox::earcut<uint32_t>(earcut_polygon);
for (uint32_t i = 0; (i+2) < indices.size(); i += 3)
{
cap_section_indices.append(indices[i+1] + polygon_vertex_base);
cap_section_indices.append(indices[i] + polygon_vertex_base);
cap_section_indices.append(indices[i+2] + polygon_vertex_base);
}
}
}
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Created cap surfaces at ", time->get_ticks_msec(), "ms");
if (cap_section_vertices.size() > 0 && cap_section_indices.size() > 0)
{
Array cap_mesh_section;
cap_mesh_section.resize(ArrayMesh::ARRAY_MAX);
cap_mesh_section[ArrayMesh::ARRAY_VERTEX] = cap_section_vertices;
cap_mesh_section[ArrayMesh::ARRAY_INDEX] = cap_section_indices;
if (cap_section_normals.size()) cap_mesh_section[ArrayMesh::ARRAY_NORMAL] = cap_section_normals;
// if (cap_section_tangents.size()) cap_mesh_section[ArrayMesh::ARRAY_TANGENT] = cap_section_tangents;
if (cap_section_colours.size()) cap_mesh_section[ArrayMesh::ARRAY_COLOR] = cap_section_colours;
if (cap_section_uvs.size()) cap_mesh_section[ArrayMesh::ARRAY_TEX_UV] = cap_section_uvs;
if (cap_section_uv2s.size()) cap_mesh_section[ArrayMesh::ARRAY_TEX_UV2] = cap_section_uv2s;
if (cap_section_bones.size()) cap_mesh_section[ArrayMesh::ARRAY_BONES] = cap_section_bones;
if (cap_section_weights.size()) cap_mesh_section[ArrayMesh::ARRAY_WEIGHTS] = cap_section_weights;
out_first_half->add_surface_from_arrays(ArrayMesh::PRIMITIVE_TRIANGLES, cap_mesh_section);
out_first_half->surface_set_material(out_first_half->get_surface_count()-1, cap_material);
const uint32_t num_cap_triangles = cap_section_indices.size();
for (uint32_t i = 0; i < num_cap_triangles; i += 3)
{
const int32_t old_index = cap_section_indices[i];
cap_section_indices[i] = cap_section_indices[i+1];
cap_section_indices[i+1] = old_index;
}
Array cap_other_mesh_section;
cap_other_mesh_section.resize(ArrayMesh::ARRAY_MAX);
cap_other_mesh_section[ArrayMesh::ARRAY_VERTEX] = cap_section_vertices;
cap_other_mesh_section[ArrayMesh::ARRAY_INDEX] = cap_section_indices;
if (cap_section_normals.size()) cap_other_mesh_section[ArrayMesh::ARRAY_NORMAL] = cap_section_flipped_normals;
// if (cap_section_tangents.size()) cap_other_mesh_section[ArrayMesh::ARRAY_TANGENT] = cap_section_flipped_tangents;
if (cap_section_colours.size()) cap_other_mesh_section[ArrayMesh::ARRAY_COLOR] = cap_section_colours;
if (cap_section_uvs.size()) cap_other_mesh_section[ArrayMesh::ARRAY_TEX_UV] = cap_section_uvs;
if (cap_section_uv2s.size()) cap_other_mesh_section[ArrayMesh::ARRAY_TEX_UV2] = cap_section_uv2s;
if (cap_section_bones.size()) cap_other_mesh_section[ArrayMesh::ARRAY_BONES] = cap_section_bones;
if (cap_section_weights.size()) cap_other_mesh_section[ArrayMesh::ARRAY_WEIGHTS] = cap_section_weights;
out_other_half->add_surface_from_arrays(ArrayMesh::PRIMITIVE_TRIANGLES, cap_other_mesh_section);
out_other_half->surface_set_material(out_other_half->get_surface_count()-1, cap_material);
}
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Generated final cap surface at ", time->get_ticks_msec(), "ms");
return impact_points;
}
SkinnedSurfaces MeshEditingLibrary::get_skinned_vertex_positions(const Mesh *mesh, const Skeleton3D *skeleton, std::vector<std::vector<Transform3D>> &vertex_transforms)
{
const uint8_t num_surfaces = mesh->get_surface_count();
SkinnedSurfaces skinned_vertex_surfaces;
skinned_vertex_surfaces.resize(num_surfaces);
if (skeleton)
{
const uint16_t bone_count = skeleton->get_bone_count();
std::vector<Transform3D> bone_transforms;
bone_transforms.resize(bone_count);
for (uint8_t bone_index = 0; bone_index < bone_count; bone_index++)
{
bone_transforms[bone_index] = skeleton->get_bone_global_pose(bone_index) * skeleton->get_bone_global_rest(bone_index).inverse();
}
vertex_transforms.resize(num_surfaces);
for (uint8_t surface = 0; surface < num_surfaces; surface++)
{
const Array &mesh_arrays = mesh->surface_get_arrays(surface);
const PackedVector3Array &mesh_vertex_array = mesh_arrays[ArrayMesh::ARRAY_VERTEX];
const uint32_t mesh_vertex_array_size = mesh_vertex_array.size();
SkinnedVertices skinned_vertex_array;
skinned_vertex_array.resize(mesh_vertex_array_size);
std::vector<Transform3D> skinned_vertex_transforms;
skinned_vertex_transforms.resize(mesh_vertex_array_size);
const PackedInt32Array &mesh_bones_array = mesh_arrays[ArrayMesh::ARRAY_BONES];
const PackedFloat32Array &mesh_weights_array = mesh_arrays[ArrayMesh::ARRAY_WEIGHTS];
const uint8_t num_bones_per_vertex = mesh_bones_array.size() / mesh_vertex_array_size;
for (uint32_t vertex_index = 0; vertex_index < mesh_vertex_array_size; vertex_index++)
{
const Vector3 &vertex = mesh_vertex_array[vertex_index];
Transform3D *transforms = new Transform3D[num_bones_per_vertex];
const uint32_t bone_index_start = (vertex_index * num_bones_per_vertex);
for (uint8_t bone_index_offset = 0; bone_index_offset < num_bones_per_vertex; bone_index_offset++)
{
const float weight = mesh_weights_array[bone_index_start + bone_index_offset];
const uint32_t bone = mesh_bones_array[bone_index_start + bone_index_offset];
transforms[bone_index_offset] = ((Transform3D)bone_transforms[bone]) * weight;
}
Vector3 x_basis, y_basis, z_basis, origin;
for (uint8_t transform = 0; transform < num_bones_per_vertex; transform++)
{
x_basis += transforms[transform].basis.rows[0];
y_basis += transforms[transform].basis.rows[1];
z_basis += transforms[transform].basis.rows[2];
origin += transforms[transform].origin;
}
const Transform3D &final_bone_transform = Transform3D(
x_basis.x, x_basis.y, x_basis.z,
y_basis.x, y_basis.y, y_basis.z,
z_basis.x, z_basis.y, z_basis.z,
origin.x, origin.y, origin.z);
skinned_vertex_transforms[vertex_index] = final_bone_transform;
skinned_vertex_array[vertex_index] = final_bone_transform.xform(vertex);
delete transforms;
}
skinned_vertex_surfaces[surface] = skinned_vertex_array;
vertex_transforms[surface] = skinned_vertex_transforms;
}
return skinned_vertex_surfaces;
}
else
{
for (uint8_t surface = 0; surface < num_surfaces; surface++)
{
const Array &mesh_arrays = mesh->surface_get_arrays(surface);
const PackedVector3Array &mesh_vertex_array = mesh_arrays[ArrayMesh::ARRAY_VERTEX];
const uint32_t mesh_vertex_array_size = mesh_vertex_array.size();
SkinnedVertices skinned_vertex_array;
skinned_vertex_array.resize(mesh_vertex_array_size);
for (uint32_t vertex_index = 0; vertex_index < mesh_vertex_array_size; vertex_index++)
{
skinned_vertex_array[vertex_index] = mesh_vertex_array[vertex_index];
}
skinned_vertex_surfaces[surface] = skinned_vertex_array;
}
return skinned_vertex_surfaces;
}
return SkinnedSurfaces();
}
const Transform3D MeshEditingLibrary::project_edges(std::vector<MeshEditEdge2D> &out_2d_edges, const Transform3D &to_node_space, const std::vector<MeshEditEdge3D> &in_3d_edges, const Plane &plane)
{
out_2d_edges.resize(in_3d_edges.size());
const Transform3D &plane_inverse_transform = Transform3D(Basis::looking_at(plane.get_normal()), plane.center()).inverse();
for (uint32_t i = 0; i < in_3d_edges.size(); i++)
{
MeshEditVert2D v0;
Vector3 p = plane_inverse_transform.xform(in_3d_edges[i].v0.position);
v0.surface = in_3d_edges[i].v0.surface;
v0.index = in_3d_edges[i].v0.index;
v0.position.x = p.x;
v0.position.y = p.y;
MeshEditVert2D v1;
p = plane_inverse_transform.xform(in_3d_edges[i].v1.position);
v1.index = in_3d_edges[i].v1.index;
v1.surface = in_3d_edges[i].v1.surface;
v1.position.x = p.x;
v1.position.y = p.y;
out_2d_edges[i].v0 = v0;
out_2d_edges[i].v1 = v1;
}
return plane_inverse_transform;
}
void MeshEditingLibrary::build_2d_polygons_from_edges(std::vector<MeshEditPolygon2D> &out_polygons, const std::vector<MeshEditEdge2D> &in_edges, std::vector<MeshEditPolygon2D> &error_polygons)
{
std::vector<MeshEditEdge2D> edge_set = in_edges;
while (edge_set.size() > 0)
{
MeshEditPolygon2D new_polygon;
const MeshEditEdge2D &first_edge = edge_set.back();
edge_set.pop_back();
new_polygon.vertices.emplace_back(first_edge.v0);
new_polygon.vertices.emplace_back(first_edge.v1);
MeshEditVert2D &polygon_end = new_polygon.vertices.back();
MeshEditEdge2D next_edge;
while (MeshEditingLibrary::find_next_edge(next_edge, edge_set, polygon_end))
{
new_polygon.vertices.emplace_back(next_edge.v1);
polygon_end = new_polygon.vertices.back();
}
if (new_polygon.vertices.size() >= 4 && (new_polygon.vertices.front().position - new_polygon.vertices.back().position).length_squared() < PRETTY_SMALL_NUMBER)
{
new_polygon.vertices.pop_back();
MeshEditingLibrary::fix_polygon_winding(new_polygon);
out_polygons.emplace_back(new_polygon);
}
else
{
error_polygons.emplace_back(new_polygon);
}
}
}
bool MeshEditingLibrary::find_next_edge(MeshEditEdge2D &out_next_edge, std::vector<MeshEditEdge2D> &in_edge_set, const MeshEditVert2D &start)
{
float closest_squared_distance = FLT_MAX;
int32_t out_edge_index = -1;
// Search the edges for one that starts closest to the starting point
uint32_t num_in_edges = in_edge_set.size();
for (uint32_t i = 0; i < num_in_edges; i++)
{
float distance_squared = (in_edge_set[i].v0.position - start.position).length_squared();
if (distance_squared < closest_squared_distance)
{
closest_squared_distance = distance_squared;
out_next_edge = in_edge_set[i];
out_edge_index = i;
}
distance_squared = (in_edge_set[i].v1.position - start.position).length_squared();
if (distance_squared < closest_squared_distance)
{
closest_squared_distance = distance_squared;
out_next_edge = in_edge_set[i];
std::swap(out_next_edge.v0, out_next_edge.v1);
out_edge_index = i;
}
}
// If the next edge starts close enough, return it
if (closest_squared_distance < TINY_NUMBER)
{
assert(out_edge_index >= 0);
in_edge_set.erase(in_edge_set.begin() + out_edge_index);
return true;
}
return false;
}
void MeshEditingLibrary::fix_polygon_winding(MeshEditPolygon2D &polygon)
{
float total_angle = 0.0f;
for (int32_t i = polygon.vertices.size() - 1; i >= 0; i--)
{
const int32_t a_index = (i - 1) % polygon.vertices.size();
const int32_t b_index = i;
const int32_t c_index = (i + 1) % polygon.vertices.size();
const float ab_dist_squared = (polygon.vertices[b_index].position - polygon.vertices[a_index].position).length_squared();
const Vector2 ab_edge = (polygon.vertices[b_index].position - polygon.vertices[a_index].position).normalized();
const float bc_dist_squared = (polygon.vertices[c_index].position - polygon.vertices[b_index].position).length_squared();
const Vector2 bc_edge = (polygon.vertices[c_index].position - polygon.vertices[b_index].position).normalized();
if (ab_dist_squared < TINY_NUMBER || bc_dist_squared < TINY_NUMBER || (ab_edge - bc_edge).length_squared() < TEENY_TINY_NUMBER)
{
polygon.vertices.erase(polygon.vertices.begin() + i);
}
else
{
total_angle += UtilityFunctions::asin(ab_edge.x * bc_edge.y - ab_edge.y * bc_edge.x);
}
}
if (total_angle < 0.0f)
{
const uint32_t num_vertices = polygon.vertices.size();
std::vector<MeshEditVert2D> new_vertices;
new_vertices.resize(num_vertices);
for (uint32_t i = 0; i < num_vertices; i++)
{
new_vertices[i] = polygon.vertices[num_vertices - (i + 1)];
}
polygon.vertices = new_vertices;
}
}
const Vector2 MeshEditingLibrary::calculate_planar_uv(const Vector3 &vertex, const Vector3 &mesh_bounds, const MeshSlicePlaneOrientation &axis)
{
switch(axis)
{
case MeshSlicePlaneOrientation::X:
return Vector2(vertex.y / mesh_bounds.y, vertex.z / mesh_bounds.z);
case MeshSlicePlaneOrientation::Y:
return Vector2(vertex.x / mesh_bounds.x, vertex.z / mesh_bounds.z);
case MeshSlicePlaneOrientation::Z: default:
return Vector2(vertex.x / mesh_bounds.x, vertex.y / mesh_bounds.y);
}
}
void MeshEditingLibrary::draw_debug_polygons(Node3D *mesh_parent_node, const std::vector<MeshEditPolygon2D> &polygons, const Transform3D &plane_transform, const Color &colour)
{
#ifdef DEBUG_ENABLED
if (polygons.size() <= 0)
return;
Ref<StandardMaterial3D> material;
material.instantiate();
material->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
material->set_shading_mode(BaseMaterial3D::SHADING_MODE_UNSHADED);
ImmediateMesh *im = memnew(ImmediateMesh);
im->surface_begin(Mesh::PRIMITIVE_LINE_STRIP, material);
const uint32_t num_polygons = polygons.size();
for (uint32_t i = 0; i < num_polygons; i++)
{
const MeshEditPolygon2D &polygon = polygons[i];
const uint32_t num_points = polygons[i].vertices.size();
for (uint32_t j = 0; j < num_points; j++)
{
const MeshEditVert2D &vertex = polygon.vertices[j];
const Vector3 &transformed_vertex = plane_transform.inverse().xform(Vector3(vertex.position.x, vertex.position.y, 0.0f));
im->surface_set_color(colour);
im->surface_add_vertex(transformed_vertex);
}
const MeshEditVert2D &vertex = polygon.vertices.front();
const Vector3 &transformed_vertex = plane_transform.inverse().xform(Vector3(vertex.position.x, vertex.position.y, 0.0f));
im->surface_set_color(colour);
im->surface_add_vertex(transformed_vertex);
}
im->surface_end();
MeshInstance3D *mi = memnew(MeshInstance3D);
mesh_parent_node->add_child(mi);
mi->set_transform(Transform3D());
mi->set_mesh(im);
#endif // DEBUG_ENABLED
}
+107
View File
@@ -0,0 +1,107 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include <godot_cpp/classes/array_mesh.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/skeleton3d.hpp>
#include <godot_cpp/classes/standard_material3d.hpp>
#include <godot_cpp/variant/plane.hpp>
#include <godot_cpp/variant/vector3.hpp>
using namespace godot;
#include <vector>
#define MESH_EDITING_LIBRARY_TAG "MeshEditingLibrary"
typedef std::vector<Vector3> SkinnedVertices;
typedef std::vector<SkinnedVertices> SkinnedSurfaces;
struct MeshEditVert3D
{
uint8_t surface; // Surface index of the original vertex array
uint32_t index; // Index into the original vertex array
Vector3 position; // Position used for generating geometry
};
struct MeshEditVert2D
{
uint8_t surface; // Surface index of the original vertex array
uint32_t index; // Index into the original vertex array
Vector2 position; // Position used for generating geometry
};
struct MeshEditEdge2D
{
MeshEditVert2D v0; // Start vertex
MeshEditVert2D v1; // End vertex
};
struct MeshEditEdge3D
{
MeshEditVert3D v0; // Start vertex
MeshEditVert3D v1; // End vertex
};
struct MeshEditPolygon2D
{
std::vector<MeshEditVert2D> vertices; // List of vertices representing a closed 2D polygon
};
class MeshEditingLibrary : public Node
{
GDCLASS(MeshEditingLibrary, Node);
public:
MeshEditingLibrary();
~MeshEditingLibrary();
enum MeshEditCapUV
{
CAP_UV_FILL_MESH_BOUNDS,
CAP_UV_FILL_CAP_BOUNDS,
CAP_UV_TILED
};
static PackedVector3Array slice_mesh(MeshInstance3D *original_mesh_instance, const Skeleton3D *original_skeleton, const Plane &local_plane, Ref<ArrayMesh> out_first_half, Ref<ArrayMesh> out_other_half, const MeshEditCapUV cap_option, const Ref<StandardMaterial3D> cap_material);
protected:
enum MeshSlicePlaneOrientation
{
X,
Y,
Z
};
private:
static const Vector2 calculate_planar_uv(const Vector3 &vertex, const Vector3 &mesh_bounds, const MeshSlicePlaneOrientation &axis);
static SkinnedSurfaces get_skinned_vertex_positions(const Mesh *mesh, const Skeleton3D *skeleton = nullptr, std::vector<std::vector<Transform3D>> &bone_transforms = std::vector<std::vector<Transform3D>>());
static const Transform3D project_edges(std::vector<MeshEditEdge2D> &out_2d_edges, const Transform3D &to_node_space, const std::vector<MeshEditEdge3D> &in_3d_edges, const Plane &plane);
static void build_2d_polygons_from_edges(std::vector<MeshEditPolygon2D> &out_polygons, const std::vector<MeshEditEdge2D> &in_edges, std::vector<MeshEditPolygon2D> &error_polygons);
static bool find_next_edge(MeshEditEdge2D &out_next_edge, std::vector<MeshEditEdge2D> &in_edge_set, const MeshEditVert2D &start);
static void fix_polygon_winding(MeshEditPolygon2D &polygon);
static void draw_debug_polygons(Node3D *mesh_parent_node, const std::vector<MeshEditPolygon2D> &polygons, const Transform3D &plane_transform, const Color &colour);
// Godot boilerplate below
protected:
static void _bind_methods()
{
ClassDB::bind_static_method("MeshEditingLibrary", D_METHOD("slice_mesh", "original_mesh_instance", "original_skeleton", "local_plane", "out_first_half", "out_other_half", "cap_option", "cap_material"), &MeshEditingLibrary::slice_mesh);
BIND_ENUM_CONSTANT(CAP_UV_FILL_MESH_BOUNDS);
BIND_ENUM_CONSTANT(CAP_UV_FILL_CAP_BOUNDS);
BIND_ENUM_CONSTANT(CAP_UV_TILED);
}
};
VARIANT_ENUM_CAST(MeshEditingLibrary::MeshEditCapUV);
+56 -1
View File
@@ -41,6 +41,18 @@ void PlayerSpawn::_on_area_3d_body_entered(Node3D *body)
} }
void PlayerOrigin::_ready()
{
#ifdef DEBUG_ENABLED
if (Engine::get_singleton()->is_editor_hint())
{
this->unload_editor_preview();
this->load_editor_preview();
}
#endif // DEBUG_ENABLED
}
bool PlayerOrigin::spawn_player(Node3D *parent, Ref<PackedScene> player) const bool PlayerOrigin::spawn_player(Node3D *parent, Ref<PackedScene> player) const
{ {
Ref<PackedScene> player_scene_to_unpack = this->player_scene.is_valid() ? this->player_scene : player; Ref<PackedScene> player_scene_to_unpack = this->player_scene.is_valid() ? this->player_scene : player;
@@ -56,7 +68,7 @@ bool PlayerOrigin::spawn_player(Node3D *parent, Ref<PackedScene> player) const
#ifdef DEBUG_ENABLED #ifdef DEBUG_ENABLED
else else
{ {
UtilityFunctions::push_error("Empty sublevel in PlayerSpawn object \"", this->tag, "\""); PRINT_ERROR(PLAYERSPAWN_LOG_TAG, "Empty sublevel in PlayerSpawn object \"", this->tag, "\"");
} }
#endif #endif
} }
@@ -70,3 +82,46 @@ bool PlayerOrigin::spawn_player(Node3D *parent, Ref<PackedScene> player) const
return false; return false;
} }
void PlayerOrigin::set_player_scene(Ref<PackedScene> s)
{
this->player_scene = s;
#ifdef DEBUG_ENABLED
if (Engine::get_singleton()->is_editor_hint())
{
this->unload_editor_preview();
this->load_editor_preview();
}
#endif // DEBUG_ENABLED
}
void PlayerOrigin::load_editor_preview()
{
if (this->player_preview_node)
return;
if (SceneLoader *scene_loader = SceneLoader::get_singleton())
{
scene_loader->load_scene(this->player_scene->get_path(), callable_mp(this, &PlayerOrigin::_threaded_load_callback));
}
}
void PlayerOrigin::_threaded_load_callback(Ref<PackedScene> loaded_scene)
{
if (loaded_scene.is_valid())
{
this->player_preview_node = cast_to<Node3D>(loaded_scene->instantiate());
this->add_child(this->player_preview_node);
}
}
void PlayerOrigin::unload_editor_preview()
{
if (this->player_preview_node)
{
this->player_preview_node->queue_free();
this->player_preview_node = nullptr;
}
}
+13 -1
View File
@@ -8,11 +8,14 @@
#pragma once #pragma once
#include "orng_macros.h" #include "orng_macros.h"
#include "singletons/scene_loader.h"
#include <godot_cpp/classes/node3d.hpp> #include <godot_cpp/classes/node3d.hpp>
#include <godot_cpp/classes/packed_scene.hpp> #include <godot_cpp/classes/packed_scene.hpp>
using namespace godot; using namespace godot;
#define PLAYERSPAWN_LOG_TAG "PlayerSpawn"
#define PLAYER_ORIGIN_TAG "origin" #define PLAYER_ORIGIN_TAG "origin"
@@ -24,6 +27,8 @@ class PlayerOrigin : public Node3D
GDCLASS(PlayerOrigin, Node3D); GDCLASS(PlayerOrigin, Node3D);
public: public:
virtual void _ready() override;
// Spawn the player at the spawn point's location. If the spawn point has // Spawn the player at the spawn point's location. If the spawn point has
// no player scene set, the passed in player scene will be used. Function // no player scene set, the passed in player scene will be used. Function
// returns false if no player could be spawned. // returns false if no player could be spawned.
@@ -31,12 +36,15 @@ public:
virtual StringName get_tag() const { return this->tag; } virtual StringName get_tag() const { return this->tag; }
void set_player_scene(Ref<PackedScene> s) { this->player_scene = s; } void set_player_scene(Ref<PackedScene> s);
Ref<PackedScene> get_player_scene() const { return this->player_scene; } Ref<PackedScene> get_player_scene() const { return this->player_scene; }
void set_sublevel_scenes_to_load(TypedArray<NodePath> scenes) { this->sublevel_scenes_to_load = scenes; } void set_sublevel_scenes_to_load(TypedArray<NodePath> scenes) { this->sublevel_scenes_to_load = scenes; }
TypedArray<NodePath> get_sublevel_scenes_to_load() const { return this->sublevel_scenes_to_load; } TypedArray<NodePath> get_sublevel_scenes_to_load() const { return this->sublevel_scenes_to_load; }
void load_editor_preview();
void unload_editor_preview();
protected: protected:
StringName tag = StringName(PLAYER_ORIGIN_TAG); StringName tag = StringName(PLAYER_ORIGIN_TAG);
@@ -45,6 +53,10 @@ protected:
// List of sublevels that need to be loaded along with the player. // List of sublevels that need to be loaded along with the player.
TypedArray<NodePath> sublevel_scenes_to_load; TypedArray<NodePath> sublevel_scenes_to_load;
private:
void _threaded_load_callback(Ref<PackedScene> loaded_scene);
Node3D *player_preview_node = nullptr;
// Godot boilerplate below // Godot boilerplate below
protected: protected:
+6 -6
View File
@@ -16,12 +16,12 @@ using namespace godot;
void SublevelScene::_ready() void SublevelScene::_ready()
{ {
#ifdef DEBUG_ENABLED // #ifdef DEBUG_ENABLED
if (Engine::get_singleton()->is_editor_hint()) // if (Engine::get_singleton()->is_editor_hint())
{ // {
this->load_sublevel(); // this->load_sublevel();
} // }
#endif // DEBUG_ENABLED // #endif // DEBUG_ENABLED
} }
void SublevelScene::set_sublevel(StringName s) void SublevelScene::set_sublevel(StringName s)
+33 -1
View File
@@ -1,5 +1,13 @@
#pragma once #pragma once
/**
* Helper constants
*/
#define TEENY_TINY_NUMBER 0.000000000001
#define TINY_NUMBER 0.0000000001
#define PRETTY_SMALL_NUMBER 0.00000001
#define SMALL_NUMBER 0.000001
/** /**
* Method and property binding helpers * Method and property binding helpers
*/ */
@@ -27,4 +35,28 @@
* Deferred function helpers * Deferred function helpers
*/ */
#define CALL_NEXT_FRAME(C) \ #define CALL_NEXT_FRAME(C) \
this->get_tree()->create_timer(0.001)->connect("timeout", C) this->get_tree()->create_timer(SMALL_NUMBER)->connect("timeout", C)
/**
* Editor hint helpers
*/
#ifdef DEBUG_ENABLED
#define RETURN_IF_EDITOR() if(Engine::get_singleton()->is_editor_hint()) { return; }
#else
#define RETURN_IF_EDITOR()
#endif // DEBUG_ENABLED
/**
* Logging helpers
*/
#ifdef DEBUG_ENABLED
#define PRINT_LOG(tag, ...) UtilityFunctions::print("[" tag "] ", __VA_ARGS__)
#define PRINT_WARNING(tag, ...) UtilityFunctions::push_warning("[" tag "] ", __VA_ARGS__)
#define PRINT_ERROR(tag, ...) UtilityFunctions::printerr("[" tag "] ", __VA_ARGS__)
#else
#define PRINT_LOG(tag, ...)
#define PRINT_WARNING(tag, ...)
#define PRINT_ERROR(tag, ...)
#endif // DEBUG_ENABLED
+17 -10
View File
@@ -21,21 +21,26 @@
#include "nodes/player_spawn.h" #include "nodes/player_spawn.h"
#include "nodes/sublevel_loader.h" #include "nodes/sublevel_loader.h"
#include "nodes/sublevel_scene.h" #include "nodes/sublevel_scene.h"
#include "nodes/character_nodes/character_3d.h"
#include "nodes/hurtbox/hurtbox_base.h"
#include "resources/level_metadata_map.h" #include "resources/level_metadata_map.h"
#include "resources/level_metadata_resource.h" #include "resources/level_metadata_resource.h"
#include "nodes/mesh_editing_library.h"
#include "singletons/input_handler.h" #include "singletons/input_handler.h"
#include "singletons/save_manager.h" #include "singletons/save_manager.h"
#include "singletons/scene_loader.h" #include "singletons/scene_loader.h"
#include "singletons/vendor_service/vendor_service.h" // #include "singletons/vendor_service/vendor_service.h"
using namespace godot; using namespace godot;
GDSINGLETON_REGISTER_PTR(InputHandler, _input_handler_singleton); GDSINGLETON_REGISTER_PTR(InputHandler, _input_handler_singleton);
GDSINGLETON_REGISTER_PTR(SaveManager, _save_manager_singleton); GDSINGLETON_REGISTER_PTR(SaveManager, _save_manager_singleton);
GDSINGLETON_REGISTER_PTR(SceneLoader, _scene_loader_singleton); GDSINGLETON_REGISTER_PTR(SceneLoader, _scene_loader_singleton);
GDSINGLETON_REGISTER_PTR(VendorService, _vendor_service_singleton); // GDSINGLETON_REGISTER_PTR(VendorService, _vendor_service_singleton);
void initialize_orng_module(ModuleInitializationLevel p_level) { void initialize_orng_module(ModuleInitializationLevel p_level) {
@@ -60,30 +65,32 @@ void initialize_orng_module(ModuleInitializationLevel p_level) {
ClassDB::register_class<MovementHandler>(); ClassDB::register_class<MovementHandler>();
ClassDB::register_class<Character3D>();
ClassDB::register_class<GameClasses>(); ClassDB::register_class<GameClasses>();
ClassDB::register_class<LevelScene>(); ClassDB::register_class<LevelScene>();
ClassDB::register_class<PlayerOrigin>(); ClassDB::register_class<PlayerOrigin>();
ClassDB::register_class<PlayerSpawn>(); ClassDB::register_class<PlayerSpawn>();
ClassDB::register_class<HurtboxBase>();
ClassDB::register_class<SaveFileData>(); ClassDB::register_class<SaveFileData>();
ClassDB::register_class<MeshEditingLibrary>();
GDSINGLETON_REGISTER_CLASS(InputHandler, _input_handler_singleton); GDSINGLETON_REGISTER_CLASS(InputHandler, _input_handler_singleton);
GDSINGLETON_REGISTER_CLASS(SaveManager, _save_manager_singleton); GDSINGLETON_REGISTER_CLASS(SaveManager, _save_manager_singleton);
GDSINGLETON_REGISTER_CLASS(SceneLoader, _scene_loader_singleton); GDSINGLETON_REGISTER_CLASS(SceneLoader, _scene_loader_singleton);
GDSINGLETON_REGISTER_CLASS(VendorService, _vendor_service_singleton); // GDSINGLETON_REGISTER_CLASS(VendorService, _vendor_service_singleton);
} }
} }
void uninitialize_orng_module(ModuleInitializationLevel p_level) { void uninitialize_orng_module(ModuleInitializationLevel p_level) {
if (p_level == ModuleInitializationLevel::MODULE_INITIALIZATION_LEVEL_SCENE) if (p_level == ModuleInitializationLevel::MODULE_INITIALIZATION_LEVEL_SCENE)
{ {
if (Engine::get_singleton()->get_main_loop()) // GDSINGLETON_UNREGISTER_CLASS(_vendor_service_singleton);
{ GDSINGLETON_UNREGISTER_CLASS(_scene_loader_singleton);
GDSINGLETON_UNREGISTER_CLASS(_vendor_service_singleton); GDSINGLETON_UNREGISTER_CLASS(_save_manager_singleton);
GDSINGLETON_UNREGISTER_CLASS(_scene_loader_singleton); GDSINGLETON_UNREGISTER_CLASS(_input_handler_singleton);
GDSINGLETON_UNREGISTER_CLASS(_save_manager_singleton);
GDSINGLETON_UNREGISTER_CLASS(_input_handler_singleton);
}
} }
} }
+104 -25
View File
@@ -8,6 +8,7 @@
#include "resources/input_resource.h" #include "resources/input_resource.h"
#include <godot_cpp/classes/input.hpp> #include <godot_cpp/classes/input.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
using namespace godot; using namespace godot;
@@ -15,15 +16,29 @@ void InputResource::update_buttons(const Ref<InputEvent> event, const float delt
{ {
for (uint8_t i = 0; i < this->input_actions.size(); i++) for (uint8_t i = 0; i < this->input_actions.size(); i++)
{ {
const InputAction *action = cast_to<InputAction>(this->input_actions[i]); InputAction *action = cast_to<InputAction>(this->input_actions[i]);
const StringName suffix_pressed = StringName("_on_") + action->get_action_name() + INPUTACTION_SUFFIX_PRESSED; const float action_strength = event->get_action_strength(action->get_action_name());
if (event->is_action_pressed(action->get_action_name()) && this->has_signal(suffix_pressed)) const float action_deadzone = action->get_deadzone();
this->emit_signal(suffix_pressed);
if (!action->is_active())
const StringName suffix_released = StringName("_on_") + action->get_action_name() + INPUTACTION_SUFFIX_RELEASED; {
if (event->is_action_released(action->get_action_name()) && this->has_signal(suffix_released)) if (event->is_action_pressed(action->get_action_name()) && action_strength >= action_deadzone)
this->emit_signal(suffix_released); {
action->set_active(true);
const StringName &pressed_signal = StringName("_on_") + action->get_action_name() + INPUTACTION_SUFFIX_PRESSED + INPUTHANDLER_SUFFIX_SIGNAL;
if (this->has_signal(pressed_signal)) this->emit_signal(pressed_signal);
}
}
else
{
if (event->is_action_released(action->get_action_name()) || (event->is_action_pressed(action->get_action_name()) && action_strength < action_deadzone))
{
action->set_active(false);
const StringName &released_signal = StringName("_on_") + action->get_action_name() + INPUTACTION_SUFFIX_RELEASED + INPUTHANDLER_SUFFIX_SIGNAL;
if (this->has_signal(released_signal)) this->emit_signal(released_signal);
}
}
} }
} }
@@ -31,17 +46,46 @@ void InputResource::update_axes(const float delta)
{ {
for (uint8_t i = 0; i < this->input_axes.size(); i++) for (uint8_t i = 0; i < this->input_axes.size(); i++)
{ {
const InputAxis *axis = cast_to<InputAxis>(this->input_axes[i]); InputAxis *axis = cast_to<InputAxis>(this->input_axes[i]);
const StringName prefix = StringName("_on_") + axis->get_axis_name(); const StringName prefix = StringName("_on_") + axis->get_axis_name();
const float axis_deadzone = axis->get_deadzone();
const StringName signal_1d = prefix + INPUTAXIS_ONE_DIMENSIONAL_SUFFIX;
if (this->has_signal(signal_1d)) this->emit_signal(signal_1d, delta, axis->get_x_axis());
const StringName signal_2d = prefix + INPUTAXIS_TWO_DIMENSIONAL_SUFFIX; Vector3 current_input = axis->get_last_axis_input();
if (this->has_signal(signal_2d)) this->emit_signal(signal_2d, delta, axis->get_lateral_vector());
const StringName signal_3d = prefix + INPUTAXIS_THREE_DIMENSIONAL_SUFFIX; const StringName &signal_1d = prefix + INPUTAXIS_ONE_DIMENSIONAL_SUFFIX + INPUTHANDLER_SUFFIX_SIGNAL;
if (this->has_signal(signal_3d)) this->emit_signal(signal_3d, delta, axis->get_spherical_vector()); if (this->has_signal(signal_1d))
{
float x_axis = axis->get_x_axis();
if (UtilityFunctions::absf(x_axis) < axis_deadzone) x_axis = 0.0f;
if (current_input.x != x_axis || current_input.length() > SMALL_NUMBER)
this->emit_signal(signal_1d, delta, x_axis);
current_input.x = x_axis;
}
const StringName &signal_2d = prefix + INPUTAXIS_TWO_DIMENSIONAL_SUFFIX + INPUTHANDLER_SUFFIX_SIGNAL;
if (this->has_signal(signal_2d))
{
Vector2 &vector = axis->get_lateral_vector();
if (UtilityFunctions::absf(vector.x) < axis_deadzone) vector.x = 0.0f;
if (UtilityFunctions::absf(vector.y) < axis_deadzone) vector.y = 0.0f;
if ((current_input.x != vector.x || current_input.z != vector.y) || current_input.length() > SMALL_NUMBER)
this->emit_signal(signal_2d, delta, vector);
current_input.x = vector.x; current_input.z = vector.y;
}
const StringName &signal_3d = prefix + INPUTAXIS_THREE_DIMENSIONAL_SUFFIX + INPUTHANDLER_SUFFIX_SIGNAL;
if (this->has_signal(signal_3d))
{
Vector3 &vector = axis->get_spherical_vector();
if (UtilityFunctions::absf(vector.x) < axis_deadzone) vector.x = 0.0f;
if (UtilityFunctions::absf(vector.y) < axis_deadzone) vector.y = 0.0f;
if (UtilityFunctions::absf(vector.z) < axis_deadzone) vector.z = 0.0f;
if (current_input != vector || current_input.length() > SMALL_NUMBER)
this->emit_signal(signal_3d, delta, vector);
current_input = vector;
}
axis->set_last_axis_input(current_input);
} }
} }
@@ -50,52 +94,87 @@ void InputResource::update_axes_mouse_event(const Ref<InputEventMouseMotion> eve
for (uint8_t i = 0; i < this->input_axes.size(); i++) for (uint8_t i = 0; i < this->input_axes.size(); i++)
{ {
const InputAxis *axis = cast_to<InputAxis>(this->input_axes[i]); const InputAxis *axis = cast_to<InputAxis>(this->input_axes[i]);
const StringName signal = StringName("_on_") + axis->get_axis_name() + INPUTAXIS_TWO_DIMENSIONAL_SUFFIX; const StringName signal = StringName("_on_") + axis->get_axis_name() + INPUTAXIS_MOUSE_INPUT_SUFFIX + INPUTHANDLER_SUFFIX_SIGNAL;
if (axis->get_include_mouse() && this->has_signal(signal)) if (axis->get_include_mouse() && this->has_signal(signal))
this->emit_signal(signal, delta, Vector2(event->get_relative().x, event->get_relative().y) * 0.001 / delta); {
this->emit_signal(signal, delta, event->get_relative() * 0.0001f / delta);
}
} }
} }
Ref<InputAction> InputResource::find_input_action(const StringName &name) const
{
for (uint8_t i = 0; i < this->input_actions.size(); i++)
{
const Ref<InputAction> action = cast_to<InputAction>(this->input_actions[i]);
if (action->get_action_name() == name)
{
return action;
}
}
return nullptr;
}
Ref<InputAxis> InputResource::find_input_axis(const StringName &name) const
{
for (uint8_t i = 0; i < this->input_axes.size(); i++)
{
const Ref<InputAxis> axis = cast_to<InputAxis>(this->input_axes[i]);
if (axis->get_axis_name() == name)
{
return axis;
}
}
return nullptr;
}
Vector3 InputAxis::get_spherical_vector() const Vector3 InputAxis::get_spherical_vector() const
{ {
const Input *input = Input::get_singleton(); const Input *input = Input::get_singleton();
return Vector3( const Vector3 &axis = Vector3(
input->get_axis(this->axis_name + INPUTAXIS_LEFT_SUFFIX, this->axis_name + INPUTAXIS_RIGHT_SUFFIX), input->get_axis(this->axis_name + INPUTAXIS_LEFT_SUFFIX, this->axis_name + INPUTAXIS_RIGHT_SUFFIX),
input->get_axis(this->axis_name + INPUTAXIS_DOWN_SUFFIX, this->axis_name + INPUTAXIS_UP_SUFFIX), input->get_axis(this->axis_name + INPUTAXIS_DOWN_SUFFIX, this->axis_name + INPUTAXIS_UP_SUFFIX),
input->get_axis(this->axis_name + INPUTAXIS_FORWARD_SUFFIX, this->axis_name + INPUTAXIS_BACK_SUFFIX) input->get_axis(this->axis_name + INPUTAXIS_FORWARD_SUFFIX, this->axis_name + INPUTAXIS_BACK_SUFFIX)
); );
return axis.length() >= this->deadzone ? axis : Vector3();
} }
Vector2 InputAxis::get_lateral_vector() const Vector2 InputAxis::get_lateral_vector() const
{ {
return Input::get_singleton()->get_vector( const Vector2 &axis = Input::get_singleton()->get_vector(
this->axis_name + INPUTAXIS_LEFT_SUFFIX, this->axis_name + INPUTAXIS_RIGHT_SUFFIX, this->axis_name + INPUTAXIS_LEFT_SUFFIX, this->axis_name + INPUTAXIS_RIGHT_SUFFIX,
this->axis_name + INPUTAXIS_FORWARD_SUFFIX, this->axis_name + INPUTAXIS_BACK_SUFFIX this->axis_name + INPUTAXIS_FORWARD_SUFFIX, this->axis_name + INPUTAXIS_BACK_SUFFIX
); );
return axis.length() >= this->deadzone ? axis : Vector2();
} }
Vector2 InputAxis::get_lateral_vector_square() const Vector2 InputAxis::get_lateral_vector_square() const
{ {
const Input *input = Input::get_singleton(); const Input *input = Input::get_singleton();
return Vector2( const Vector2 &axis = Vector2(
input->get_axis(this->axis_name + INPUTAXIS_LEFT_SUFFIX, this->axis_name + INPUTAXIS_RIGHT_SUFFIX), input->get_axis(this->axis_name + INPUTAXIS_LEFT_SUFFIX, this->axis_name + INPUTAXIS_RIGHT_SUFFIX),
input->get_axis(this->axis_name + INPUTAXIS_FORWARD_SUFFIX, this->axis_name + INPUTAXIS_BACK_SUFFIX) input->get_axis(this->axis_name + INPUTAXIS_FORWARD_SUFFIX, this->axis_name + INPUTAXIS_BACK_SUFFIX)
); );
return axis.length() >= this->deadzone ? axis : Vector2();
} }
float InputAxis::get_x_axis() const float InputAxis::get_x_axis() const
{ {
return Input::get_singleton()->get_axis(this->axis_name + INPUTAXIS_LEFT_SUFFIX, this->axis_name + INPUTAXIS_RIGHT_SUFFIX); const float axis = Input::get_singleton()->get_axis(this->axis_name + INPUTAXIS_LEFT_SUFFIX, this->axis_name + INPUTAXIS_RIGHT_SUFFIX);
return UtilityFunctions::absf(axis) >= this->deadzone ? axis : 0.0f;
} }
float InputAxis::get_y_axis() const float InputAxis::get_y_axis() const
{ {
return Input::get_singleton()->get_axis(this->axis_name + INPUTAXIS_DOWN_SUFFIX, this->axis_name + INPUTAXIS_UP_SUFFIX); const float axis = Input::get_singleton()->get_axis(this->axis_name + INPUTAXIS_DOWN_SUFFIX, this->axis_name + INPUTAXIS_UP_SUFFIX);
return UtilityFunctions::absf(axis) >= this->deadzone ? axis : 0.0f;
} }
float InputAxis::get_z_axis() const float InputAxis::get_z_axis() const
{ {
return Input::get_singleton()->get_axis(this->axis_name + INPUTAXIS_FORWARD_SUFFIX, this->axis_name + INPUTAXIS_BACK_SUFFIX); const float axis = Input::get_singleton()->get_axis(this->axis_name + INPUTAXIS_FORWARD_SUFFIX, this->axis_name + INPUTAXIS_BACK_SUFFIX);
return UtilityFunctions::absf(axis) >= this->deadzone ? axis : 0.0f;
} }
+26 -2
View File
@@ -13,6 +13,8 @@
#include <godot_cpp/classes/resource.hpp> #include <godot_cpp/classes/resource.hpp>
using namespace godot; using namespace godot;
#define INPUTHANDLER_SUFFIX_SIGNAL StringName("_signal")
#define INPUTACTION_SUFFIX_PRESSED StringName("_pressed") #define INPUTACTION_SUFFIX_PRESSED StringName("_pressed")
#define INPUTACTION_SUFFIX_RELEASED StringName("_released") #define INPUTACTION_SUFFIX_RELEASED StringName("_released")
@@ -26,6 +28,7 @@ using namespace godot;
#define INPUTAXIS_ONE_DIMENSIONAL_SUFFIX StringName("_1d") #define INPUTAXIS_ONE_DIMENSIONAL_SUFFIX StringName("_1d")
#define INPUTAXIS_TWO_DIMENSIONAL_SUFFIX StringName("_2d") #define INPUTAXIS_TWO_DIMENSIONAL_SUFFIX StringName("_2d")
#define INPUTAXIS_THREE_DIMENSIONAL_SUFFIX StringName("_3d") #define INPUTAXIS_THREE_DIMENSIONAL_SUFFIX StringName("_3d")
#define INPUTAXIS_MOUSE_INPUT_SUFFIX StringName("_mouse")
class InputAxis2D : public Resource class InputAxis2D : public Resource
@@ -67,11 +70,17 @@ public:
void set_input_events(const TypedArray<InputEvent> events) { this->input_events = events; } void set_input_events(const TypedArray<InputEvent> events) { this->input_events = events; }
TypedArray<InputEvent> get_input_events() const { return this->input_events; } TypedArray<InputEvent> get_input_events() const { return this->input_events; }
void set_active(const bool active) { this->_active = active; }
bool is_active() const { return this->_active; }
protected: protected:
StringName action_name = "action_name"; StringName action_name = "action_name";
float deadzone = 0.5f; float deadzone = 0.5f;
TypedArray<InputEvent> input_events; TypedArray<InputEvent> input_events;
private:
bool _active = false;
// Godot boilerplate below // Godot boilerplate below
protected: protected:
static void _bind_methods() static void _bind_methods()
@@ -79,6 +88,9 @@ protected:
ADD_GETTER_SETTER(InputAction, action_name, Variant::STRING_NAME); ADD_GETTER_SETTER(InputAction, action_name, Variant::STRING_NAME);
ADD_GETTER_SETTER(InputAction, deadzone, Variant::FLOAT); ADD_GETTER_SETTER(InputAction, deadzone, Variant::FLOAT);
ADD_GETTER_SETTER_HINTED(InputAction, input_events, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "InputEvent")); ADD_GETTER_SETTER_HINTED(InputAction, input_events, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "InputEvent"));
ClassDB::bind_method(D_METHOD("is_active"), &InputAction::is_active);
ClassDB::bind_method(D_METHOD("set_active", "active"), &InputAction::set_active);
} }
}; };
@@ -115,8 +127,11 @@ public:
void set_up_down_events(const TypedArray<InputAxis2D> events) { this->up_down_events = events; } void set_up_down_events(const TypedArray<InputAxis2D> events) { this->up_down_events = events; }
TypedArray<InputAxis2D> get_up_down_events() const { return this->up_down_events; } TypedArray<InputAxis2D> get_up_down_events() const { return this->up_down_events; }
void set_last_axis_input(const Vector3 &value) { this->last_axis_input = value; }
Vector3 get_last_axis_input() const { return this->last_axis_input; }
Vector3 get_spherical_vector() const; Vector3 get_spherical_vector() const;
Vector2 get_lateral_vector() const; Vector2 get_lateral_vector() const;
Vector2 get_lateral_vector_square() const; Vector2 get_lateral_vector_square() const;
@@ -134,6 +149,9 @@ protected:
TypedArray<InputAxis2D> left_right_events; TypedArray<InputAxis2D> left_right_events;
TypedArray<InputAxis2D> forward_back_events; TypedArray<InputAxis2D> forward_back_events;
TypedArray<InputAxis2D> up_down_events; TypedArray<InputAxis2D> up_down_events;
private:
Vector3 last_axis_input = Vector3();
// Godot boilerplate below // Godot boilerplate below
protected: protected:
@@ -185,6 +203,9 @@ public:
void set_input_axes(const TypedArray<InputAxis> input_axes) { this->input_axes = input_axes; } void set_input_axes(const TypedArray<InputAxis> input_axes) { this->input_axes = input_axes; }
TypedArray<InputAxis> get_input_axes() const { return this->input_axes; } TypedArray<InputAxis> get_input_axes() const { return this->input_axes; }
Ref<InputAction> find_input_action(const StringName &name) const;
Ref<InputAxis> find_input_axis(const StringName &name) const;
protected: protected:
TypedArray<InputAction> input_actions; TypedArray<InputAction> input_actions;
@@ -197,6 +218,9 @@ protected:
{ // input_actions, input_axes { // input_actions, input_axes
ADD_GETTER_SETTER_HINTED(InputResource, input_actions, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "InputAction")); ADD_GETTER_SETTER_HINTED(InputResource, input_actions, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "InputAction"));
ADD_GETTER_SETTER_HINTED(InputResource, input_axes, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "InputAxis")); ADD_GETTER_SETTER_HINTED(InputResource, input_axes, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "InputAxis"));
BIND_METHOD_1PARAM(InputResource, find_input_action, name);
BIND_METHOD_1PARAM(InputResource, find_input_axis, name);
} }
{ // update { // update
+144 -87
View File
@@ -22,9 +22,7 @@ GDSINGLETON_CPP(InputHandler);
void InputHandler::_process(double delta) void InputHandler::_process(double delta)
{ {
for (InputResource *resource : this->active_resources) for (InputResource *resource : this->active_resources)
{
resource->update_axes(delta); resource->update_axes(delta);
}
} }
void InputHandler::_input(const Ref<InputEvent> &event) void InputHandler::_input(const Ref<InputEvent> &event)
@@ -32,16 +30,12 @@ void InputHandler::_input(const Ref<InputEvent> &event)
for (InputResource *resource : this->active_resources) for (InputResource *resource : this->active_resources)
{ {
if (event->is_action_type()) if (event->is_action_type())
{
resource->update_buttons(event, this->get_process_delta_time()); resource->update_buttons(event, this->get_process_delta_time());
}
else if (const InputEventMouseMotion *mouse_event = cast_to<InputEventMouseMotion>(event.ptr())) else if (const InputEventMouseMotion *mouse_event = cast_to<InputEventMouseMotion>(event.ptr()))
{ {
const Input *input = Input::get_singleton(); const Input *input = Input::get_singleton();
if (input->get_mouse_mode() != Input::MOUSE_MODE_VISIBLE) if (input->get_mouse_mode() != Input::MOUSE_MODE_VISIBLE)
{
resource->update_axes_mouse_event(event, this->get_process_delta_time()); resource->update_axes_mouse_event(event, this->get_process_delta_time());
}
} }
} }
} }
@@ -52,55 +46,54 @@ void InputHandler::add_input_resource(Node *target, InputResource *resource)
const TypedArray<InputAction> &input_actions = resource->get_input_actions(); const TypedArray<InputAction> &input_actions = resource->get_input_actions();
const TypedArray<InputAxis> &input_axes = resource->get_input_axes(); const TypedArray<InputAxis> &input_axes = resource->get_input_axes();
for(uint8_t i = 0; i < input_actions.size(); i++) for (uint8_t i = 0; i < input_actions.size(); i++)
{ {
if (const InputAction *action = cast_to<InputAction>(input_actions[i])) if (const InputAction *action = cast_to<InputAction>(input_actions[i]))
{ {
if (!input_map->has_action(action->get_action_name())) if (!input_map->has_action(action->get_action_name()))
{
input_map->add_action(action->get_action_name(), action->get_deadzone()); input_map->add_action(action->get_action_name(), action->get_deadzone());
}
for(uint8_t s = 0; s < 2; s++) for (uint8_t s = 0; s < 2; s++)
{ {
const StringName signal_name = StringName("_on_") + action->get_action_name() + this->input_action_suffixes[s]; const StringName callback_name = StringName("_on_") + action->get_action_name() + this->input_action_suffixes[s];
if (target->has_method(signal_name)) if (target->has_method(callback_name))
{ {
const StringName signal_name = callback_name + INPUTHANDLER_SUFFIX_SIGNAL;
if (!resource->has_signal(signal_name)) resource->add_user_signal(signal_name);
const Callable &callable = Callable(target, callback_name);
if (!resource->is_connected(signal_name, callable))
resource->connect(signal_name, callable);
const TypedArray<InputEvent> &events = action->get_input_events(); const TypedArray<InputEvent> &events = action->get_input_events();
if (!resource->has_signal(signal_name))
{
resource->add_user_signal(signal_name);
}
for (uint8_t e = 0; e < events.size(); e++) for (uint8_t e = 0; e < events.size(); e++)
{ {
const Ref<InputEvent> &event = events[e]; const Ref<InputEvent> &event = events[e];
input_map->action_add_event(action->get_action_name(), event); input_map->action_add_event(action->get_action_name(), event);
} }
resource->connect(signal_name, Callable(target, signal_name));
} }
} }
} }
} }
for(uint8_t i = 0; i < input_axes.size(); i++) for (uint8_t i = 0; i < input_axes.size(); i++)
{ {
if (const InputAxis *axis = cast_to<InputAxis>(input_axes[i])) if (const InputAxis *axis = cast_to<InputAxis>(input_axes[i]))
{ {
const uint8_t &axis_dimensions = axis->get_axis_dimensions(); const uint8_t &axis_dimensions = axis->get_axis_dimensions();
for(uint8_t s = 0; s <= axis_dimensions; s++) for (uint8_t s = 0; s <= axis_dimensions; s++)
{ {
const StringName signal_name = StringName("_on_") + axis->get_axis_name() + this->input_axis_suffixes[s]; const StringName callback_name = StringName("_on_") + axis->get_axis_name() + this->input_axis_suffixes[s];
if (!resource->has_signal(signal_name)) if (target->has_method(callback_name))
{ {
resource->add_user_signal(signal_name); const StringName signal_name = callback_name + INPUTHANDLER_SUFFIX_SIGNAL;
} if (!resource->has_signal(signal_name)) resource->add_user_signal(signal_name);
if (target->has_method(signal_name)) const Callable &callable = Callable(target, callback_name);
{ if (!resource->is_connected(signal_name, callable)) resource->connect(signal_name, callable);
resource->connect(signal_name, Callable(target, signal_name));
} }
} }
const StringName &axis_name = axis->get_axis_name(); const StringName &axis_name = axis->get_axis_name();
const float &deadzone = axis->get_deadzone(); const float &deadzone = axis->get_deadzone();
if (axis_dimensions >= InputAxis::AXIS_DIMENSIONS::ONE) if (axis_dimensions >= InputAxis::AXIS_DIMENSIONS::ONE)
@@ -109,7 +102,7 @@ void InputHandler::add_input_resource(Node *target, InputResource *resource)
const StringName &right_axis_action = axis_name + INPUTAXIS_RIGHT_SUFFIX; const StringName &right_axis_action = axis_name + INPUTAXIS_RIGHT_SUFFIX;
if (!input_map->has_action(left_axis_action)) input_map->add_action(left_axis_action, deadzone); if (!input_map->has_action(left_axis_action)) input_map->add_action(left_axis_action, deadzone);
if (!input_map->has_action(right_axis_action)) input_map->add_action(right_axis_action, deadzone); if (!input_map->has_action(right_axis_action)) input_map->add_action(right_axis_action, deadzone);
const TypedArray<InputAxis2D> &left_right_events = axis->get_left_right_events(); const TypedArray<InputAxis2D> &left_right_events = axis->get_left_right_events();
for(uint8_t e = 0; e < left_right_events.size(); e++) for(uint8_t e = 0; e < left_right_events.size(); e++)
{ {
@@ -125,7 +118,7 @@ void InputHandler::add_input_resource(Node *target, InputResource *resource)
const StringName &forward_axis_action = axis_name + INPUTAXIS_FORWARD_SUFFIX; const StringName &forward_axis_action = axis_name + INPUTAXIS_FORWARD_SUFFIX;
if (!input_map->has_action(back_axis_action)) input_map->add_action(back_axis_action, deadzone); if (!input_map->has_action(back_axis_action)) input_map->add_action(back_axis_action, deadzone);
if (!input_map->has_action(forward_axis_action)) input_map->add_action(forward_axis_action, deadzone); if (!input_map->has_action(forward_axis_action)) input_map->add_action(forward_axis_action, deadzone);
const TypedArray<InputAxis2D> &forward_back_events = axis->get_forward_back_events(); const TypedArray<InputAxis2D> &forward_back_events = axis->get_forward_back_events();
for(uint8_t e = 0; e < forward_back_events.size(); e++) for(uint8_t e = 0; e < forward_back_events.size(); e++)
{ {
@@ -141,7 +134,7 @@ void InputHandler::add_input_resource(Node *target, InputResource *resource)
const StringName &up_axis_action = axis_name + INPUTAXIS_UP_SUFFIX; const StringName &up_axis_action = axis_name + INPUTAXIS_UP_SUFFIX;
if (!input_map->has_action(down_axis_action)) input_map->add_action(down_axis_action, deadzone); if (!input_map->has_action(down_axis_action)) input_map->add_action(down_axis_action, deadzone);
if (!input_map->has_action(up_axis_action)) input_map->add_action(up_axis_action, deadzone); if (!input_map->has_action(up_axis_action)) input_map->add_action(up_axis_action, deadzone);
const TypedArray<InputAxis2D> &up_down_events = axis->get_up_down_events(); const TypedArray<InputAxis2D> &up_down_events = axis->get_up_down_events();
for(uint8_t e = 0; e < up_down_events.size(); e++) for(uint8_t e = 0; e < up_down_events.size(); e++)
{ {
@@ -150,66 +143,120 @@ void InputHandler::add_input_resource(Node *target, InputResource *resource)
input_map->action_add_event(up_axis_action, up_down_event->get_positive()); input_map->action_add_event(up_axis_action, up_down_event->get_positive());
} }
} }
if (axis->get_include_mouse()) if (axis->get_include_mouse())
{ {
Engine *engine = Engine::get_singleton();
this->call_deferred("_enable_mouse_capture"); this->call_deferred("_enable_mouse_capture");
const StringName callback_name = StringName("_on_") + axis->get_axis_name() + INPUTAXIS_MOUSE_INPUT_SUFFIX;
if (target->has_method(callback_name))
{
const StringName signal_name = callback_name + INPUTHANDLER_SUFFIX_SIGNAL;
if (!resource->has_signal(signal_name)) resource->add_user_signal(signal_name);
const Callable &callable = Callable(target, callback_name);
if (!resource->is_connected(signal_name, callable)) resource->connect(signal_name, callable);
}
} }
} }
} }
this->active_resources.insert(resource); this->active_resources.insert(resource);
const StringName input_resource_method = target->get_name() + StringName("_") + resource->get_path(); const StringName &input_resource_method = target->get_name() + StringName("_") + resource->get_path();
if (this->bound_remove_methods.find(input_resource_method) == this->bound_remove_methods.end()) if (this->bound_remove_methods.find(input_resource_method) == this->bound_remove_methods.end())
{ {
MethodBind *bind = ClassDB::bind_method(input_resource_method, &InputHandler::remove_input_resource); MethodBind *bind = ClassDB::bind_method(input_resource_method, &InputHandler::remove_input_resource);
this->bound_remove_methods.emplace(input_resource_method, bind); this->bound_remove_methods.emplace(input_resource_method, bind);
} }
target->connect("tree_exiting", Callable(this, input_resource_method).bind(target, resource), CONNECT_ONE_SHOT);
const Callable &callable = Callable(this, input_resource_method);
if (!target->is_connected("tree_exiting", callable))
target->connect("tree_exiting", callable.bind(target, resource), CONNECT_ONE_SHOT);
} }
void InputHandler::_enable_mouse_capture() void InputHandler::_enable_mouse_capture()
{ {
Input *input = Input::get_singleton(); this->mouse_input_counter++;
input->set_mouse_mode(Input::MOUSE_MODE_CAPTURED); Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
} }
void InputHandler::remove_input_resource(Node *target, InputResource *resource) void InputHandler::remove_input_resource(Node *target, InputResource *resource)
{ {
Input *input = Input::get_singleton();
InputMap *input_map = InputMap::get_singleton(); InputMap *input_map = InputMap::get_singleton();
const TypedArray<InputAction> &input_actions = resource->get_input_actions(); const TypedArray<InputAction> &input_actions = resource->get_input_actions();
const TypedArray<InputAxis> &input_axes = resource->get_input_axes(); const TypedArray<InputAxis> &input_axes = resource->get_input_axes();
for(uint8_t i = 0; i < input_actions.size(); i++) for (uint8_t i = 0; i < input_actions.size(); i++)
{ {
if (const InputAction *action = cast_to<InputAction>(input_actions[i])) if (const InputAction *action = cast_to<InputAction>(input_actions[i]))
{ {
input->action_release(action->get_action_name());
input_map->action_erase_events(action->get_action_name()); input_map->action_erase_events(action->get_action_name());
for(uint8_t s = 0; s < 2; s++)
const StringName &name_prefix = StringName("_on_") + action->get_action_name();
const StringName &callback_name_pressed = name_prefix + input_action_suffixes[0];
const StringName &signal_name_pressed = callback_name_pressed + INPUTHANDLER_SUFFIX_SIGNAL;
const Callable &callable_pressed = Callable(target, callback_name_pressed);
if (resource->has_signal(signal_name_pressed) && resource->is_connected(signal_name_pressed, callable_pressed))
resource->disconnect(signal_name_pressed, callable_pressed);
const StringName &callback_name_released = name_prefix + input_action_suffixes[1];
const StringName &signal_name_released = callback_name_released + INPUTHANDLER_SUFFIX_SIGNAL;
const Callable &callable_released = Callable(target, callback_name_released);
if (target->has_method(callback_name_released))
{ {
const StringName signal_name = StringName("_on_") + action->get_action_name() + input_action_suffixes[s]; target->call(callback_name_released);
if (target->has_method(signal_name)) if (resource->has_signal(signal_name_released) && resource->is_connected(signal_name_released, callable_released))
{ resource->disconnect(signal_name_released, callable_released);
resource->disconnect(signal_name, Callable(target, signal_name));
}
} }
} }
} }
for(uint8_t i = 0; i < input_axes.size(); i++) for (uint8_t i = 0; i < input_axes.size(); i++)
{ {
if (const InputAxis *axis = cast_to<InputAxis>(input_axes[i])) if (const InputAxis *axis = cast_to<InputAxis>(input_axes[i]))
{ {
for(uint8_t s = 0; s < 3; s++) const StringName &callback_name_one = StringName("_on_") + axis->get_axis_name() + this->input_axis_suffixes[0];
const StringName &signal_name_one = callback_name_one + INPUTHANDLER_SUFFIX_SIGNAL;
if (target->has_method(callback_name_one))
{ {
const StringName signal_name = StringName("_on_") + axis->get_axis_name() + this->input_axis_suffixes[s]; if (resource->has_signal(signal_name_one))
if (target->has_method(signal_name)) resource->disconnect(signal_name_one, Callable(target, callback_name_one));
{ if (target->has_method(callback_name_one))
resource->disconnect(signal_name, Callable(target, signal_name)); target->call(callback_name_one, this->get_process_delta_time(), 0.0f);
}
} }
const StringName &callback_name_two = StringName("_on_") + axis->get_axis_name() + this->input_axis_suffixes[1];
const StringName &signal_name_two = callback_name_two + INPUTHANDLER_SUFFIX_SIGNAL;
if (target->has_method(callback_name_two))
{
if (resource->has_signal(signal_name_two))
resource->disconnect(signal_name_two, Callable(target, callback_name_two));
if (target->has_method(callback_name_two))
target->call(callback_name_two, this->get_process_delta_time(), Vector2(0.0f, 0.0f));
}
const StringName &callback_name_three = StringName("_on_") + axis->get_axis_name() + this->input_axis_suffixes[2];
const StringName &signal_name_three = callback_name_three + INPUTHANDLER_SUFFIX_SIGNAL;
if (target->has_method(callback_name_three))
{
if (resource->has_signal(signal_name_three))
resource->disconnect(signal_name_three, Callable(target, callback_name_three));
if (target->has_method(callback_name_three))
target->call(callback_name_three, this->get_process_delta_time(), Vector3(0.0f, 0.0f, 0.0f));
}
const StringName &callback_name_mouse = StringName("_on_") + axis->get_axis_name() + INPUTAXIS_MOUSE_INPUT_SUFFIX;
const StringName &signal_name_mouse = callback_name_three + INPUTHANDLER_SUFFIX_SIGNAL;
if (target->has_method(callback_name_mouse))
{
if (resource->has_signal(signal_name_mouse))
resource->disconnect(signal_name_mouse, Callable(target, callback_name_mouse));
if (target->has_method(callback_name_mouse))
target->call(callback_name_mouse, this->get_process_delta_time(), Vector2(0.0f, 0.0f));
}
/* /*
* This part would be a good, safe precaution to take, but it seems * This part would be a good, safe precaution to take, but it seems
* to cause inputs to stick if an input resource is removed while * to cause inputs to stick if an input resource is removed while
@@ -217,48 +264,58 @@ void InputHandler::remove_input_resource(Node *target, InputResource *resource)
* side effects, but I'm keeping it commented here in case there * side effects, but I'm keeping it commented here in case there
* turns out to be a reason to put it back later. * turns out to be a reason to put it back later.
*/ */
// const StringName &axis_name = axis->get_axis_name(); const StringName &axis_name = axis->get_axis_name();
// const uint8_t &axis_dimensions = axis->get_axis_dimensions(); const uint8_t &axis_dimensions = axis->get_axis_dimensions();
// const float &deadzone = axis->get_deadzone(); if (axis_dimensions >= InputAxis::AXIS_DIMENSIONS::ONE)
// if (axis_dimensions >= InputAxis::AXIS_DIMENSIONS::ONE) {
// { const StringName &left_axis_action = axis_name + INPUTAXIS_LEFT_SUFFIX;
// const StringName &left_axis_action = axis_name + INPUTAXIS_LEFT_SUFFIX; const StringName &right_axis_action = axis_name + INPUTAXIS_RIGHT_SUFFIX;
// const StringName &right_axis_action = axis_name + INPUTAXIS_RIGHT_SUFFIX;
input->action_release(left_axis_action);
// input_map->action_erase_events(left_axis_action); input->action_release(right_axis_action);
// input_map->action_erase_events(right_axis_action);
// } input_map->action_erase_events(left_axis_action);
input_map->action_erase_events(right_axis_action);
}
// if (axis_dimensions >= InputAxis::AXIS_DIMENSIONS::TWO) if (axis_dimensions >= InputAxis::AXIS_DIMENSIONS::TWO)
// { {
// const StringName &back_axis_action = axis_name + INPUTAXIS_BACK_SUFFIX; const StringName &back_axis_action = axis_name + INPUTAXIS_BACK_SUFFIX;
// const StringName &forward_axis_action = axis_name + INPUTAXIS_FORWARD_SUFFIX; const StringName &forward_axis_action = axis_name + INPUTAXIS_FORWARD_SUFFIX;
// input_map->action_erase_events(back_axis_action); input->action_release(back_axis_action);
// input_map->action_erase_events(forward_axis_action); input->action_release(forward_axis_action);
// }
input_map->action_erase_events(back_axis_action);
input_map->action_erase_events(forward_axis_action);
}
if (axis_dimensions >= InputAxis::AXIS_DIMENSIONS::THREE)
{
const StringName &down_axis_action = axis_name + INPUTAXIS_DOWN_SUFFIX;
const StringName &up_axis_action = axis_name + INPUTAXIS_UP_SUFFIX;
input->action_release(down_axis_action);
input->action_release(up_axis_action);
input_map->action_erase_events(down_axis_action);
input_map->action_erase_events(up_axis_action);
}
// if (axis_dimensions >= InputAxis::AXIS_DIMENSIONS::THREE)
// {
// const StringName &down_axis_action = axis_name + INPUTAXIS_DOWN_SUFFIX;
// const StringName &up_axis_action = axis_name + INPUTAXIS_UP_SUFFIX;
// input_map->action_erase_events(down_axis_action);
// input_map->action_erase_events(up_axis_action);
// }
if (axis->get_include_mouse()) if (axis->get_include_mouse())
{ {
Engine *engine = Engine::get_singleton();
this->call_deferred("_disable_mouse_capture"); this->call_deferred("_disable_mouse_capture");
} }
} }
} }
this->active_resources.erase(resource); this->active_resources.erase(resource);
} }
void InputHandler::_disable_mouse_capture() void InputHandler::_disable_mouse_capture()
{ {
Input *input = Input::get_singleton(); mouse_input_counter--;
input->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); if (mouse_input_counter <= 0)
{
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
}
} }
+2
View File
@@ -39,6 +39,8 @@ private:
const StringName input_axis_suffixes[3] = { INPUTAXIS_ONE_DIMENSIONAL_SUFFIX, INPUTAXIS_TWO_DIMENSIONAL_SUFFIX, INPUTAXIS_THREE_DIMENSIONAL_SUFFIX }; const StringName input_axis_suffixes[3] = { INPUTAXIS_ONE_DIMENSIONAL_SUFFIX, INPUTAXIS_TWO_DIMENSIONAL_SUFFIX, INPUTAXIS_THREE_DIMENSIONAL_SUFFIX };
std::map<const StringName, MethodBind*> bound_remove_methods; std::map<const StringName, MethodBind*> bound_remove_methods;
int8_t mouse_input_counter = 0;
// Godot boilerplate below // Godot boilerplate below
protected: protected:
+2 -1
View File
@@ -165,9 +165,10 @@ void SceneLoader::load_scene(const StringName path, Callable callback)
if (path.is_empty()) if (path.is_empty())
return; return;
if (!this->resource_loader) return;
if (this->resource_loader->load_threaded_request(path, "PackedScene", true) != Error::OK) if (this->resource_loader->load_threaded_request(path, "PackedScene", true) != Error::OK)
{ {
UtilityFunctions::printerr("Scene ", path, " does not exist."); PRINT_ERROR("SceneLoader", "Scene ", path, " does not exist.");
return; return;
} }