mirror of
https://github.com/zhenyan121/Cubed.git
synced 2026-08-08 17:57:02 +08:00
* build(deps): add assimp library as dependency * feat(render): add model loading and rendering pipeline * refactor(render): rename depth player shaders to depth model and clean up * build: add EnTT library * feat(entity): add ECS-based entity rendering * feat(render): add shadow pass for entity models * refactor(render): unify model and player rendering with single shader pipeline * refactor(collision): convert AABB to center-half representation and migrate player data to ECS * refactor(gameplay): add base classes Chunk and World for shared logic * feat(gameplay): implement entity movement system with collision detection - Add Velocity and HitBoxes components to entity - Introduce HitboxManager for loading per-entity collision AABBs from JSON - Create MoveSystem with per-axis collision handling - Move get_block_aabb to base World class and add virtual get_per_tick_time - Remove static get_block_aabb from ClientWorld; use member m_per_tick_time for tick duration * fix(gameplay): correct hitbox insertion in HitboxManager::load * build: remove entt library * refactor(gameplay): replace entt components with SparseVector for player data Refactor client world to use a custom SparseVector for player data instead of entt registry. Consolidate Transform, ViewAngles, and related structs into Position, Orientation, WalkPose. Introduce PlayerData and PlayerRenderData. Remove the unused move_system.cpp. Unify player render and shadow render into a single function. * feat(render): add model ID system with concurrent lookup and namespace-based loading - Extract `ModelID` and `Model` struct to new `model.hpp` - Replace `std::unordered_map` with `tbb::concurrent_hash_map` for thread safety - Add `get_model(ModelID)`, `get_model_id`, `get_model_name` methods - Parse model names in `namespace:name` format to construct asset paths - Update `load_model` to accept `string_view` and use ID-based management * refactor(gameplay): extract movement, gravity, orientation, and walk pose into structs * refactor(gameplay): extract Entity base class from ClientPlayer Move position, walk pose, velocity, orientation, movement, and gravity fields and their accessors into a new Entity base class. ClientPlayer now inherits from Entity, removing duplicated members. Also update velocity handling to use 3D vector per axis and adjust related logic. * feat(player): split max speed into horizontal/vertical, set spawn pos * refactor: move movement logic into SpeedSystem and Entity components * refactor(gameplay): extract physics and collision from ClientPlayer into PhysicalSystem Move per-axis collision detection and move distance calculation to new PhysicalSystem. Move SpeedSystem implementation from inline header to separate .cpp file. Add const accessors to Entity. Replace inline AABB helper with HitboxManager registration of player hitbox using new PLAYER_SIZE constant. Remove obsolete members and functions from ClientPlayer. * refactor(gameplay): integrate model and hitbox ID system into Entity - Introduce HitboxID, EntityID, and ModelID types for safer ID-based lookups - Replace AABB struct with Hitbox (includes HitboxID) - Convert ModelManager and HitboxManager to singletons with Handle structs - Update Entity to store IDs for model and hitbox, removing direct references - Reorganize creature model assets into subdirectories per entity type - Add player model (player.glb) and collision data for pig - Remove ModelManager dependency from App and Renderer - Add namespace parsing utility for asset paths - Mark sparse_vector::insert() with [[nodiscard]] * build: add entt library * refactor(gameplay): rename ClientPlayer to LocalPlayer * refactor(gameplay): separate player logic into manager and ECS components * feat(gameplay): add entity managers and refactor to ECS components * refactor(gameplay): replace client thread with timer-based system and add entity manager * feat(gameplay): implement entity system with concurrent task handling and fix model loading * feat(gameplay): add entity destruction support * feat(entity): add client-to-server entity creation and destruction requests Extend the network protocol with `C2SEntityCreateRequest` and `C2SEntityDestoryRequest` packets. Refactor entity managers to split public client-facing create/destroy methods that send requests over the network, from internal handlers that process received packets. Add utility functions for converting protobuf Vec3 to glm::vec3. * feat(gameplay): implement entity update packets Add S2CEntityUpdate to sync entity positions from server to client, including update handling in the client entity manager and server-side AI updates. * feat(ai): add wander AI system with move boost Add AIBase and WanderAITag components, a WanderAISystem, and a MoveBoost component to control wandering behavior. Replace the old MoveState with MoveBoost and include a horizontal random direction helper. * refactor(ecs): move entity physics to tick-based systems Update PhysicalSystem and SpeedSystem to operate on entt::registry instead of individual components. Add TickVelocity for server creatures so movement is calculated per tick without frame delta time. LocalPlayer now implements its own client-side physics with collision detection. * feat(gameplay): add server-side entity movement and AI Refactor LocalPlayer::update_physical to operate on a passed position, and run speed, physical, and wander AI systems in ServerEntityManager. * feat(gameplay): add pig wander AI and refine speed physics * feat(server): send entity position updates to all sessions * fix: correct velocity clamping and hitbox loading Preserve sign when clamping velocity; negative velocities now clamp to zero instead of flipping direction. Support loading hitbox definitions from JSON arrays and objects. Tune pig entity movement, spawn height, and wander probabilities. * feat(creatures): refine pig movement physics Add movement constants for pigs and switch deceleration to per-axis friction so creatures stop naturally. Extend wander boost duration for smoother behavior. * feat(physics): implement step-up for horizontal collisions * feat: sync entity direction and rotate models accordingly Move direction into the transform component and include it in server-to-client entity updates. Client now sets transform direction from the network message and uses it to compute yaw for model rotation, so entities visually face their movement direction. Refactor net_utils to support arbitrary Vec3 fields. * feat(render): interpolate entity transforms for rendering Add RenderTransform component to smooth position/direction updates and use it in entity and shadow passes. * fix(server_world): send time before entity updates * build: replace nlohmann json with rapidjson * refactor(json): migrate from nlohmann to rapidjson Replace nlohmann::json with rapidjson across localization, hitbox manager, server world, and sensitive filter. Add json_utils helper for converting rapidjson documents to maps, and improve parse error handling. * feat(item): add item manager with JSON asset loading Implement ItemManager to load and query item definitions from assets/item JSON files. Add ItemData struct, item asset metadata, CMake source registration, and initialize the manager during app startup. Also add AGENTS.md repository guidelines. * refactor(item): decouple items from block types The item system now supports an ItemKind and property, allowing item JSON to declare a type instead of assuming every item is a block. BlockManager was moved to its own header, redesigned around concurrent hash maps, and exposes id_from_name(). Texture and UI code now key items by ItemID, while block placement resolves the block type from the item registry. * fix(gameplay): use inline const for static EMPTY members Use inline const for static EMPTY members to avoid ODR and linker issues. Add missing block_manager.hpp includes in gameplay sources. * fix: stabilize block item registration and display Store item names as owned strings in ItemManager, set block type property for block items, validate item kind before placement, and handle items without textures gracefully in inventory UI. * feat: add pig spawn egg item Add pig spawn egg asset and texture, parse spawn egg item kind and creature property, and spawn the configured entity when used on an empty block. Also fix item texture loading to use actual image dimensions and update selected item UI sizing. * refactor(gameplay): update systems per entity with chunk check Refactor server entity update flow to process entities individually, skipping those whose chunk is not loaded. System update methods now accept a single entity instead of iterating the full registry view, and `ServerWorld::get_chunk_ref_count` is added to determine if an entity's chunk is active. * perf(render): skip entities outside loaded chunks * feat: add --direct-enter option to skip to world scene Support a new CLI flag that launches the app directly into the world scene. If no IP is provided, it starts a local server on the specified port and connects to 127.0.0.1; otherwise it connects to the given IP. With this flag enabled, a port must be specified via -p. Also expose SceneManager::push as public so scenes can be pushed immediately when bypassing the normal menu flow. * refactor(localization): switch block translations to item naming Remove the `name_key` field from block definitions and use item-based localization keys (`item.*.name`) for inventory display. Item data now stores the localized name at load time. * feat(gameplay): spawn creatures during chunk generation Add creature spawning to chunk generation with a configurable SpawnConfig, including a default pig spawn. Spawning occurs in the final generation phase and registers entities through the server world's entity manager. Also destroy entities when their chunk is unloaded to prevent orphaned entities and expose the entity manager from ServerWorld. * feat(gameplay): add run mode based thread pool config Introduce RunMode enum and thread pool sizing helpers for client, server, and hybrid modes. Add compute pool to server world and pass mode through server/client initialization. * perf(server): parallelize entity update loop Use parallel_do to process entities concurrently via the compute pool. Switch get_all_session to a thread-safe tbb::concurrent_vector and make ChunkEntity's ref_count atomic to avoid data races. Also remove the debug pig spawn from world init. * feat(creatures): animate creature walk cycles Add a Gait component synchronized over the network and procedural animation for model nodes. Load animation parameters from assets/model/creature/pig/animation.json and apply leg swing, body bob, and head motion based on gait. Refactor Gait into its own header for reuse. * fix(gameplay): make entity interpolation frame-rate independent * perf(render): batch model rendering with instancing Replaces per-entity draw calls with instanced rendering for both main and shadow passes. Each model's node hierarchy is flattened once and instance matrices are updated per frame, reducing draw calls and CPU overhead. * refactor(render): build entity instance buffers once per frame Move instance matrix upload into build_vertices and use a precomputed instance data map for both shadow and color passes, avoiding duplicate GPU buffer updates. * perf(gameplay): batch entity updates into single packet Aggregate per-entity update messages into S2CEntityUpdateBatch and broadcast once per tick. Reuse serialized packets in several broadcast loops to avoid repeated make_packet calls. * fix: correct thread count and shadow projection uniform - Add reserved client thread count to client threads in server generation calculation. - Set projection matrix uniform only for non-shadow rendering. * feat(ecs): add entity type separation and creature limits Replace generic entity creation with typed creatures and items. Rename `add_entity` to `add_creature`, enforce per-player creature cap, and track entity/creature totals for metrics. Expose run mode to dev panel and show new counts. * perf(render): frustum cull entities before instance building Add frustum culling to entity instance data collection using AABB vs camera frustum planes. Pass renderer into get_instances_data_map to compute MVP and extract planes. Also add "Rendered Entities" debug counter for visibility. * feat(audio): add ambient pig sounds Add pig call audio with randomized timing, triggered by proximity to the player as 3D positional sound. * feat(client-entity): use snapshot history for entity interpolation Replace exponential smoothing with a buffered snapshot system. Each entity keeps a deque of position/direction snapshots with timestamps; the render transform is interpolated at a fixed 100 ms render delay to hide network jitter. Snapshots are capped to 16 entries. * refactor(hitbox): move player hitbox definition to JSON asset * feat(client_player): use snapshot interpolation for remote players Replace exponential position smoothing with snapshot interpolation. Remote player transforms are rendered from a delayed snapshot history, using linear interpolation for position and shortest-path interpolation for yaw/pitch. A 100 ms render delay compensates for network tick rate.
438 lines
18 KiB
C++
438 lines
18 KiB
C++
#ifndef ENTT_ENTITY_ORGANIZER_HPP
|
|
#define ENTT_ENTITY_ORGANIZER_HPP
|
|
|
|
#include "../core/type_info.hpp"
|
|
#include "../core/type_traits.hpp"
|
|
#include "../core/utility.hpp"
|
|
#include "../graph/adjacency_matrix.hpp"
|
|
#include "../graph/flow.hpp"
|
|
#include "../stl/cstddef.hpp"
|
|
#include "../stl/type_traits.hpp"
|
|
#include "../stl/utility.hpp"
|
|
#include "../stl/vector.hpp"
|
|
#include "fwd.hpp"
|
|
#include "helper.hpp"
|
|
|
|
namespace entt {
|
|
|
|
/*! @cond ENTT_INTERNAL */
|
|
namespace internal {
|
|
|
|
template<typename>
|
|
struct is_view: stl::false_type {};
|
|
|
|
template<typename... Args>
|
|
struct is_view<basic_view<Args...>>: stl::true_type {};
|
|
|
|
template<typename Type>
|
|
inline constexpr bool is_view_v = is_view<Type>::value;
|
|
|
|
template<typename>
|
|
struct is_group: stl::false_type {};
|
|
|
|
template<typename... Args>
|
|
struct is_group<basic_group<Args...>>: stl::true_type {};
|
|
|
|
template<typename Type>
|
|
inline constexpr bool is_group_v = is_group<Type>::value;
|
|
|
|
template<typename Type, typename Override>
|
|
struct unpack_type {
|
|
using ro = stl::conditional_t<
|
|
type_list_contains_v<Override, const Type> || (stl::is_const_v<Type> && !type_list_contains_v<Override, stl::remove_const_t<Type>>),
|
|
type_list<stl::remove_const_t<Type>>,
|
|
type_list<>>;
|
|
|
|
using rw = stl::conditional_t<
|
|
type_list_contains_v<Override, stl::remove_const_t<Type>> || (!stl::is_const_v<Type> && !type_list_contains_v<Override, const Type>),
|
|
type_list<Type>,
|
|
type_list<>>;
|
|
};
|
|
|
|
template<typename... Args, typename... Override>
|
|
struct unpack_type<basic_registry<Args...>, type_list<Override...>> {
|
|
using ro = type_list<>;
|
|
using rw = type_list<>;
|
|
};
|
|
|
|
template<typename... Args, typename... Override>
|
|
struct unpack_type<const basic_registry<Args...>, type_list<Override...>>
|
|
: unpack_type<basic_registry<Args...>, type_list<Override...>> {};
|
|
|
|
template<typename... Get, typename... Exclude, typename... Override>
|
|
struct unpack_type<basic_view<get_t<Get...>, exclude_t<Exclude...>>, type_list<Override...>> {
|
|
using ro = type_list_cat_t<type_list<typename Exclude::element_type...>, typename unpack_type<constness_as_t<typename Get::element_type, Get>, type_list<Override...>>::ro...>;
|
|
using rw = type_list_cat_t<typename unpack_type<constness_as_t<typename Get::element_type, Get>, type_list<Override...>>::rw...>;
|
|
};
|
|
|
|
template<typename... Get, typename... Exclude, typename... Override>
|
|
struct unpack_type<const basic_view<get_t<Get...>, exclude_t<Exclude...>>, type_list<Override...>>
|
|
: unpack_type<basic_view<get_t<Get...>, exclude_t<Exclude...>>, type_list<Override...>> {};
|
|
|
|
template<typename... Owned, typename... Get, typename... Exclude, typename... Override>
|
|
struct unpack_type<basic_group<owned_t<Owned...>, get_t<Get...>, exclude_t<Exclude...>>, type_list<Override...>> {
|
|
using ro = type_list_cat_t<type_list<typename Exclude::element_type...>, typename unpack_type<constness_as_t<typename Get::element_type, Get>, type_list<Override...>>::ro..., typename unpack_type<constness_as_t<typename Owned::element_type, Owned>, type_list<Override...>>::ro...>;
|
|
using rw = type_list_cat_t<typename unpack_type<constness_as_t<typename Get::element_type, Get>, type_list<Override...>>::rw..., typename unpack_type<constness_as_t<typename Owned::element_type, Owned>, type_list<Override...>>::rw...>;
|
|
};
|
|
|
|
template<typename... Owned, typename... Get, typename... Exclude, typename... Override>
|
|
struct unpack_type<const basic_group<owned_t<Owned...>, get_t<Get...>, exclude_t<Exclude...>>, type_list<Override...>>
|
|
: unpack_type<basic_group<owned_t<Owned...>, get_t<Get...>, exclude_t<Exclude...>>, type_list<Override...>> {};
|
|
|
|
template<typename, typename, typename>
|
|
struct resource_traits;
|
|
|
|
template<typename Registry, typename... Args, typename... Req>
|
|
struct resource_traits<Registry, type_list<Args...>, type_list<Req...>> {
|
|
using args = type_list<stl::remove_const_t<Args>...>;
|
|
using ro = type_list_cat_t<typename unpack_type<Args, type_list<Req...>>::ro..., typename unpack_type<Req, type_list<>>::ro...>;
|
|
using rw = type_list_cat_t<typename unpack_type<Args, type_list<Req...>>::rw..., typename unpack_type<Req, type_list<>>::rw...>;
|
|
static constexpr auto sync_point = (stl::is_same_v<Args, Registry> || ...);
|
|
};
|
|
|
|
template<typename Registry, typename... Req, typename Ret, typename... Args>
|
|
resource_traits<Registry, type_list<stl::remove_reference_t<Args>...>, type_list<Req...>> free_function_to_resource_traits(Ret (*)(Args...));
|
|
|
|
template<typename Registry, typename... Req, typename Ret, typename Type, typename... Args>
|
|
resource_traits<Registry, type_list<stl::remove_reference_t<Args>...>, type_list<Req...>> constrained_function_to_resource_traits(Ret (*)(Type &, Args...));
|
|
|
|
template<typename Registry, typename... Req, typename Ret, typename Class, typename... Args>
|
|
resource_traits<Registry, type_list<stl::remove_reference_t<Args>...>, type_list<Req...>> constrained_function_to_resource_traits(Ret (Class::*)(Args...));
|
|
|
|
template<typename Registry, typename... Req, typename Ret, typename Class, typename... Args>
|
|
resource_traits<Registry, type_list<stl::remove_reference_t<Args>...>, type_list<Req...>> constrained_function_to_resource_traits(Ret (Class::*)(Args...) const);
|
|
|
|
} // namespace internal
|
|
/*! @endcond */
|
|
|
|
/**
|
|
* @brief Utility class for creating a static task graph.
|
|
*
|
|
* This class offers minimal support (but sufficient in many cases) for creating
|
|
* an execution graph from functions and their requirements on resources.<br/>
|
|
* Note that the resulting tasks aren't executed in any case. This isn't the
|
|
* goal of the tool. Instead, they are returned to the user in the form of a
|
|
* graph that allows for safe execution.
|
|
*
|
|
* @tparam Registry Basic registry type.
|
|
*/
|
|
template<typename Registry>
|
|
class basic_organizer final {
|
|
using callback_type = void(const void *, Registry &);
|
|
using prepare_type = void(Registry &);
|
|
using dependency_type = stl::size_t(const bool, const type_info **, const stl::size_t);
|
|
|
|
struct vertex_data final {
|
|
stl::size_t ro_count{};
|
|
stl::size_t rw_count{};
|
|
const char *name{};
|
|
const void *payload{};
|
|
callback_type *callback{};
|
|
dependency_type *dependency{};
|
|
prepare_type *prepare{};
|
|
const type_info *info{};
|
|
};
|
|
|
|
template<typename Type>
|
|
[[nodiscard]] static decltype(auto) extract(Registry ®) {
|
|
if constexpr(stl::is_same_v<Type, Registry>) {
|
|
return reg;
|
|
} else if constexpr(internal::is_view_v<Type>) {
|
|
return static_cast<Type>(as_view{reg});
|
|
} else if constexpr(internal::is_group_v<Type>) {
|
|
return static_cast<Type>(as_group{reg});
|
|
} else {
|
|
return reg.ctx().template emplace<stl::remove_reference_t<Type>>();
|
|
}
|
|
}
|
|
|
|
template<typename... Args>
|
|
[[nodiscard]] static auto to_args(Registry ®, type_list<Args...>) {
|
|
return stl::tuple<decltype(extract<Args>(reg))...>(extract<Args>(reg)...);
|
|
}
|
|
|
|
template<typename... Type>
|
|
[[nodiscard]] static stl::size_t fill_dependencies(type_list<Type...>, [[maybe_unused]] const type_info **buffer, [[maybe_unused]] const stl::size_t count) {
|
|
if constexpr(sizeof...(Type) == 0u) {
|
|
return {};
|
|
} else {
|
|
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays, modernize-avoid-c-arrays)
|
|
const type_info *info[]{&type_id<Type>()...};
|
|
const auto length = count < sizeof...(Type) ? count : sizeof...(Type);
|
|
|
|
for(stl::size_t pos{}; pos < length; ++pos) {
|
|
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
|
|
buffer[pos] = info[pos];
|
|
}
|
|
|
|
return length;
|
|
}
|
|
}
|
|
|
|
template<typename... RO, typename... RW>
|
|
void track_dependencies(stl::size_t index, const bool sync_point, type_list<RO...>, type_list<RW...>) {
|
|
builder.bind(static_cast<id_type>(index));
|
|
builder.set(type_hash<Registry>::value(), sync_point || (sizeof...(RO) + sizeof...(RW) == 0u));
|
|
(builder.ro(type_hash<RO>::value()), ...);
|
|
(builder.rw(type_hash<RW>::value()), ...);
|
|
}
|
|
|
|
public:
|
|
/*! Basic registry type. */
|
|
using registry_type = Registry;
|
|
/*! @brief Underlying entity identifier. */
|
|
using entity_type = registry_type::entity_type;
|
|
/*! @brief Unsigned integer type. */
|
|
using size_type = stl::size_t;
|
|
/*! @brief Raw task function type. */
|
|
using function_type = callback_type;
|
|
|
|
/*! @brief Vertex type of a task graph defined as an adjacency list. */
|
|
struct vertex {
|
|
/**
|
|
* @brief Constructs a vertex of the task graph.
|
|
* @param data The data associated with the vertex.
|
|
* @param from List of in-edges of the vertex.
|
|
* @param to List of out-edges of the vertex.
|
|
*/
|
|
vertex(vertex_data data, stl::vector<stl::size_t> from, stl::vector<stl::size_t> to)
|
|
: node{stl::move(data)},
|
|
in{stl::move(from)},
|
|
out{stl::move(to)} {}
|
|
|
|
/**
|
|
* @brief Fills a buffer with the type info objects for the writable
|
|
* resources of a vertex.
|
|
* @param buffer A buffer pre-allocated by the user.
|
|
* @param length The length of the user-supplied buffer.
|
|
* @return The number of type info objects written to the buffer.
|
|
*/
|
|
[[nodiscard]] size_type ro_dependency(const type_info **buffer, const stl::size_t length) const noexcept {
|
|
return node.dependency(false, buffer, length);
|
|
}
|
|
|
|
/**
|
|
* @brief Fills a buffer with the type info objects for the read-only
|
|
* resources of a vertex.
|
|
* @param buffer A buffer pre-allocated by the user.
|
|
* @param length The length of the user-supplied buffer.
|
|
* @return The number of type info objects written to the buffer.
|
|
*/
|
|
[[nodiscard]] size_type rw_dependency(const type_info **buffer, const stl::size_t length) const noexcept {
|
|
return node.dependency(true, buffer, length);
|
|
}
|
|
|
|
/**
|
|
* @brief Returns the number of read-only resources of a vertex.
|
|
* @return The number of read-only resources of the vertex.
|
|
*/
|
|
[[nodiscard]] size_type ro_count() const noexcept {
|
|
return node.ro_count;
|
|
}
|
|
|
|
/**
|
|
* @brief Returns the number of writable resources of a vertex.
|
|
* @return The number of writable resources of the vertex.
|
|
*/
|
|
[[nodiscard]] size_type rw_count() const noexcept {
|
|
return node.rw_count;
|
|
}
|
|
|
|
/**
|
|
* @brief Checks if a vertex is also a top-level one.
|
|
* @return True if the vertex is a top-level one, false otherwise.
|
|
*/
|
|
[[nodiscard]] bool top_level() const noexcept {
|
|
return in.empty();
|
|
}
|
|
|
|
/**
|
|
* @brief Returns a type info object associated with a vertex.
|
|
* @return A properly initialized type info object.
|
|
*/
|
|
[[nodiscard]] const type_info &info() const noexcept {
|
|
return *node.info;
|
|
}
|
|
|
|
/**
|
|
* @brief Returns a user defined name associated with a vertex, if any.
|
|
* @return The user defined name associated with the vertex, if any.
|
|
*/
|
|
[[nodiscard]] const char *name() const noexcept {
|
|
return node.name;
|
|
}
|
|
|
|
/**
|
|
* @brief Returns the function associated with a vertex.
|
|
* @return The function associated with the vertex.
|
|
*/
|
|
[[nodiscard]] function_type *callback() const noexcept {
|
|
return node.callback;
|
|
}
|
|
|
|
/**
|
|
* @brief Returns the payload associated with a vertex, if any.
|
|
* @return The payload associated with the vertex, if any.
|
|
*/
|
|
[[nodiscard]] const void *data() const noexcept {
|
|
return node.payload;
|
|
}
|
|
|
|
/**
|
|
* @brief Returns the list of in-edges of a vertex.
|
|
* @return The list of in-edges of a vertex.
|
|
*/
|
|
[[nodiscard]] const stl::vector<stl::size_t> &in_edges() const noexcept {
|
|
return in;
|
|
}
|
|
|
|
/**
|
|
* @brief Returns the list of out-edges of a vertex.
|
|
* @return The list of out-edges of a vertex.
|
|
*/
|
|
[[nodiscard]] const stl::vector<stl::size_t> &out_edges() const noexcept {
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* @brief Prepares a registry and assures that all required resources
|
|
* are properly instantiated before using them.
|
|
* @param reg A valid registry.
|
|
*/
|
|
void prepare(registry_type ®) const {
|
|
node.prepare ? node.prepare(reg) : void();
|
|
}
|
|
|
|
private:
|
|
vertex_data node;
|
|
stl::vector<stl::size_t> in;
|
|
stl::vector<stl::size_t> out;
|
|
};
|
|
|
|
/**
|
|
* @brief Adds a free function to the task list.
|
|
* @tparam Candidate Function to add to the task list.
|
|
* @tparam Req Additional requirements and/or override resource access mode.
|
|
* @param name Optional name to associate with the task.
|
|
*/
|
|
template<auto Candidate, typename... Req>
|
|
void emplace(const char *name = nullptr) {
|
|
using resource_type = decltype(internal::free_function_to_resource_traits<registry_type, Req...>(Candidate));
|
|
|
|
callback_type *callback = +[](const void *, registry_type ®) {
|
|
stl::apply(Candidate, to_args(reg, typename resource_type::args{}));
|
|
};
|
|
|
|
vertex_data vdata{
|
|
resource_type::ro::size,
|
|
resource_type::rw::size,
|
|
name,
|
|
nullptr,
|
|
callback,
|
|
+[](const bool rw, const type_info **buffer, const stl::size_t length) { return rw ? fill_dependencies(typename resource_type::rw{}, buffer, length) : fill_dependencies(typename resource_type::ro{}, buffer, length); },
|
|
+[](registry_type ®) { void(to_args(reg, typename resource_type::args{})); },
|
|
&type_id<stl::integral_constant<decltype(Candidate), Candidate>>()};
|
|
|
|
track_dependencies(vertices.size(), resource_type::sync_point, typename resource_type::ro{}, typename resource_type::rw{});
|
|
vertices.push_back(stl::move(vdata));
|
|
}
|
|
|
|
/**
|
|
* @brief Adds a free function with payload or a member function with an
|
|
* instance to the task list.
|
|
* @tparam Candidate Function or member to add to the task list.
|
|
* @tparam Req Additional requirements and/or override resource access mode.
|
|
* @tparam Type Type of class or type of payload.
|
|
* @param value_or_instance A valid object that fits the purpose.
|
|
* @param name Optional name to associate with the task.
|
|
*/
|
|
template<auto Candidate, typename... Req, typename Type>
|
|
void emplace(Type &value_or_instance, const char *name = nullptr) {
|
|
using resource_type = decltype(internal::constrained_function_to_resource_traits<registry_type, Req...>(Candidate));
|
|
|
|
callback_type *callback = +[](const void *payload, registry_type ®) {
|
|
Type *curr = static_cast<Type *>(const_cast<constness_as_t<void, Type> *>(payload));
|
|
stl::apply(Candidate, stl::tuple_cat(stl::forward_as_tuple(*curr), to_args(reg, typename resource_type::args{})));
|
|
};
|
|
|
|
vertex_data vdata{
|
|
resource_type::ro::size,
|
|
resource_type::rw::size,
|
|
name,
|
|
&value_or_instance,
|
|
callback,
|
|
+[](const bool rw, const type_info **buffer, const stl::size_t length) { return rw ? fill_dependencies(typename resource_type::rw{}, buffer, length) : fill_dependencies(typename resource_type::ro{}, buffer, length); },
|
|
+[](registry_type ®) { void(to_args(reg, typename resource_type::args{})); },
|
|
&type_id<stl::integral_constant<decltype(Candidate), Candidate>>()};
|
|
|
|
track_dependencies(vertices.size(), resource_type::sync_point, typename resource_type::ro{}, typename resource_type::rw{});
|
|
vertices.push_back(stl::move(vdata));
|
|
}
|
|
|
|
/**
|
|
* @brief Adds an user defined function with optional payload to the task
|
|
* list.
|
|
* @tparam Req Additional requirements and/or override resource access mode.
|
|
* @param func Function to add to the task list.
|
|
* @param payload User defined arbitrary data.
|
|
* @param name Optional name to associate with the task.
|
|
*/
|
|
template<typename... Req>
|
|
void emplace(function_type *func, const void *payload = nullptr, const char *name = nullptr) {
|
|
using resource_type = internal::resource_traits<registry_type, type_list<>, type_list<Req...>>;
|
|
track_dependencies(vertices.size(), true, typename resource_type::ro{}, typename resource_type::rw{});
|
|
|
|
vertex_data vdata{
|
|
resource_type::ro::size,
|
|
resource_type::rw::size,
|
|
name,
|
|
payload,
|
|
func,
|
|
+[](const bool rw, const type_info **buffer, const stl::size_t length) { return rw ? fill_dependencies(typename resource_type::rw{}, buffer, length) : fill_dependencies(typename resource_type::ro{}, buffer, length); },
|
|
nullptr,
|
|
&type_id<void>()};
|
|
|
|
vertices.push_back(stl::move(vdata));
|
|
}
|
|
|
|
/**
|
|
* @brief Generates a task graph for the current content.
|
|
* @return The adjacency list of the task graph.
|
|
*/
|
|
[[nodiscard]] stl::vector<vertex> graph() const {
|
|
stl::vector<vertex> adjacency_list{};
|
|
adjacency_list.reserve(vertices.size());
|
|
|
|
for(auto adjacency_matrix = builder.graph(); auto curr: adjacency_matrix.vertices()) {
|
|
stl::vector<stl::size_t> in{};
|
|
stl::vector<stl::size_t> out{};
|
|
|
|
for(auto &&edge: adjacency_matrix.in_edges(curr)) {
|
|
in.push_back(edge.first);
|
|
}
|
|
|
|
for(auto &&edge: adjacency_matrix.out_edges(curr)) {
|
|
out.push_back(edge.second);
|
|
}
|
|
|
|
adjacency_list.emplace_back(vertices[curr], stl::move(in), stl::move(out));
|
|
}
|
|
|
|
return adjacency_list;
|
|
}
|
|
|
|
/*! @brief Erases all elements from a container. */
|
|
void clear() {
|
|
builder.clear();
|
|
vertices.clear();
|
|
}
|
|
|
|
private:
|
|
stl::vector<vertex_data> vertices;
|
|
flow builder;
|
|
};
|
|
|
|
} // namespace entt
|
|
|
|
#endif
|