1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use super::*;
use serde_json::{json, Value};
use std::process::Child;

#[derive(Debug, Default)]
/// Handle to a spawned child process, as well as the command
/// and the env vars used in spawning the process.
pub struct LaunchProcess {
    /// Spawned child process.
    pub process: Option<Child>,
    /// Constructed command with all arguments used.
    pub command: Option<Vec<String>>,
    pub envs: Option<HashMap<String, String>>,
}

impl LaunchProcess {
    pub fn process(child: Child) -> Self {
        Self {
            process: Some(child),
            ..Default::default()
        }
    }

    pub fn command(mut self, arg: String) -> Self {
        match self.command.as_mut() {
            Some(args) => {
                args.push(arg);
            }
            None => {
                self.command = Some(vec![arg]);
            }
        };
        self
    }

    pub fn envs(mut self, envs: HashMap<String, String>) -> Self {
        self.envs = Some(envs);
        self
    }

    fn command_as_str(&self) -> String {
        if let Some(cmd) = &self.command {
            cmd.join(" ")
        } else {
            String::from("None")
        }
    }

    fn envs_as_str(&self) -> String {
        if let Some(vars) = &self.envs {
            format!("{:?}", vars)
        } else {
            String::from("None")
        }
    }

    pub fn debug(&self) -> String {
        format!(
            "Command: {}\nEnvs: {}",
            self.command_as_str(),
            self.envs_as_str()
        )
    }
}

pub trait DccEngineEnv: fmt::Debug + Send + Sync {
    fn launch_vanilla_maya(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_custom_maya(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_3ds_max(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_blender(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_zbrush(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_vanilla_mari(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_custom_mari(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_substance_painter(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_substance_designer(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_unity(&self, project: &Project) -> AnyResult<LaunchProcess>;

    fn launch_unreal(&self, project: &Project) -> AnyResult<LaunchProcess>;
}

#[allow(dead_code)]
#[derive(Deserialize, Debug, Default)]
/// The response from Embark Studios' SkyHook server,
/// from JSON deserialized into Rust struct.

pub struct SkyHookResponse {
    #[serde(rename = "ReturnValue")]
    return_value: Vec<String>,

    #[serde(rename = "Success")]
    success: bool,
}

#[derive(Serialize, Default)]
/// The payload sent to Embark Studios' SkyHook server,
/// from Rust struct serialized into JSON.
pub struct SkyHookPayload {
    #[serde(rename = "FunctionName")]
    function_name: String,

    #[serde(rename = "Parameters")]
    param: Value,
}

impl SkyHookPayload {
    pub fn ozone_script(num: u8, assets: HashSet<ProductionAsset>) -> AnyResult<Self> {
        Ok(Self {
            function_name: format!("ozone_script_{}", num),
            ..Default::default()
        }
        .selected_assets(assets)?)
    }

    /// Inserts `"selected_assets"` into `Self::param`.
    pub fn selected_assets(mut self, assets: HashSet<ProductionAsset>) -> AnyResult<Self> {
        self.param = json!({ "selected_assets": AssetRequestBuilder::new(assets).finish()? });
        Ok(self)
    }

    /// For simple `Self::param` of pairs of strings.
    pub fn with_str_params(mut self, param: &[(&str, &str)]) -> Self {
        self.param = param
            .iter()
            .map(|(k, v)| (String::from(*k), String::from(*v)))
            .collect();
        self
    }

    /// From `.dcc_engine/common/skyhook_py2/skyhook/modules/core.py`
    pub fn echo_message(msg: &str) -> Self {
        Self {
            function_name: "echo_message".into(),
            ..Default::default()
        }
        .with_str_params(&[("message", msg)])
    }

    /// From `.dcc_engine/maya/rusty_hunter/scripts/rusty_hunter/mayahii/rh_scene.py` module.
    pub fn open_maya_scene(path: &Path) -> Self {
        Self {
            function_name: "open_scene".into(),
            ..Default::default()
        }
        .with_str_params(&[("path", &path.to_string_lossy().to_string())])
    }
}

/// An "asset sanitizer" before they getting sent inside HTTP requests.
struct AssetRequestBuilder {
    input: Vec<ProductionAsset>,
    output: Vec<StandardAsset>,
}

impl AssetRequestBuilder {
    fn new(assets: HashSet<ProductionAsset>) -> Self {
        Self {
            input: assets.into_iter().collect(),
            output: vec![],
        }
    }

    /// Tries to remove the enum variants by getting to the "inner"s. Fails if encountering
    /// any [`ProductionAsset`] that cannot be made into a [`StandardAsset`].
    fn standard_assets(mut self) -> AnyResult<Self> {
        let mut output = vec![];
        // `Self::input` will be empty after this loop
        while let Some(a) = self.input.pop() {
            output.push(
                a.inner_standard_owned()
                    .context("Unsupported inner type of ProductionAsset")?,
            );
        }
        self.output = output;
        Ok(self)
    }

    fn finish(mut self) -> AnyResult<Vec<StandardAsset>> {
        self = self.standard_assets()?;
        Ok(self.output)
    }
}