Skip to content

Commit

Permalink
fix(server): fix the basic fragments task
Browse files Browse the repository at this point in the history
  • Loading branch information
jabibamman committed Feb 15, 2024
1 parent 1f12969 commit 64a80e8
Show file tree
Hide file tree
Showing 9 changed files with 143 additions and 51 deletions.
73 changes: 46 additions & 27 deletions server/src/messages/fragment_maker.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::env;
use std::error::Error;

use shared::types::fractal_descriptor::FractalType::IteratedSinZ;
Expand All @@ -13,40 +12,60 @@ use shared::types::{
};
use shared::utils::env_utils::get_env_var_as_u16;

pub fn create_task_for_request(_request: FragmentRequest) -> Result<FragmentTask, Box<dyn Error>> {
pub fn create_tasks() -> Result<Vec<FragmentTask>, Box<dyn Error>> {
let width = get_env_var_as_u16("RESOLUTION_WIDTH")?;
let height = get_env_var_as_u16("RESOLUTION_HEIGHT")?;

Ok(FragmentTask {
id: U8Data {
offset: 0,
count: 16,
},
fractal: FractalDescriptor {
fractal_type: IteratedSinZ(IteratedSinZDescriptor {
c: Complex { re: 0.2, im: 1.0 },
}),
},
max_iteration: 64,
resolution: Resolution { nx: width, ny: height },
range: Range {
min: Point {
x: -2.0,
y: -3.55556,

let range = generate_range(Range::new(Point::new(-3.0, -3.0), Point::new(3.0, 3.0)), 2.0);
let mut tasks = vec![];

for r in range {
let task = FragmentTask {
id: U8Data {
offset: 0,
count: 16,
},
max: Point { x: 2.0, y: 3.55556 },
},
})
fractal: FractalDescriptor {
fractal_type: IteratedSinZ(IteratedSinZDescriptor {
c: Complex { re: 0.2, im: 1.0 },
}),
},
max_iteration: 64,
resolution: Resolution { nx: width, ny: height },
range: r,
};

tasks.push(task);
}

Ok(tasks)

}

pub fn generate_range(full_image: Range) -> Vec<Range> {
let mut ranges = vec![];
for y in (full_image.min.y..full_image.max.y).step_by(2) {
for x in (full_image.min.x..full_image.min.x).step_by(2) {
pub fn process_result(_result: FragmentResult) {



}



pub fn generate_range(full_image: Range, step: f64) -> Vec<Range> {
let mut ranges = Vec::new();
let y_step = step;
let x_step = step;

let mut y = full_image.min.y;
while y < full_image.max.y {
let mut x = full_image.min.x;
while x < full_image.max.x {
let min = Point::new(x, y);
let max = Point::new(x + 2, y + 2);
let max = Point::new((x + x_step).min(full_image.max.x), (y + y_step).min(full_image.max.y));
ranges.push(Range::new(min, max));
x += x_step;
}
y += y_step;
}
ranges
}

63 changes: 49 additions & 14 deletions server/src/messages/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,11 @@ use std::{
io::{self, Read},
net::TcpStream,
};
use image::{GrayImage, ImageBuffer, Luma, Rgb};

use log::{debug, error, info};
use shared::{types::{color::{HSL, RGB}, messages::Message, pixel_intensity::{self, PixelIntensity}, resolution::Resolution}, utils::{colors_utils::color, fragment_task_impl::FragmentTaskOperation}};
use shared::{types::{error::FractalError, filesystem::FileExtension, messages::Message, pixel_intensity::PixelIntensity}, utils::{filesystem::{get_dir_path_buf, get_extension_str, get_file_path}, fragment_task_impl::FragmentTaskOperation, image::image_from_pixel_intensity}};

use super::{
fragment_maker::{create_task_for_request, process_result},
serialization::deserialize_message,
};
use crate::services;
use super::serialization::deserialize_message;
use crate::{messages::fragment_maker::create_tasks, services};

/// Handles a client TCP stream.
///
Expand Down Expand Up @@ -88,15 +83,18 @@ pub fn handle_client(mut stream: TcpStream) -> io::Result<()> {
debug!("Deserialized data {:?}", message_result);

match message_result {
Ok(Message::FragmentRequest(request)) => {
let task = match create_task_for_request(request) {
Ok(task) => task,
Ok(Message::FragmentRequest(_request)) => {
let task = match create_tasks() {
Ok(task) => task[0].clone(),
Err(e) => {
error!("Error creating task: {:?}", e);
return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"));
}
};


debug!("Task created: {:?}", task.clone());


let serialized_task = match task.serialize() {
Ok(serialized_task) => serialized_task,
Err(e) => {
Expand All @@ -118,8 +116,45 @@ pub fn handle_client(mut stream: TcpStream) -> io::Result<()> {
Ok(Message::FragmentTask(_task)) => {
todo!()
}
Ok(Message::FragmentResult(result)) => {
process_result(result);
Ok(Message::FragmentResult(_result)) => {
//process_result(result);

let img = match image_from_pixel_intensity(pixel_intensity) {
Ok(img) => img,
Err(e) => {
error!("Error creating image from pixel intensity: {:?}", e);
return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"));
}
};

let dir_path_buf = match get_dir_path_buf() {
Ok(dir_path_buf) => dir_path_buf,
Err(e) => {
error!("Error getting directory path: {:?}", e);
return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"));
}
};

let img_path: String = match get_file_path("tondaronla", dir_path_buf, get_extension_str(FileExtension::PNG)) {
Ok(img_path) => img_path,
Err(e) => {
error!("Error getting file path: {:?}", e);
return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"));
}
};


match img.save(img_path.clone()).map_err(FractalError::Image) {
Ok(_) => {
info!("Image saved successfully");
debug!("Image path {}", img_path);
}
Err(e) => {
error!("Error saving image: {:?}", e);
return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"));
}
}

}
Err(e) => {
error!("Error deserializing request: {:?}", e);
Expand Down
2 changes: 1 addition & 1 deletion server/src/messages/serialization.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use log::debug;
use serde::de::{self, Error as SerdeError};
use serde::de::Error as SerdeError;

use shared::{
types::messages::{FragmentRequest, FragmentResult, Message},
Expand Down
1 change: 0 additions & 1 deletion server/src/services/server_runner.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use log::{error, info};
use shared::types::resolution::Resolution;

use crate::messages::handler::handle_client;
use std::net::TcpListener;
Expand Down
2 changes: 1 addition & 1 deletion shared/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ path = "src/lib.rs"
rand = "0.8.5"
serde = { version = "1.0.193", features = ["derive"] }
serde_json ="1.0.108"
env_logger = "0.10.1"
env_logger = "0.11.2"
log = "0.4.20"
image = { version = "0.24.7", features = [] }

Expand Down
17 changes: 17 additions & 0 deletions shared/src/types/point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,20 @@ pub struct Point {
pub x: f64,
pub y: f64,
}

impl Point {
/// Creates a new `Point` with the specified x and y coordinates.
///
/// # Arguments
///
/// * `x` - A `f64` representing the x-coordinate of the point.
/// * `y` - A `f64` representing the y-coordinate of the point.
///
/// # Returns
///
/// A new `Point` with the specified x and y coordinates.
pub fn new(x: f64, y: f64) -> Point {
Point { x, y }
}

}
17 changes: 17 additions & 0 deletions shared/src/types/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,20 @@ pub struct Range {
pub min: Point,
pub max: Point,
}

impl Range {
/// Creates a new `Range` with the specified minimum and maximum points.
///
/// # Arguments
///
/// * `min` - A `Point` defining the minimum (bottom-left) corner of the range.
/// * `max` - A `Point` defining the maximum (top-right) corner of the range.
///
/// # Returns
///
/// A new `Range` with the specified minimum and maximum points.
pub fn new(min: Point, max: Point) -> Self {
Range { min, max }
}
}

9 changes: 5 additions & 4 deletions shared/src/utils/colors_utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{types::{color::{HSL, RGB}, pixel_intensity::PixelIntensity}, utils::type_of::type_of};
use crate::{types::{color::{HSL, RGB}, pixel_intensity::PixelIntensity}}
;

///Generates a color based on the provided pixel intensity.
/// # Arguments
Expand Down Expand Up @@ -64,9 +65,9 @@ fn test_color() {

let result = color(pixel_intensity);

let test0 = type_of(result[0]);
let test1 = type_of(result[1]);
let test2 = type_of(result[2]);
let test0 = crate::utils::type_of::type_of(result[0]);
let test1 = crate::utils::type_of::type_of(result[1]);
let test2 = crate::utils::type_of::type_of(result[2]);

assert!(test0.eq("u8"));
assert!(test1.eq("u8"));
Expand Down
10 changes: 7 additions & 3 deletions shared/src/utils/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ use image::{ImageBuffer, Rgb};

use crate::types::{pixel_intensity::PixelIntensity, resolution::Resolution};

use super::colors_utils::color;
use super::{colors_utils::color, env_utils::get_env_var_as_u16};



pub fn image_from_pixel_intensity(pixel_intensity: &[PixelIntensity], resolution: Resolution) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
pub fn image_from_pixel_intensity(pixel_intensity: Vec<PixelIntensity>) -> Result<ImageBuffer<Rgb<u8>, Vec<u8>>, Box<dyn std::error::Error>> {
let width = get_env_var_as_u16("RESOLUTION_WIDTH")?;
let height = get_env_var_as_u16("RESOLUTION_HEIGHT")?;

let resolution = Resolution::new(width, height);
let mut img = ImageBuffer::new(resolution.nx.into(), resolution.ny.into());
for (i, pixel_intensity) in pixel_intensity.iter().enumerate() {
let x = (i % 250 as usize) as u32;
Expand All @@ -15,5 +19,5 @@ pub fn image_from_pixel_intensity(pixel_intensity: &[PixelIntensity], resolution
img.put_pixel(x, y, Rgb(color(*pixel_intensity)));
}

img
Ok(img)
}

0 comments on commit 64a80e8

Please sign in to comment.