Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
leanmendoza committed Nov 22, 2023
1 parent b1748a3 commit 6b8b07c
Show file tree
Hide file tree
Showing 5 changed files with 158 additions and 7 deletions.
37 changes: 34 additions & 3 deletions rust/decentraland-godot-lib/src/dcl/js/js_modules/Testing.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
module.exports.logTestResult = async function (body) { return {} }
module.exports.plan = async function (body) { return {} }
module.exports.setCameraTransform = async function (body) { return {} }
const env = require('env')

const testingEnabled = env['testing_enable']

function emptyTesting() {
return {
logTestResult: async function (body) { return {} },
plan: async function (body) { return {} },
setCameraTransform: async function (body) { return {} },
}
}

function testingModule() {
function takeAndCompareSnapshot(body) {
const { id, cameraPosition, cameraTarget, snapshotFrameSize, tolerance } = body

return Deno.core.ops.op_take_and_compare_snapshot(
id,
[cameraPosition.x, cameraPosition.y, cameraPosition.z],
[cameraTarget.x, cameraTarget.y, cameraTarget.z],
[snapshotFrameSize.x, snapshotFrameSize.y],
tolerance
);
}

return {
logTestResult: async function (body) { return {} },
plan: async function (body) { return {} },
setCameraTransform: async function (body) { return {} },
takeAndCompareSnapshot
}
}

module.exports = testingEnabled ? testingModule() : emptyTesting()
27 changes: 24 additions & 3 deletions rust/decentraland-godot-lib/src/dcl/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod players;
pub mod portables;
pub mod restricted_actions;
pub mod runtime;
pub mod testing;
pub mod websocket;

use crate::dcl::scene_apis::{LocalCall, RpcCall};
Expand All @@ -28,6 +29,7 @@ use deno_core::{
include_js_files, op, v8, Extension, Op, OpState, RuntimeOptions,
};
use once_cell::sync::Lazy;
use serde::Serialize;
use v8::IsolateHandle;

