1use std::{
2 io,
3 num::NonZeroU64,
4 pin::Pin,
5 sync::{Arc, Mutex},
6 task::{Context, Poll},
7};
8
9use super::{
10 CommandResults,
11 errors::PluginModuleError,
12 memory_manager::{EcsAccessManager, EcsWorld},
13};
14use hashbrown::{HashMap, HashSet};
15use tokio::io::AsyncWrite;
16use wasmtime::{
17 Config, Engine, Store,
18 component::{Component, HasSelf, Linker},
19};
20use wasmtime_wasi::{
21 WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView,
22 cli::{IsTerminal, StdoutStream},
23 p2::Pollable,
24};
25
26pub(crate) mod types_mod {
27 wasmtime::component::bindgen!({
28 path: "../../plugin/wit/veloren.wit",
29 world: "common-types",
30 });
31}
32
33wasmtime::component::bindgen!({
34 path: "../../plugin/wit/veloren.wit",
35 world: "plugin",
36 with: {
37 "veloren:plugin/types@0.0.1": types_mod::veloren::plugin::types,
38 "veloren:plugin/information@0.0.1.entity": Entity,
39 },
40});
41
42mod animation_plugin {
43 wasmtime::component::bindgen!({
44 path: "../../plugin/wit/veloren.wit",
45 world: "animation-plugin",
46 with: {
47 "veloren:plugin/types@0.0.1": super::types_mod::veloren::plugin::types,
48 },
49 });
50}
51
52mod server_plugin {
53 wasmtime::component::bindgen!({
54 path: "../../plugin/wit/veloren.wit",
55 world: "server-plugin",
56 with: {
57 "veloren:plugin/types@0.0.1": super::types_mod::veloren::plugin::types,
58 "veloren:plugin/information@0.0.1.entity": super::Entity,
59 },
60 });
61}
62
63pub struct Entity {
64 uid: common::uid::Uid,
65}
66
67pub use animation::Body;
68use exports::veloren::plugin::animation;
69pub use types_mod::veloren::plugin::types::{
70 self, CharacterState, Dependency, Skeleton, Transform,
71};
72use veloren::plugin::{actions, information};
73
74type StoreType = wasmtime::Store<WasiHostCtx>;
75
76enum PluginWrapper {
78 Full(Plugin),
79 Animation(animation_plugin::AnimationPlugin),
80 Server(server_plugin::ServerPlugin),
81}
82
83impl PluginWrapper {
84 fn load_event<S: wasmtime::AsContextMut>(
85 &self,
86 store: S,
87 mode: common::resources::GameMode,
88 ) -> wasmtime::Result<()>
89 where
90 <S as wasmtime::AsContext>::Data: std::marker::Send,
91 {
92 let mode = match mode {
93 common::resources::GameMode::Server => types::GameMode::Server,
94 common::resources::GameMode::Client => types::GameMode::Client,
95 common::resources::GameMode::Singleplayer => types::GameMode::SinglePlayer,
96 };
97 match self {
98 PluginWrapper::Full(pl) => pl.veloren_plugin_events().call_load(store, mode),
99 PluginWrapper::Animation(pl) => pl.veloren_plugin_events().call_load(store, mode),
100 PluginWrapper::Server(pl) => pl.veloren_plugin_events().call_load(store, mode),
101 }
102 }
103
104 fn command_event<S: wasmtime::AsContextMut>(
105 &self,
106 store: S,
107 name: &str,
108 args: &[String],
109 player: types::Uid,
110 ) -> wasmtime::Result<Result<Vec<String>, String>>
111 where
112 <S as wasmtime::AsContext>::Data: std::marker::Send,
113 {
114 match self {
115 PluginWrapper::Full(pl) => pl
116 .veloren_plugin_server_events()
117 .call_command(store, name, args, player),
118 PluginWrapper::Animation(_) => Ok(Err("not implemented".into())),
119 PluginWrapper::Server(pl) => pl
120 .veloren_plugin_server_events()
121 .call_command(store, name, args, player),
122 }
123 }
124
125 fn player_join_event(
126 &self,
127 store: &mut StoreType,
128 name: &str,
129 uuid: (types::Uid, types::Uid),
130 ) -> wasmtime::Result<types::JoinResult> {
131 match self {
132 PluginWrapper::Full(pl) => pl
133 .veloren_plugin_server_events()
134 .call_join(store, name, uuid),
135 PluginWrapper::Animation(_) => Ok(types::JoinResult::None),
136 PluginWrapper::Server(pl) => pl
137 .veloren_plugin_server_events()
138 .call_join(store, name, uuid),
139 }
140 }
141
142 fn create_body(&self, store: &mut StoreType, bodytype: i32) -> Option<animation::Body> {
143 match self {
144 PluginWrapper::Full(pl) => {
145 let body_iface = pl.veloren_plugin_animation().body();
146 body_iface.call_constructor(store, bodytype).ok()
147 },
148 PluginWrapper::Animation(pl) => {
149 let body_iface = pl.veloren_plugin_animation().body();
150 body_iface.call_constructor(store, bodytype).ok()
151 },
152 PluginWrapper::Server(_) => None,
153 }
154 }
155
156 fn update_skeleton(
157 &self,
158 store: &mut StoreType,
159 body: animation::Body,
160 dep: types::Dependency,
161 time: f32,
162 ) -> Option<types::Skeleton> {
163 match self {
164 PluginWrapper::Full(pl) => {
165 let body_iface = pl.veloren_plugin_animation().body();
166 body_iface.call_update_skeleton(store, body, dep, time).ok()
167 },
168 PluginWrapper::Animation(pl) => {
169 let body_iface = pl.veloren_plugin_animation().body();
170 body_iface.call_update_skeleton(store, body, dep, time).ok()
171 },
172 PluginWrapper::Server(_) => None,
173 }
174 }
175}
176
177pub struct PluginModule {
179 ecs: Arc<EcsAccessManager>,
180 plugin: PluginWrapper,
181 store: Mutex<wasmtime::Store<WasiHostCtx>>,
182 name: String,
183 bodies: HashMap<String, animation::Body>,
185}
186
187struct WasiHostCtx {
188 preview2_ctx: WasiCtx,
189 preview2_table: wasmtime::component::ResourceTable,
190 ecs: Arc<EcsAccessManager>,
191 registered_commands: HashSet<String>,
192 registered_bodies: HashMap<String, types::BodyIndex>,
193}
194
195impl WasiView for WasiHostCtx {
196 fn ctx(&mut self) -> WasiCtxView<'_> {
197 WasiCtxView {
198 ctx: &mut self.preview2_ctx,
199 table: &mut self.preview2_table,
200 }
201 }
202}
203
204impl information::Host for WasiHostCtx {}
205
206impl types::Host for WasiHostCtx {}
207
208impl actions::Host for WasiHostCtx {
209 fn register_command(&mut self, name: String) {
210 tracing::info!("Plugin registers /{name}");
211 self.registered_commands.insert(name);
212 }
213
214 fn player_send_message(&mut self, uid: actions::Uid, text: String) {
215 tracing::info!("Plugin sends message {text} to player {uid:?}");
216 }
217
218 fn register_animation(&mut self, name: String, id: types::BodyIndex) {
219 let _ = self.registered_bodies.insert(name, id);
220 }
221}
222
223impl information::HostEntity for WasiHostCtx {
224 fn find_entity(
225 &mut self,
226 uid: actions::Uid,
227 ) -> Result<wasmtime::component::Resource<information::Entity>, types::Error> {
228 self.ctx()
229 .table
230 .push(Entity {
231 uid: common::uid::Uid(NonZeroU64::new(uid).ok_or(types::Error::RuntimeError)?),
232 })
233 .map_err(|_err| types::Error::RuntimeError)
234 }
235
236 fn health(
237 &mut self,
238 self_: wasmtime::component::Resource<information::Entity>,
239 ) -> Result<information::Health, types::Error> {
240 let uid = self
241 .ctx()
242 .table
243 .get(&self_)
244 .map_err(|_err| types::Error::RuntimeError)?
245 .uid;
246 self.ecs.with(|world| {
247 let world = world.ok_or(types::Error::EcsPointerNotAvailable)?;
248 let player = world
249 .id_maps
250 .uid_entity(uid)
251 .ok_or(types::Error::EcsEntityNotFound)?;
252 world
253 .health
254 .get(player)
255 .map(|health| information::Health {
256 current: health.current(),
257 base_max: health.base_max(),
258 maximum: health.maximum(),
259 })
260 .ok_or(types::Error::EcsComponentNotFound)
261 })
262 }
263
264 fn name(
265 &mut self,
266 self_: wasmtime::component::Resource<information::Entity>,
267 ) -> Result<String, types::Error> {
268 let uid = self
269 .ctx()
270 .table
271 .get(&self_)
272 .map_err(|_err| types::Error::RuntimeError)?
273 .uid;
274 self.ecs.with(|world| {
275 let world = world.ok_or(types::Error::EcsPointerNotAvailable)?;
276 let player = world
277 .id_maps
278 .uid_entity(uid)
279 .ok_or(types::Error::EcsEntityNotFound)?;
280 Ok(world
281 .player
282 .get(player)
283 .ok_or(types::Error::EcsComponentNotFound)?
284 .alias
285 .to_owned())
286 })
287 }
288
289 fn drop(
290 &mut self,
291 rep: wasmtime::component::Resource<information::Entity>,
292 ) -> wasmtime::Result<()> {
293 Ok(self.ctx().table.delete(rep).map(|_entity| ())?)
294 }
295}
296
297struct InfoStream(String);
298
299impl AsyncWrite for InfoStream {
300 fn poll_write(
301 self: Pin<&mut Self>,
302 _cx: &mut Context,
303 buf: &[u8],
304 ) -> Poll<Result<usize, io::Error>> {
305 tracing::info!("{}: {}", self.0, String::from_utf8_lossy(buf));
306 Poll::Ready(Ok(buf.len()))
307 }
308
309 fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Result<(), io::Error>> {
310 Poll::Ready(Ok(()))
311 }
312
313 fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Result<(), io::Error>> {
314 Poll::Ready(Ok(()))
315 }
316}
317
318#[wasmtime_wasi::async_trait]
319impl Pollable for InfoStream {
320 async fn ready(&mut self) {}
321}
322
323struct ErrorStream(String);
324
325impl AsyncWrite for ErrorStream {
326 fn poll_write(
327 self: Pin<&mut Self>,
328 _cx: &mut Context,
329 buf: &[u8],
330 ) -> Poll<Result<usize, io::Error>> {
331 tracing::error!("{}: {}", self.0, String::from_utf8_lossy(buf));
332 Poll::Ready(Ok(buf.len()))
333 }
334
335 fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Result<(), io::Error>> {
336 Poll::Ready(Ok(()))
337 }
338
339 fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Result<(), io::Error>> {
340 Poll::Ready(Ok(()))
341 }
342}
343
344#[wasmtime_wasi::async_trait]
345impl Pollable for ErrorStream {
346 async fn ready(&mut self) {}
347}
348
349struct LogStream(String, tracing::Level);
350
351impl IsTerminal for LogStream {
352 fn is_terminal(&self) -> bool { true }
353}
354
355impl StdoutStream for LogStream {
356 fn async_stream(&self) -> Box<dyn AsyncWrite + Send + Sync> {
357 if self.1 == tracing::Level::INFO {
358 Box::new(InfoStream(self.0.clone()))
359 } else {
360 Box::new(ErrorStream(self.0.clone()))
361 }
362 }
363}
364
365impl PluginModule {
366 pub fn new(name: String, wasm_data: &[u8]) -> Result<Self, PluginModuleError> {
368 let ecs = Arc::new(EcsAccessManager::default());
369
370 let mut config = Config::new();
372 config.wasm_component_model(true);
373
374 let engine = Engine::new(&config).map_err(PluginModuleError::Wasmtime)?;
375 let wasi = WasiCtxBuilder::new()
377 .stdout(LogStream(name.clone(), tracing::Level::INFO))
378 .stderr(LogStream(name.clone(), tracing::Level::ERROR))
379 .build();
380 let host_ctx = WasiHostCtx {
381 preview2_ctx: wasi,
382 preview2_table: wasmtime_wasi::ResourceTable::new(),
383 ecs: Arc::clone(&ecs),
384 registered_commands: HashSet::new(),
385 registered_bodies: HashMap::new(),
386 };
387 let mut store = Store::new(&engine, host_ctx);
389
390 let module =
392 Component::from_binary(&engine, wasm_data).map_err(PluginModuleError::Wasmtime)?;
393
394 let mut linker = Linker::new(&engine);
396 wasmtime_wasi::p2::add_to_linker_sync(&mut linker).map_err(PluginModuleError::Wasmtime)?;
397 Plugin::add_to_linker::<_, HasSelf<_>>(&mut linker, |x| x)
398 .map_err(PluginModuleError::Wasmtime)?;
399
400 let instance_fut = linker.instantiate(&mut store, &module);
401 let instance = (instance_fut).map_err(PluginModuleError::Wasmtime)?;
402
403 let plugin = match Plugin::new(&mut store, &instance) {
404 Ok(pl) => Ok(PluginWrapper::Full(pl)),
405 Err(_) => match animation_plugin::AnimationPlugin::new(&mut store, &instance) {
406 Ok(pl) => Ok(PluginWrapper::Animation(pl)),
407 Err(_) => server_plugin::ServerPlugin::new(&mut store, &instance)
408 .map(PluginWrapper::Server),
409 },
410 }
411 .map_err(PluginModuleError::Wasmtime)?;
412
413 Ok(Self {
414 plugin,
415 ecs,
416 store: store.into(),
417 name,
418 bodies: Default::default(),
419 })
420 }
421
422 pub fn name(&self) -> &str { &self.name }
423
424 pub fn load_event(
426 &mut self,
427 ecs: &EcsWorld,
428 mode: common::resources::GameMode,
429 ) -> Result<(), PluginModuleError> {
430 self.ecs
431 .execute_with(ecs, || {
432 self.plugin.load_event(self.store.get_mut().unwrap(), mode)
433 })
434 .map_err(PluginModuleError::Wasmtime)
435 }
436
437 pub fn command_event(
438 &mut self,
439 ecs: &EcsWorld,
440 name: &str,
441 args: &[String],
442 player: common::uid::Uid,
443 ) -> Result<Vec<String>, CommandResults> {
444 if !self
445 .store
446 .get_mut()
447 .unwrap()
448 .data()
449 .registered_commands
450 .contains(name)
451 {
452 return Err(CommandResults::UnknownCommand);
453 }
454 self.ecs.execute_with(ecs, || {
455 match self.plugin.command_event(
456 self.store.get_mut().unwrap(),
457 name,
458 args,
459 player.0.into(),
460 ) {
461 Err(err) => Err(CommandResults::HostError(err)),
462 Ok(result) => result.map_err(CommandResults::PluginError),
463 }
464 })
465 }
466
467 pub fn player_join_event(
468 &mut self,
469 ecs: &EcsWorld,
470 name: &str,
471 uuid: common::uuid::Uuid,
472 ) -> types::JoinResult {
473 self.ecs.execute_with(ecs, || {
474 match self.plugin.player_join_event(
475 self.store.get_mut().unwrap(),
476 name,
477 uuid.as_u64_pair(),
478 ) {
479 Ok(value) => {
480 tracing::info!("JoinResult {value:?}");
481 value
482 },
483 Err(err) => {
484 tracing::error!("join_event: {err:?}");
485 types::JoinResult::None
486 },
487 }
488 })
489 }
490
491 pub fn skeleton(
492 &mut self,
493 species: &str,
494 dep: &types::Dependency,
495 time: f32,
496 ) -> Option<types::Skeleton> {
497 let store = self.store.get_mut().unwrap();
498 let body = match self.bodies.entry_ref(species) {
499 hashbrown::hash_map::EntryRef::Occupied(e) => *e.get(),
500 hashbrown::hash_map::EntryRef::Vacant(e) => {
501 let index = *store.data().registered_bodies.get(species)?;
503 *e.insert(self.plugin.create_body(store, index)?)
504 },
505 };
506 self.plugin.update_skeleton(store, body, *dep, time)
507 }
508}