使用 serde,是否可以反序列化为实现类型的结构?
Using serde, is it possible to deserialize to a struct that implements a type?
我正在构建一个 rogue-like,我已经让数据加载器工作并且部分 ECS 工作(从头开始构建)。数据存储在 .yml
文件中,用于描述游戏中的事物(在本例中为生物)以及这些事物具有的特征,例如:
---
orc:
feature_packs:
- physical
- basic_identifiers_mob
features:
- component: char
initial_value: T
goblin:
feature_packs:
- physical
- basic_identifiers_mob
features:
- component: char
initial_value: t
如您所见,描述了两种生物,地精和兽人,它们都拥有两个功能包(功能组),还拥有一个 char
功能,用于描述它们的外观喜欢玩家。
initial_value
字段可以是字符串、整数、浮点数、布尔值、范围等,具体取决于组件需要什么,这将指示组件可能具有的值或可能的值当组件在实体 building/creation.
期间生成时
问题是我不知道如何在遍历功能时,select 基于组件名称的结构,例如,select Char
"char"
功能的结构。
为了更好地描述我的意思,我用我更容易理解的语言写了一个例子,Ruby:
data_manager = function_that_loads_data('folder_path')
Entity_Manager.build(:mob, :orc, data_manager)
class Entity_Manager
class << self
attr_accessor :entities, :components
end
def self.build(entity_type, template_name, data_manager)
template = data_manager[entity_type][template_name]
entity_id = generate_unique_id
entities[entity_id] = Entity.new(entity_id, components: template.components.keys)
template.components.each do |component|
components[component.name][entity_id] =
Components.get(component.name).new(component.initial_value) # <= This part, how do I do the equivalent in rust, a function that will return or allow me to get or create a struct based on the value of a string variable
end
end
end
现在 serde 是我所知道的唯一似乎能够读取文本数据并将其转换为数据的东西,因此为此目的
如何使用 serde(或更合适的非 serde 使用解决方案)获取功能的名称并检索正确的结构,所有这些都实现了一个类型?
顺便说一下,我尽量不使用的一个解决方案是一个巨大的匹配语句。
我的作品的 repo 是 here
- Data manager - 加载和管理加载到游戏中的数据
- Entity manager - 管理实体和组件(不支持位密钥 atm)
- Entity Builder - 将使用来自数据管理器的数据构建实体的位置(这是我目前遇到的问题)
- Components - 简单组件列表
我想避免的是做这样的事情:
pub fn get(comp_name: &String) -> impl Component {
match comp_name.as_ref() {
"kind" => Kind,
"location" => Location,
"name" => Name,
"position" => Position,
"char" => Char,
}
}
因为它不是真正可维护的,虽然宏会有很大帮助,但我不是很擅长那些 atm,它甚至不起作用,rust 一直认为我正在尝试初始化类型,当我只是想要 return 全部将实现的几种可能类型之一 Component
编辑:因为看起来我不够清楚:
- 我不是要将游戏对象加载到游戏中,而是要加载 模板
- 我正在使用那些 模板 来生成将在游戏过程中存在的实体
- 我已经可以按以下结构将我想要的数据加载到游戏中:
pub enum InitialValue {
Char(char),
String(String),
Int(i32),
Float(f32),
Bool(bool),
Range(Range<i32>),
Point((i32,i32))
}
impl InitialValue {
pub fn unwrap_char(&self) -> &char {
match &self {
InitialValue::Char(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_string(&self) -> &String {
match &self {
InitialValue::String(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_int(&self) -> &i32 {
match &self {
InitialValue::Int(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_float(&self) -> &f32 {
match &self {
InitialValue::Float(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_bool(&self) -> &bool {
match &self {
InitialValue::Bool(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_range(&self) -> &Range<i32> {
match &self {
InitialValue::Range(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_point(&self) -> &(i32, i32) {
match &self {
InitialValue::Point(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
}
#[derive(Debug, Deserialize)]
pub struct Component {
#[serde(rename="component")]
name: String,
#[serde(default)]
initial_value: Option<InitialValue>,
}
#[derive(Debug, Deserialize)]
pub struct Template {
pub feature_packs: Vec<String>,
pub features: Vec<Component>,
}
如何将模板转换为实体实例?
具体来说,我如何针对给定的 Component.name
找到组件
然后初始化呢?或者是我的方法错了,还有更好的方法
方式.
- 如果我做错了,其他游戏如何加载数据然后使用它生成
游戏实体?
听起来你想要一个标记的联合,或者求和类型; Rust 知道这些是 enum
erations. Serde even supports using container internal tags。所以这是我的小实验:
#[macro_use] extern crate serde_derive;
extern crate serde_yaml;
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag="component")]
enum Feature {
Char { initial_value : char },
Weight { kgs : u32 }
}
fn main() {
let v = vec![
Feature::Char{initial_value:'x'},
Feature::Weight{kgs:12}
];
println!("{}", serde_yaml::to_string(&v).unwrap());
}
这输出:
---
- component: Char
initial_value: x
- component: Weight
kgs: 12
可能下一步是为变体制作专用结构。
我正在构建一个 rogue-like,我已经让数据加载器工作并且部分 ECS 工作(从头开始构建)。数据存储在 .yml
文件中,用于描述游戏中的事物(在本例中为生物)以及这些事物具有的特征,例如:
---
orc:
feature_packs:
- physical
- basic_identifiers_mob
features:
- component: char
initial_value: T
goblin:
feature_packs:
- physical
- basic_identifiers_mob
features:
- component: char
initial_value: t
如您所见,描述了两种生物,地精和兽人,它们都拥有两个功能包(功能组),还拥有一个 char
功能,用于描述它们的外观喜欢玩家。
initial_value
字段可以是字符串、整数、浮点数、布尔值、范围等,具体取决于组件需要什么,这将指示组件可能具有的值或可能的值当组件在实体 building/creation.
问题是我不知道如何在遍历功能时,select 基于组件名称的结构,例如,select Char
"char"
功能的结构。
为了更好地描述我的意思,我用我更容易理解的语言写了一个例子,Ruby:
data_manager = function_that_loads_data('folder_path')
Entity_Manager.build(:mob, :orc, data_manager)
class Entity_Manager
class << self
attr_accessor :entities, :components
end
def self.build(entity_type, template_name, data_manager)
template = data_manager[entity_type][template_name]
entity_id = generate_unique_id
entities[entity_id] = Entity.new(entity_id, components: template.components.keys)
template.components.each do |component|
components[component.name][entity_id] =
Components.get(component.name).new(component.initial_value) # <= This part, how do I do the equivalent in rust, a function that will return or allow me to get or create a struct based on the value of a string variable
end
end
end
现在 serde 是我所知道的唯一似乎能够读取文本数据并将其转换为数据的东西,因此为此目的
如何使用 serde(或更合适的非 serde 使用解决方案)获取功能的名称并检索正确的结构,所有这些都实现了一个类型?
顺便说一下,我尽量不使用的一个解决方案是一个巨大的匹配语句。
我的作品的 repo 是 here
- Data manager - 加载和管理加载到游戏中的数据
- Entity manager - 管理实体和组件(不支持位密钥 atm)
- Entity Builder - 将使用来自数据管理器的数据构建实体的位置(这是我目前遇到的问题)
- Components - 简单组件列表
我想避免的是做这样的事情:
pub fn get(comp_name: &String) -> impl Component {
match comp_name.as_ref() {
"kind" => Kind,
"location" => Location,
"name" => Name,
"position" => Position,
"char" => Char,
}
}
因为它不是真正可维护的,虽然宏会有很大帮助,但我不是很擅长那些 atm,它甚至不起作用,rust 一直认为我正在尝试初始化类型,当我只是想要 return 全部将实现的几种可能类型之一 Component
编辑:因为看起来我不够清楚:
- 我不是要将游戏对象加载到游戏中,而是要加载 模板
- 我正在使用那些 模板 来生成将在游戏过程中存在的实体
- 我已经可以按以下结构将我想要的数据加载到游戏中:
pub enum InitialValue {
Char(char),
String(String),
Int(i32),
Float(f32),
Bool(bool),
Range(Range<i32>),
Point((i32,i32))
}
impl InitialValue {
pub fn unwrap_char(&self) -> &char {
match &self {
InitialValue::Char(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_string(&self) -> &String {
match &self {
InitialValue::String(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_int(&self) -> &i32 {
match &self {
InitialValue::Int(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_float(&self) -> &f32 {
match &self {
InitialValue::Float(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_bool(&self) -> &bool {
match &self {
InitialValue::Bool(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_range(&self) -> &Range<i32> {
match &self {
InitialValue::Range(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
pub fn unwrap_point(&self) -> &(i32, i32) {
match &self {
InitialValue::Point(val) => val,
_ => panic!("Stored value does not match unwrap type")
}
}
}
#[derive(Debug, Deserialize)]
pub struct Component {
#[serde(rename="component")]
name: String,
#[serde(default)]
initial_value: Option<InitialValue>,
}
#[derive(Debug, Deserialize)]
pub struct Template {
pub feature_packs: Vec<String>,
pub features: Vec<Component>,
}
如何将模板转换为实体实例?
具体来说,我如何针对给定的
Component.name
找到组件 然后初始化呢?或者是我的方法错了,还有更好的方法 方式.- 如果我做错了,其他游戏如何加载数据然后使用它生成 游戏实体?
听起来你想要一个标记的联合,或者求和类型; Rust 知道这些是 enum
erations. Serde even supports using container internal tags。所以这是我的小实验:
#[macro_use] extern crate serde_derive;
extern crate serde_yaml;
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag="component")]
enum Feature {
Char { initial_value : char },
Weight { kgs : u32 }
}
fn main() {
let v = vec![
Feature::Char{initial_value:'x'},
Feature::Weight{kgs:12}
];
println!("{}", serde_yaml::to_string(&v).unwrap());
}
这输出:
---
- component: Char
initial_value: x
- component: Weight
kgs: 12
可能下一步是为变体制作专用结构。