#How to color specific pixels on a sprite's image?

1 messages · Page 1 of 1 (latest)

tough stratus
#

The full code of the program is as follows:

use bevy::{
    prelude::*,
    window::WindowResolution,
};

const WIDTH: usize = 240;
const HEIGHT: usize = 240;
const ITERATIONS: usize = 50;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                resolution: WindowResolution::new(WIDTH as f32, HEIGHT as f32),
                title: String::from("Mandelbrot Set"),
                ..default()
            }),
            ..default()
        }))
        .add_systems(Startup, (spawn_camera, spawn_visual, color_pixels_in_viewport).chain())
        .run();
}

fn spawn_camera(mut cmds: Commands) {
    cmds.spawn(Camera2dBundle::default());
}

#[derive(Resource, Deref, DerefMut)]
struct VisualTexture(Handle<Image>);

fn spawn_visual(mut cmds: Commands, asset_server: Res<AssetServer>) {
    let tex = asset_server.load("base.png");
    cmds.spawn(SpriteBundle {
        texture: tex.clone(),
        ..default()
    });
    cmds.insert_resource(VisualTexture(tex));
}
#
fn color_pixels_in_viewport(cam_qry: Query<(&Camera, &GlobalTransform)>, mut images: ResMut<Assets<Image>>, visual_tex: Res<VisualTexture>) {
    let (cam, cam_glob_xform) = cam_qry.single();
    let Some(img) = images.get_mut(visual_tex.clone()) else { return };

    for y in 0..HEIGHT {
        for x in 0..WIDTH {
            let Some(c) = cam.viewport_to_world_2d(cam_glob_xform, Vec2::new(x as f32, y as f32))
            else {
                continue;
            };
            let mut z = Vec2::ZERO;
            let mut successful_iterations = 0;

            for _ in 0..ITERATIONS {
                z = f(z, c);

                if z.x + z.y > 2. {
                    break;
                }
                successful_iterations += 1;
            }

            // color current pixel in image
        }
    }
}

/*
f : C  -> C
    z |-> z^2 + c
*/
fn f(z: Vec2, c: Vec2) -> Vec2 {
    /*
    z^2 = (a + bi)^2
        = (a + bi)(a + bi)
        = a^2 + 2abi - b^2
        = (a^2 - b^2) + 2abi <=> <x^2 - y^2, 2xy>
    */
    Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c
}
#

I'm starting with a small iteration count and resolution for testing purposes

#

I also plan to parallelize the coloring function so it's fast and works in realtime when I'm zooming into the image and whatnot