struct SceneJsFileContent(pub String);
Expand Down Expand Up @@ -64,7 +66,7 @@ pub fn create_runtime() -> deno_core::JsRuntime {
// add core ops
ext = ext.ops(vec![op_require::DECL, op_log::DECL, op_error::DECL]);

let op_sets: [Vec<deno_core::OpDecl>; 8] = [
let op_sets: [Vec<deno_core::OpDecl>; 9] = [
engine::ops(),
runtime::ops(),
fetch::ops(),
Expand All @@ -73,6 +75,7 @@ pub fn create_runtime() -> deno_core::JsRuntime {
portables::ops(),
players::ops(),
events::ops(),
testing::ops(),
];

let mut op_map = HashMap::new();
Expand Down Expand Up @@ -209,6 +212,7 @@ pub(crate) fn scene_thread(
.borrow_mut()
.put(SceneStartTime(std::time::SystemTime::now()));


let script = runtime.execute_script("<loader>", ascii_str!("require (\"~scene.js\")"));

let script = match script {
Expand Down Expand Up @@ -346,12 +350,12 @@ async fn run_script(
// synchronously returns a string containing JS code from the file system
#[op(v8)]
fn op_require(
state: Rc<RefCell<OpState>>,
state: &mut OpState,
module_spec: String,
) -> Result<String, deno_core::error::AnyError> {
match module_spec.as_str() {
// user module load
"~scene.js" => Ok(state.borrow_mut().take::<SceneJsFileContent>().0),
"~scene.js" => Ok(state.take::<SceneJsFileContent>().0),
// core module load
"~system/CommunicationsController" => {
Ok(include_str!("js_modules/CommunicationsController.js").to_owned())
Expand All @@ -376,6 +380,7 @@ fn op_require(
"~system/Testing" => Ok(include_str!("js_modules/Testing.js").to_owned()),
"~system/UserActionModule" => Ok(include_str!("js_modules/UserActionModule.js").to_owned()),
"~system/UserIdentity" => Ok(include_str!("js_modules/UserIdentity.js").to_owned()),
"env" => Ok(get_env_for_scene(state)),
_ => Err(generic_error(format!(
"invalid module request `{module_spec}`"
))),
Expand Down Expand Up @@ -419,3 +424,19 @@ fn op_error(state: Rc<RefCell<OpState>>, message: String, immediate: bool) {
message,
})
}

#[derive(Serialize)]
pub struct SceneEnv {
pub enable_know_env: bool,
pub testing_enable: bool,
}

fn get_env_for_scene(state: &mut OpState) -> String {
let scene_env = state.borrow::<SceneEnv>();
if scene_env.enable_know_env {
let scene_env_json = serde_json::to_string(scene_env).unwrap();
format!("module.exports = {}", scene_env_json)
} else {
"module.exports = {}".to_owned()
}
}
59 changes: 59 additions & 0 deletions rust/decentraland-godot-lib/src/dcl/js/testing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use deno_core::{
anyhow::{self, anyhow},
error::AnyError,
op, Op, OpDecl, OpState,
};
use godot::builtin::{Vector2, Vector3};

use crate::dcl::{SceneResponse, TakeAndCompareSnapshotResponse};

use super::SceneEnv;

pub fn ops() -> Vec<OpDecl> {
vec![op_take_and_compare_snapshot::DECL]
}

#[op]
fn op_take_and_compare_snapshot(
state: &mut OpState,
id: String,
camera_position: [f32; 3],
camera_target: [f32; 3],
snapshot_frame_size: [f32; 2],
tolerance: f32,
) -> Result<TakeAndCompareSnapshotResponse, AnyError> {
let scene_env = state.borrow::<SceneEnv>();
if !scene_env.testing_enable {
return Err(anyhow::anyhow!("Testing mode not available"));
}

let (sx, rx) =
tokio::sync::oneshot::channel::<Result<TakeAndCompareSnapshotResponse, String>>();

let sender = state.borrow_mut::<std::sync::mpsc::SyncSender<SceneResponse>>();
sender
.send(SceneResponse::TakeSnapshot {
id,
camera_position: Vector3 {
x: camera_position[0],
y: camera_position[1],
z: camera_position[2],
},
camera_target: Vector3 {
x: camera_target[0],
y: camera_target[1],
z: camera_target[2],
},
snapshot_frame_size: Vector2 {
x: snapshot_frame_size[0],
y: snapshot_frame_size[1],
},
tolerance,
response: sx.into(),
})
.expect("error sending scene response!!");

rx.blocking_recv()
.map_err(|e| anyhow::anyhow!(e))?
.map_err(|e| anyhow!(e))
}
26 changes: 25 additions & 1 deletion rust/decentraland-godot-lib/src/dcl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ pub mod js;
pub mod scene_apis;
pub mod serialization;

use godot::builtin::{Vector3, Vector2};
use serde::Serialize;

use crate::wallet::Wallet;

use self::{
crdt::{DirtyCrdtState, SceneCrdtState},
js::{scene_thread, SceneLogMessage},
scene_apis::RpcCall,
scene_apis::{RpcCall, RpcResultSender},
};

use std::{
Expand Down Expand Up @@ -57,6 +60,27 @@ pub enum SceneResponse {
Vec<RpcCall>,
),
RemoveGodotScene(SceneId, Vec<SceneLogMessage>),
TakeSnapshot {
id: String,
camera_position: Vector3,
camera_target: Vector3,
snapshot_frame_size: Vector2,
tolerance: f32,
response: RpcResultSender<Result<TakeAndCompareSnapshotResponse, String>>,
},
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TakeAndCompareSnapshotResponse {
// true if the threshold was met, false otherwise or if it wasn't previously exist
is_match: bool,
// from 0 to 1 how similar the snapshot taken is to the previous one
similarity: f32,
// true if the snapshot already exists in the snapshot folder, false otherwise
was_exist: bool,
// true if the snapshot was created and saved, false otherwise
replaced: bool,
}

pub type SharedSceneCrdtState = Arc<Mutex<SceneCrdtState>>;
Expand Down
16 changes: 16 additions & 0 deletions rust/decentraland-godot-lib/src/scene_runner/scene_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ use crate::{
SceneEntityId,
},
js::SceneLogLevel,
scene_apis::RpcResultSender,
DclScene, RendererResponse, SceneDefinition, SceneId, SceneResponse,
TakeAndCompareSnapshotResponse,
},
godot_classes::{dcl_camera_3d::DclCamera3D, dcl_ui_control::DclUiControl},
wallet::Wallet,
Expand Down Expand Up @@ -71,6 +73,9 @@ pub struct SceneManager {
input_state: InputState,
last_raycast_result: Option<GodotDclRaycastResult>,

snapshot_sender:
HashMap<String, RpcResultSender<Result<TakeAndCompareSnapshotResponse, String>>>,

#[export]
pointer_tooltips: VariantArray,
}
Expand Down Expand Up @@ -458,6 +463,15 @@ impl SceneManager {
self.console.callv(arguments);
}
}

SceneResponse::TakeSnapshot {
id,
camera_position,
camera_target,
snapshot_frame_size,
tolerance,
response,
} => {}
},
Err(std::sync::mpsc::TryRecvError::Empty) => return,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
Expand Down Expand Up @@ -653,6 +667,8 @@ impl NodeVirtual for SceneManager {
input_state: InputState::default(),
last_raycast_result: None,
pointer_tooltips: VariantArray::new(),

snapshot_sender: HashMap::new(),
}
}

Expand Down

0 comments on commit 6b8b07c

Please sign in to comment.