Algoritmo para generar lineas

En clase hicimos un ejercicio para dibujar lineas de la forma: y=mx +b en la pantalla, de tal suerte que elegimos que pixel representa al elemento de la linea de la mejor forma. El código me pareció divertido, esta hecho usando la librería Allegro (obsoleta dicen por ahí) pero bastante útil para programar en 5 minutos XD.

/*
YESICA HERNANDEZ HERNANDEZ
COMPUTACION GRAFICA
PROGRAMA PARA DIBUJAR LINEAS EN LA PANTALLA

INSTRUCIONES:
CON LA TECLA ESC CERRAMOS LA VENTANA
DESCRIPCION:
EN ESTE CODIGO SE USO LA LIBRERIA GRAFICA ALLEGRO
SE IMPLEMENTA EL ALGORTIMO VISTO EN CLASE PARA DIBUJAR LINEAS
PIXEL POR PIXEL, CONOCIENDO DOS PUNTOS QUE PERTENECEN A ELLA,
SE PINTAN 600 COORDENADAS ANTES DE FINALIZAR LA ANIMACION.
LOS VALORES DE LAS COORDENADAS SE DEBEN DAR AL PROGRAMA COMO
PARAMETROS, EJEMPLO:
Linea.exe 20.0 86.0 44.0 11.0
EN DONDE TENEMOS:
Linea.exe x1 y1 x2 y2
*/
#include
#include

//VARIABLE PARA MANIPULAR LOS PIXELES COLOREADOS
float vi[2],vf[2],vx[2],px,m,dx,dy;
int contador;


//DECLARACIONES DE LAS FUNCIONES
void init();
void deinit();
int linea();
void titulo();
void get_values();

//-------------------------------------MAIN -------------------------
int main(int arg, char** val){

//Agregando valores iniciales, transformados a numeros:
vi[0]=atof(val[1]);
vi[1]=atof(val[2]);
vf[0]=atof(val[3]);
vf[1]=atof(val[4]);

dx=vf[0]-vi[0];
dy=vf[1]-vi[1];
m = dy/dx;
//Inicializamos los metodos de la libreria,
// grafics, teclado, mouse y temporizadores
init();
//imprimimos informacion sobre el programa en pantalla (mis datos)
titulo();
get_values();
//bucle principal de eecucion
while (!key[KEY_ESC]) {
//llamamos a la rutina para colorear pixeles aleatoriamente
if(linea()==1){
//hacemos una pausa de 0.2 segundos
rest(100);
}else break;
}
//llamada a las rutinas de finalizacion de allegro
deinit();
return 0;
}
END_OF_MAIN()


void get_values(){
rectfill(screen, 290, 10, 590, 40, makecol(40,20, 30));
textprintf_ex(screen, font, 300, 20, makecol(202,255, 112),-1, "Puntos de la recta:");
textprintf_ex(screen, font, 300, 30, makecol(202,255, 112),-1,"(%3.1f,%3.1f) (%3.1f,%3.1f)",vi[0],vi[1],vf[0],vf[1]);
}

/*
esta funcion pinta pixeles aleatoriamente en la pantalla, cuyo tamaño
definimos como 600x480
*/
int linea(){
int edo=1;
//generamos valores aleatorios dentro de ciertos rangos por
//medio del modulo
if(contador>0){
int r = rand()%255;
int g = rand()%255;
int b = rand()%255;
//incluimos el pixel en pantalla
putpixel (screen,vx[0],430- vx[1], makecol(r, g, b));
// hacemos el reemplazo por el siguiente pixel
if(px<0){
vx[0]++;
px=px+dy;
}
else if(px>=0){
vx[0]++;
vx[1]++;
px = (2*dy)-(2*dx)+px;
}
// NOS ASEGURAMOS QUE SOLO SE PINTEN 600 PUNTOS PERTENECIENTES A LA RECTA
contador--;
}else edo = 0;
return edo;
}

/*
funcion para mostrar en pantalla mis datos
*/
void titulo(){
textprintf(screen, font, 20, 430, makecol(0,197, 205), "YESICA HERNANDEZ HERNANDEZ / Computacion Grafica");
textprintf(screen, font, 10, 440, makecol(72,209, 174), ".................ALGORITMO PARA LINEA.................");
textprintf(screen, font, 20, 460, makecol(202,255, 112), "Presione ESC para cerrar");
}


/*
funcion que inicializa los elementos de allegro, necesaria para establecer
el modo de pantalla, la profundidad
de colo el tamaño de la venta y el estado de la misma.
TAMBIEN ESTABLECEMOS LA SEMILLA A UTILIZAR PARA LOS
NUMEROS ALEATORIOS
*/
void init() {
int depth, res;
allegro_init();
depth = desktop_color_depth();
if (depth == 0) depth = 32;
set_color_depth(depth);
res = set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
if (res != 0) {
allegro_message(allegro_error);
exit(-1);
}
srand (time(0));
install_timer();
install_keyboard();
//incializamos las variables de calculo;
contador=600;
vx[0]=vi[0];
vx[1]=vi[1];
px=(2*dy)-dx;

}
/*FUNCION DE ALLEGRO QUE LIMPIA EL BUFFER DEL TECLADO*/
void deinit() {
clear_keybuf();
}
¿Que se necesita para probar este codigo?
Tener la librería Allegro instalada,
si se prueba desde el IDE de desarrollo, poner los parámetros en la configuración de ejecución
si se prueba desde un shell/linea de comandos, probar con la sintaxis expuesta en los comentarios


No hay comentarios:

Publicar un comentario