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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use crate::{
    components::transform::HaTransform,
    ha_renderer::{HaRenderer, PipelineSource},
    material::common::MaterialRenderTargetSignature,
    math::*,
    pipeline::{render_queue::*, stage::*, *},
    render_target::RenderTargetViewport,
};
use core::{
    prefab::{Prefab, PrefabComponent},
    Scalar,
};
use serde::{Deserialize, Serialize};
use std::{
    any::TypeId,
    sync::{Arc, RwLock},
};

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum HaCameraOrtographicScaling {
    None,
    Stretch(Vec2),
    FitHorizontal(Scalar),
    FitVertical(Scalar),
    /// (view size, fit inside)
    FitToView(Vec2, bool),
}

impl Default for HaCameraOrtographicScaling {
    fn default() -> Self {
        Self::None
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct HaCameraOrthographic {
    #[serde(default)]
    pub scaling: HaCameraOrtographicScaling,
    #[serde(default)]
    pub centered: bool,
    #[serde(default)]
    pub ignore_depth_planes: bool,
}

impl HaCameraOrthographic {
    pub fn matrix(&self, size: Vec2) -> Mat4 {
        let size = match self.scaling {
            HaCameraOrtographicScaling::None => size,
            HaCameraOrtographicScaling::Stretch(size) => size,
            HaCameraOrtographicScaling::FitHorizontal(width) => {
                let height = width * size.y / size.x;
                Vec2::new(width, height)
            }
            HaCameraOrtographicScaling::FitVertical(height) => {
                let width = height * size.x / size.y;
                Vec2::new(width, height)
            }
            HaCameraOrtographicScaling::FitToView(view, inside) => {
                let aspect = size.x / size.y;
                let view_aspect = view.x / view.y;
                let (width, height) = if (aspect >= view_aspect) != inside {
                    (size.x * view.x / size.y, view.y)
                } else {
                    (view.x, size.y * view.y / size.x)
                };
                Vec2::new(width, height)
            }
        };
        let frustum = if self.centered {
            let half_size = size * 0.5;
            FrustumPlanes {
                left: -half_size.x,
                right: half_size.x,
                top: -half_size.y,
                bottom: half_size.y,
                near: -1.0,
                far: 1.0,
            }
        } else {
            FrustumPlanes {
                left: 0.0,
                right: size.x,
                top: 0.0,
                bottom: size.y,
                near: -1.0,
                far: 1.0,
            }
        };
        if self.ignore_depth_planes {
            Mat4::orthographic_without_depth_planes(frustum)
        } else {
            Mat4::orthographic_rh_zo(frustum)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct HaCameraPerspective {
    #[serde(default = "HaCameraPerspective::default_fov")]
    pub fov: Scalar,
    #[serde(default = "HaCameraPerspective::default_near")]
    pub near: Scalar,
    #[serde(default)]
    pub far: Option<Scalar>,
}

impl Default for HaCameraPerspective {
    fn default() -> Self {
        Self {
            fov: Self::default_fov(),
            near: Self::default_near(),
            far: None,
        }
    }
}

impl HaCameraPerspective {
    fn default_fov() -> Scalar {
        #[cfg(feature = "scalar64")]
        {
            50.0_f64.to_radians()
        }
        #[cfg(not(feature = "scalar64"))]
        {
            50.0_f32.to_radians()
        }
    }

    fn default_near() -> Scalar {
        1.0
    }

    pub fn matrix(&self, size: Vec2) -> Mat4 {
        if let Some(far) = self.far {
            Mat4::perspective_fov_rh_zo(self.fov, size.x, size.y, self.near, far)
        } else {
            Mat4::infinite_perspective_rh(self.fov, size.x / size.y, self.near)
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HaCameraProjection {
    Orthographic(#[serde(default)] HaCameraOrthographic),
    Perspective(#[serde(default)] HaCameraPerspective),
}

impl Default for HaCameraProjection {
    fn default() -> Self {
        Self::Orthographic(Default::default())
    }
}

impl HaCameraProjection {
    pub fn matrix(&self, size: Vec2) -> Mat4 {
        match self {
            Self::Orthographic(orthographic) => orthographic.matrix(size),
            Self::Perspective(perspective) => perspective.matrix(size),
        }
    }
}

#[derive(Debug, Clone)]
pub struct HaStageCameraInfo {
    pub width: usize,
    pub height: usize,
    pub transform_matrix: Mat4,
    pub view_matrix: Mat4,
    pub projection_matrix: Mat4,
}

impl HaStageCameraInfo {
    pub fn render_target_to_screen(&self, mut point: Vec2) -> Vec2 {
        point.x = (2.0 * point.x / self.width as Scalar) - 1.0;
        point.y = (-2.0 * point.y / self.height as Scalar) + 1.0;
        point
    }

    pub fn screen_to_device(&self, mut point: Vec2) -> Vec2 {
        point.x = (point.x + 1.0) * 0.5 * self.width as Scalar;
        point.y = (point.y + 1.0) * 0.5 * self.height as Scalar;
        point
    }

    pub fn world_to_screen(&self) -> Mat4 {
        self.projection_matrix * self.view_matrix
    }

    pub fn world_to_screen_point(&self, point: Vec3) -> Vec3 {
        self.world_to_screen().mul_point(point)
    }

    pub fn world_to_screen_direction(&self, point: Vec3) -> Vec3 {
        self.world_to_screen().mul_direction(point)
    }

    pub fn screen_to_world(&self) -> Mat4 {
        self.world_to_screen().inverted()
    }

    pub fn screen_to_world_point(&self, point: Vec3) -> Vec3 {
        self.screen_to_world().mul_point(point)
    }

    pub fn screen_to_world_direction(&self, point: Vec3) -> Vec3 {
        self.screen_to_world().mul_direction(point)
    }

    /// [(plane center, plane outward normal); 6]
    pub fn world_planes(&self) -> [(Vec3, Vec3); 6] {
        let matrix = self.screen_to_world();
        [
            (
                matrix.mul_point(Vec3::new(-1.0, 0.0, 0.0)),
                matrix.mul_direction(Vec3::new(-1.0, 0.0, 0.0)),
            ),
            (
                matrix.mul_point(Vec3::new(1.0, 0.0, 0.0)),
                matrix.mul_direction(Vec3::new(1.0, 0.0, 0.0)),
            ),
            (
                matrix.mul_point(Vec3::new(0.0, -1.0, 0.0)),
                matrix.mul_direction(Vec3::new(0.0, -1.0, 0.0)),
            ),
            (
                matrix.mul_point(Vec3::new(0.0, 1.0, 0.0)),
                matrix.mul_direction(Vec3::new(0.0, 1.0, 0.0)),
            ),
            (
                matrix.mul_point(Vec3::new(0.0, 0.0, -1.0)),
                matrix.mul_direction(Vec3::new(0.0, 0.0, -1.0)),
            ),
            (
                matrix.mul_point(Vec3::new(0.0, 0.0, 1.0)),
                matrix.mul_direction(Vec3::new(0.0, 0.0, 1.0)),
            ),
        ]
    }

    pub fn is_inside_world_bounds(&self, point: Vec3) -> bool {
        let point = self.world_to_screen_point(point);
        point.x >= -1.0
            && point.x <= 1.0
            && point.y >= -1.0
            && point.y <= 1.0
            && point.z >= -1.0
            && point.z <= 1.0
    }

    pub fn world_vertices(&self) -> [Vec3; 8] {
        let matrix = self.screen_to_world();
        [
            matrix.mul_point(Vec3::new(-1.0, -1.0, -1.0)),
            matrix.mul_point(Vec3::new(1.0, -1.0, -1.0)),
            matrix.mul_point(Vec3::new(1.0, 1.0, -1.0)),
            matrix.mul_point(Vec3::new(-1.0, 1.0, -1.0)),
            matrix.mul_point(Vec3::new(-1.0, -1.0, 1.0)),
            matrix.mul_point(Vec3::new(1.0, -1.0, 1.0)),
            matrix.mul_point(Vec3::new(1.0, 1.0, 1.0)),
            matrix.mul_point(Vec3::new(-1.0, 1.0, 1.0)),
        ]
    }

    /// (min, max)
    pub fn world_bounds(&self) -> (Vec3, Vec3) {
        let vertices = self.world_vertices();
        vertices
            .iter()
            .skip(1)
            .fold((vertices[0], vertices[0]), |(min, max), v| {
                (Vec3::partial_min(min, *v), Vec3::partial_max(max, *v))
            })
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct HaCamera {
    #[serde(default)]
    pub projection: HaCameraProjection,
    #[serde(default)]
    pub viewport: RenderTargetViewport,
    #[serde(default)]
    pub pipeline: PipelineSource,

    #[serde(skip)]
    pub(crate) cached_pipeline: Option<PipelineId>,
}

impl HaCamera {
    pub fn with_projection(mut self, projection: HaCameraProjection) -> Self {
        self.projection = projection;
        self
    }

    pub fn with_viewport(mut self, viewport: RenderTargetViewport) -> Self {
        self.viewport = viewport;
        self
    }

    pub fn with_pipeline(mut self, pipeline: PipelineSource) -> Self {
        self.pipeline = pipeline;
        self
    }

    pub fn pipeline_stage_info<'a, T: 'static>(
        &'a self,
        renderer: &'a HaRenderer,
        camera_transform: &'a HaTransform,
    ) -> Option<impl Iterator<Item = HaStageCameraInfo> + 'a> {
        Some(
            self.pipeline_stage_info_raw(Some(TypeId::of::<T>()), renderer, camera_transform)?
                .map(|(_, info)| info),
        )
    }

    pub fn pipeline_stage_info_raw<'a>(
        &'a self,
        type_id: Option<TypeId>,
        renderer: &'a HaRenderer,
        camera_transform: &'a HaTransform,
    ) -> Option<impl Iterator<Item = (TypeId, HaStageCameraInfo)> + 'a> {
        let id = self.cached_pipeline?;
        let pipeline = renderer.pipelines.get(&id)?;
        Some(
            pipeline
                .stages
                .iter()
                .filter(move |stage| type_id.map(|tid| stage.type_id == tid).unwrap_or(true))
                .filter_map(|stage| {
                    let render_target = pipeline.render_targets.get(&stage.render_target)?;
                    let render_target = renderer.render_targets.get(render_target.1)?;
                    let width = render_target.width();
                    let height = render_target.height();
                    let (_, _, width, height) = self.viewport.rect(width, height);
                    let transform_matrix = camera_transform.world_matrix();
                    let view_matrix = transform_matrix.inverted();
                    let projection_matrix =
                        self.projection.matrix(Vec2::new(width as _, height as _));
                    Some((
                        stage.type_id,
                        HaStageCameraInfo {
                            width,
                            height,
                            transform_matrix,
                            view_matrix,
                            projection_matrix,
                        },
                    ))
                }),
        )
    }

    pub fn record_to_pipeline_stage<'a, T: 'static>(
        &'a self,
        renderer: &'a HaRenderer,
        camera_transform: &'a HaTransform,
    ) -> Option<impl Iterator<Item = (StageProcessInfo, Arc<RwLock<RenderQueue>>)> + 'a> {
        Some(
            self.record_to_pipeline_stage_raw(Some(TypeId::of::<T>()), renderer, camera_transform)?
                .map(|(_, info, queue)| (info, queue)),
        )
    }

    pub fn record_to_pipeline_stage_raw<'a>(
        &'a self,
        type_id: Option<TypeId>,
        renderer: &'a HaRenderer,
        camera_transform: &'a HaTransform,
    ) -> Option<impl Iterator<Item = (TypeId, StageProcessInfo, Arc<RwLock<RenderQueue>>)> + 'a>
    {
        let id = self.cached_pipeline?;
        let pipeline = renderer.pipelines.get(&id)?;
        Some(
            pipeline
                .stages
                .iter()
                .filter(move |stage| type_id.map(|tid| stage.type_id == tid).unwrap_or(true))
                .filter_map(|stage| {
                    let render_target = pipeline.render_targets.get(&stage.render_target)?;
                    let render_target = renderer.render_targets.get(render_target.1)?;
                    let width = render_target.width();
                    let height = render_target.height();
                    let (x, y, width, height) = self.viewport.rect(width, height);
                    let transform_matrix = camera_transform.world_matrix();
                    let view_matrix = transform_matrix.inverted();
                    let projection_matrix =
                        self.projection.matrix(Vec2::new(width as _, height as _));
                    let info = StageProcessInfo {
                        width,
                        height,
                        transform_matrix,
                        view_matrix,
                        projection_matrix,
                        material_render_target_signature: MaterialRenderTargetSignature::new(
                            render_target,
                        ),
                        domain: stage.domain.to_owned(),
                        filters: stage.filters.to_owned(),
                    };
                    if !matches!(self.viewport, RenderTargetViewport::Full) {
                        if let Ok(mut queue) = stage.render_queue.write() {
                            queue
                                .record(0, 0, RenderCommand::Viewport(x, y, width, height))
                                .ok()?;
                            queue.record(0, 0, RenderCommand::SortingBarrier).ok()?;
                        }
                    }
                    Some((stage.type_id, info, Arc::clone(&stage.render_queue)))
                }),
        )
    }
}

impl Prefab for HaCamera {}
impl PrefabComponent for HaCamera {}

#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
pub struct HaDefaultCamera;

impl Prefab for HaDefaultCamera {}
impl PrefabComponent for HaDefaultCamera {}