Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Grafica pe calculator / Geometrie computationala
Computer Graphics / Computation Geometry
Titular curs : Conf. Dr. Marin Vlada, Universitatea din Bucuresti
WEB: http://marinvlada.googlepages.com/, www.ad-astra.ro/marinvlada
E-mail: marinvlada[at]yahoo.com, marinvlada[at]gmail.com
Course: COMPUTER GRAPHICS | Bachelor of Science (Computer Science)
Software: C++, OpenGL, Java 3D, Java Script, VRML, SVG
http://marinvlada.googlepages.com/prog_grafic.htm
©
www.cniv.ro
www.icvl.eu
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
PROIECT – generare litere folosind curbe B-spline Nota: Codul in C++
Curbe B-spline si aplicatii
Fata de curbele Bezier, curbele B-spline sunt descrise prin functii polinomiale (de gr. II
si III) definite pe portiuni.
Curbele B-spline de gradul II (parabolice) sunt utilizate la generarea caracterelor
pentru fonturile True Type ( .ttf) din sistemul Windows, iar curbele B-spline de gradul
III (cubice) sunt utilizate la generarea caracterelor pentru fonturile PostScript ( .ps).
Curbele B-spline de gradul II (parabolice)
Daca se considera o linie poligonala formata din 3 puncte Pi(xi, yi), i=1,2, 3, atunci
aceasta se aproximeaza cu o curba B-spline ce are o extremitate in mijlocul segmentului
P1 P2, iar cealalta extremitate se afla in mijlocul segmentului P2 P3 , curba fiind un arc
de parabola (curba de gradu II) definit de drumul (aplicatia) :
γ : [0,1] � R2, unde γ (t) = (x(t), y(t)),
x(t) = a x1 + b x2 + c x3
y(t) = a y1 + b y2 + c y3 , pentru t ∈ [0,1] , notatiile fiind
a = (1 – 2t + t2 )/2 , b = (1 + 2t -t
2 ) /2, c = t
2 /2, a+b+c = 1
P2
γ
P1 P3
Evident, pentru t=0 si t=1 avem, respectiv
γ (0) = (x(0), y(0)), x(0) = (x1 + x2)/2 , y(0) = (y1+y2)/2 si
γ (1) = (x(1), y(1)), x(1) = (x2 + x3)/2 , y(1) = (y2+y3)/2
Definitie.
Linia poligonala P = P1 P2 ... Pn , unde Pi(xi, yi), i=1,2, … ,n , se aproximeaza cu o
curba B-spline γ = γ1 ∪ γ 2 ∪ ... ∪ γn-2 , avand urmatoarele proprietati ;
a) are extremitatile in mijloacele segmentolor P1 P2 si Pn-1 Pn ;
b) segmentele Pi Pi+1 , i=1,2, …, n-1 sunt tangente la curba in mijloacele segmentelor Pi
Pi+1.
c) curba este definita pe portiuni de γi : [0,1] � R2, unde γi (t) = (x(t), y(t)),
i=1,2, … ,n-2 si
x(t) = a xi + b xi+1 + c xi+2
y(t) = a yi + b yi+1 + c yi+2 , pentru t ∈ [0,1] , notatiile fiind
a = (1 – 2t + t2 )/2 , b = (1 + 2t -t
2 ) /2, c = t
2 /2, a+b+c = 1
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
In figura urmatoare se prezinta aceste proprietati.
P2 P4 . . . . . Pn -2 Pn
γ1 γ2 γ3 γn-2
P1 P3 Pn -1
Programul realizeaza generarea literelor mari de tip cursiv prin citirea coordonatelor
unor puncte ce reprezinta o linie poligonala cu punctele aflate pe conturul literei. Un
exemplu de astfel de litere este prezentat mai jos.
Program litereM.cpp
#include <graphics.h> #include <conio.h> #include <math.h> #include <iostream.h> int gd, gm; int n, i, j, k, ii, d, max, xx, yy; int x[200]; int y[200]; float a, b, c, p, t; int round(float nr) { int aux=nr; nr=nr*10; int val=(int)nr % 10; if (val>=0&&val<5) return aux; else return aux+1; } int LUNG() // pentru pasul de discretizare; nr. de diviziuni { max = 0; for (int ii = i; ii <= i+1; ii++)
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
{ d = abs ( x[ii] - x[ii+1] ); if (d > max) max = d; d = abs ( y[ii] - y[ii+1] ); if (d > max) max = d; } return max; } void CURBA() { p = 1.0 / LUNG(); // pasul de discretizare pe [0,1] t = 0; //{initializare; parcurgerea intervalului [0,1] } for (ii = 1; ii <= LUNG(); ii++) { a = 1 - t ; a = (a*a)/2; c = (t*t)/2 ; b = 1 - a - c: xx = round (a*x[i] + b*x[j] + c*x[k]); yy = getmaxy() - round( a*y[i] + b*y[j] + c*y[k]); lineto ( xx, yy) ;// { se traseaza linie } t = t + p; } } void main() { cout <<" Dati nr. de puncte n= "; cin >>n; cout <<" Dati coordonatele punctelor "; for(i = 1; i <= n; i++) { cin >> x[i]; cin >> y[i]; } gd = DETECT; initgraph (&gd, &gm, "C:\\Borlandc\\bgi"); moveto (x[1],getmaxy()-y[1]); xx = round((x[1]+x[2])/2); yy = getmaxy ()-round((y[1]+y[2])/2); lineto(xx, yy); for(i = 1; i <= n-2; i++) { j=i+1; k=i+2; CURBA (); } lineto(x[n],getmaxy()-y[n]); getch(); closegraph(); }
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Date pentru testare ( nr. puncte si coordonate)
PROIECT – generare litere mici - editare Nota: Codul in C++
Programul realizeaza generarea literelor mici de tip cursiv prin citirea dintr-un fisier a
unui numar de puncte ce reprezinta o linie poligonala cu punctele aflate pe conturul
literei.
13 150 300 125 350 150 400 225 350 230 220 240 150 280 75 320 150 330 220 335 350 410 400 435 350 410 300 5 140 260 210 210 280 235 350 260 420 210 4 100 100 130 85 160 110 210 350 15 130 330 180 380 250 410 300 380 320 330 310 290 280 250 230 200 130 220 230 230 280 130 320 90 340 120 330 140 310 110
13 150 180 125 130 150 80 225 130 230 260 240 330 280 405 320 330 330 260 335 130 410 80 435 130 410 180 5 140 220 210 270 280 245 350 220 420 270 4 100 100 130 85 160 110 210 350 15 130 330 180 380 250 410 300 380 320 330 310 290 280 250 230 200 130 220 230 230 280 130 320 90 340 120 330 140 310 110
15 130 330 180 380 250 410 300 380 320 330 310 290 280 250 230 200 130 220 230 230 280 130 320 90 340 120 330 140 310 110 5 10 10 100 200 200 10 250 200 300 10
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Programul litere.cpp // utilizeaza curbe B-spline parbolice #include<stdio.h> #include<dos.h> #include<graphics.h> #include<stdlib.h> #include<io.h> #include<conio.h> #include<ctype.h> int n,i,j,k,ii,d,max,x=1,y=450,xx,yy,x1[100],y1[100]; float a,b,c,p,t; //functie "round" pentru rotunjire //---------------------------------------------------- int round(float nr) { int aux=nr; nr=nr*10; int val=(int)nr % 10; if (val>=0&&val<5) return aux; else return aux+1; } //sfarsit functie round //---------------------------------------------------- //functie "lung" //---------------------------------------------------- int lung() // determina numarul de diviziuni ptr. discretizare { max=0; for (int ij=i;ij<=i+1;ij++) { d =abs(x+x1[ij]-(x+x1[ij+1])); if (d>max) max=d; d=abs(y+y1[ij]-(y+y1[ij+1])); if (d>max) max=d; } return max; } //sfarsit functie lung //----------------------------------------------- //procedura "curba" //----------------------------------------------- void curba() { p=1.0/lung(); // pasul de discretizare t=0; for (ii=1;ii<=lung();ii++) { a=1-t; a=(a*a)/2; c=(t*t)/2; b=1-a-c:
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
xx=round(a*(x+x1[i])+ b*(x+x1[j])+c*(x+x1[k])); yy=getmaxy()-round(a*(y+y1[i])+b*(y+y1[j])+c*(y+y1[k]));
lineto(xx,yy); t=t+p; } } //sfarsit procedura curba //--------------------------------------------------- // procedura "litera" //--------------------------------------------------- void litera(int x2,int y2,FILE *fp) { fscanf(fp,"%d",&n); while (n !=5000) { for (i=1;i<= n;i++) fscanf(fp," %d %d",&x1[i],&y1[i]); moveto(x2+x1[1],getmaxy()-(y2+y1[1])); xx=round(((x2+x1[1])+(x2+x1[2]))/2); yy=getmaxy()-round(((y2+y1[1])+(y2+y1[2]))/2); lineto(xx, yy); for(i =1;i<=n-2;i++) { j=i+1;k=i+2; curba(); } //lineto(x2+x1[n],getmaxy()-y2+y1[n]); fscanf(fp,"%d",&n); } }//sfarsit procedura litera //----------------------------------------------- //partea principala "main" void main(){ FILE *f; char *c; int gdriver = DETECT, gmode, errorcode,ch,bool=1,val; initgraph(&gdriver, &gmode, "c:\\borlandc\\bgi"); errorcode = graphresult(); if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); } for(int i1=1; i1<=15; i1++) { setcolor(i1); setfillstyle(1,i1); circle(i1*18,30,5); fillellipse(i1*18,30,5,5);
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
outtextxy(i1*18-3,38,itoa(i1,c,10)); outtextxy(20,48,"Alegeti una din culorile de mai sus pentru editare prin scirerea cifrei!!!");
} gotoxy(2,5); printf("Culoare="); scanf("%d",&val); delay(400); // asteptare … cleardevice(); setcolor(val); outtextxy(20,48,"Puteti incepe editarea!!!"); sleep(2); cleardevice(); while(bool) { ch=toascii(getch()); if (!kbhit()) { switch(ch) { case 32 : if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 97 : f=fopen("c:\\borlandc\\bin\\a.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 98 : f=fopen("c:\\borlandc\\bin\\b.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 99 : x=x-8; f=fopen("c:\\borlandc\\bin\\c.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 100 :f=fopen("c:\\borlandc\\bin\\d.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 101 :f=fopen("c:\\borlandc\\bin\\e.txt","r"); litera(x,y,f); fclose(f); if ((x+=18)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
case 102 :f=fopen("c:\\borlandc\\bin\\f.txt","r"); litera(x,y,f);
fclose(f);
if ((x+=19)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 103 :f=fopen("c:\\borlandc\\bin\\g.txt","r"); litera(x,y,f); fclose(f); if ((x+=17)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 104 :f=fopen("c:\\borlandc\\bin\\h.txt","r"); litera(x,y,f); fclose(f); if ((x+=19)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 105 :f=fopen("c:\\borlandc\\bin\\i.txt","r"); litera(x,y,f); putpixel(x+11,getmaxy()-y-20,15); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 106 :f=fopen("c:\\borlandc\\bin\\j.txt","r"); litera(x,y,f); putpixel(x+11,getmaxy()-y-20,15); fclose(f); if ((x+=16)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 107 :f=fopen("c:\\borlandc\\bin\\k.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 108 :f=fopen("c:\\borlandc\\bin\\l.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 109 :f=fopen("c:\\borlandc\\bin\\m.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 110 :f=fopen("c:\\borlandc\\bin\\n.txt","r"); litera(x,y,f); fclose(f); if ((x+=17)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
case 111 :f=fopen("c:\\borlandc\\bin\\o.txt","r"); litera(x,y,f); fclose(f);
if ((x+=18)>getmaxx()-30) {x=1;y-=30;};
if (y<50) {cleardevice();y=450;} break; case 112 :f=fopen("c:\\borlandc\\bin\\p.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 113 :f=fopen("c:\\borlandc\\bin\\q.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 114 :f=fopen("c:\\borlandc\\bin\\r.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 115 :f=fopen("c:\\borlandc\\bin\\s.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 116 :f=fopen("c:\\borlandc\\bin\\t.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 117 :f=fopen("c:\\borlandc\\bin\\u.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 118 :f=fopen("c:\\borlandc\\bin\\v.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 119 :f=fopen("c:\\borlandc\\bin\\w.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 120 :f=fopen("c:\\borlandc\\bin\\x.txt","r"); litera(x,y,f);
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break;
case 121 :f=fopen("c:\\borlandc\\bin\\y.txt","r");
litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 122 :f=fopen("c:\\borlandc\\bin\\z.txt","r"); litera(x,y,f); fclose(f); if ((x+=20)>getmaxx()-30) {x=1;y-=30;}; if (y<50) {cleardevice();y=450;} break; case 13 : x=1; if((y=y-30)<50) {cleardevice();y=450;} break; default: bool=0; } } }; closegraph(); }
Fsiere de intrare :
15 fisiere pentru generarea literelor A-O de tip cursiv
OBSERVATIE : f=fopen("c:\\borlandc\\bin\\a.txt","r");
sfarsit de fisier= 5000
a.txt b.txt c.txt d.txt e.txt
15 20 7 19 2 14 0 11 2 12 3 12 9 11 14 5 17 1 13 -1 7 1 1 6 0 11 1 12 3
12 0 7 1 1 5 0 13 13 10 28 3 13 14 0 18 5 16 9 15 7 17 5 22 8
5000
c.txt
7 20 6 19 1 15 0 7 4 10 17 15 16 17 13
5000
13 20 7 19 2 14 0 11 2 12 3 12 8 5 16 0 7 1 1 6 0 11 1 12 3 12 45 5000
10 0 3 1 1 5 0 13 13 10 17 3 13 14 0 18 5 16 9 15 7 5000
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
12 15
5000
f.txt g.txt h.txt i.txt j.txt
15 0 3 1 1 5 0 13 13 10 28 4 13 7 4 7 -2 7 -7 7 -2 7 4 8 1 13 0 19 2 15 6
5000
15 11 2 12 3 12 8 5 16 0 7 1 1 6 0 11 1 12 5 12 -7 9 -10 5 -4 9 0 12 5 22 7 5000
15 0 7 1 1 5 0 13 13 10 28 3 13 8 4 8 -2 8 4 11 8 14 4 15 3 14 0 17 0 21 5
5000
11 1 6 2 1 5 0 9 2 11 6 11 16 11 6 10 2 15 0 19 1 20 7 5000
j.txt
11 1 6 2 1 5 0 11 16 11 6 11 -7 9 -10 5 -4 9 0 12 5 22 7 5000
k.txt l.txt m.txt n.txt o.txt
17 0 7 1 1 5 0 13 13 10 28 3 13 8 4 8 -2 8 4 11 8 14 4 15 3 10 2 15 1 14 0 17 -1 23 5
5000
9 0 7 1 1 5 0 13 13 10 28 3 13 14 0 18 5 22 7
5000
14 0 8 3 16 5 11 5 0 5 11 7 16 10 11 10 0 10 11 13 16 15 11 15 3 17 0 22 11 5000
10 0 8 3 16 5 11 5 0 5 11 7 16 10 11 10 3 15 0 17 11 5000
11 10 14 14 11 12 4 8 0 2 1 0 6 2 12 4 18 12 15 8 7 25 11 5000
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Proiect - EDITOR si curbe B-spline Nota: Codul in Pascal/Delphi {program editor introd. puncte plus aproximarea liniei poligonale cu curbe bspline -initial cursorul se pozitioneaza in mijloc -se misca cu tastele sageti -se pozitioneaza pe punct cu enter -se termina introducerea punctelor cu tasta ESC -programul se termina cu tasta ENTER }
uses crt,graph; const esc=#27; enter=#13; sus=#72; jos=#80; dr=#77; st=#75; raz=5; var gd,gm:integer; ii,i,j,k,d,max,xx,yy:integer; x,y,xu,yu:integer; lx,ly:integer; ch:char; vx:array[0..100]of integer; vy:array[0..100]of integer; nk:integer; a,b,c,p,t:real; function lung:integer; begin max:=0; for ii:=i to i+1 do begin c:=abs(vx[ii]-vx[ii+1]); if d>max then max:=d; c:=abs(vy[ii]-vy[ii+1]); if d>max then max:=d; end; lung:=max; end; procedure curba; begin p:=1/lung; t:=0; for ii:=1 to lung do begin a:=1-t;a:=(a*a)/2;c:=(t*t)/2;b:=1-a-c: xx:=round(a*vx[i]+b*vx[j]+c*vx[k]); yy:=round(a*vy[i]+b*vy[j]+c*vy[k]); lineto(xx,yy); t:=t+p;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
end; end;
procedure bspline; begin moveto(vx[1],vy[1]); xx:=round((vx[1]+vx[2])/2); yy:=round((vy[1]+vy[2])/2); lineto(xx, yy); for i:=1 to nk-2 do begin j:=i+1;k:=i+2; curba; end; lineto(vx[nk],vy[nk]); end; procedure draw_cursor(xc,yc:integer); begin moveto (xc,yc);linerel(lx,0); moveto (xc,yc);linerel(-lx,0); moveto (xc,yc);linerel(0,ly); moveto (xc,yc);linerel(0,-lx); end; BEGIN gc:=detect; initgraph(gd,gm,'c:\TP\BGI'); lx:=(getmaxx+1)div 50; ly:=(getmaxy+1)div 50; SetWriteMode(XorPut); x:=GetMaxX div 2; y:=GetMaxY div 2; nk:=1; repeat draw_cursor(x,y); ch:=readkey; xu:=x; yu:=y; case ch of enter:begin if nk=1 then begin VX[nK]:=XU; VY[nK]:=YU; nk:=nk+1; circle(xu,yu,raz); end else begin circle(xu,yu,raz); line(vx[nk-1],vy[nk-1],xu,yu); VX[NK]:=XU; VY[NK]:=YU; nK:=nK+1; end; end; sus:begin
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
yu:=y-5; end; jos:begin
yu:=y+5;
end; dr:begin xu:=x+7; end; st:begin xu:=x-7; end; end; draw_cursor(x,y); x:=xu; y:=yu; until ch=esc: cleardevice; SetWriteMode(NormalPut); NK:=NK-1; bspline; readln; closegraph; END.
PROIECT –jocul “sarpe” Nota: Codul in C++
Sarpe.cpp
#include<conio.h> #include<stdlib.h> #include<dos.h> #include<stdio.h> #include<graphics.h> #include<ctype.h> int ch,i,j,f,r,a[10][2],s=0,len=30; unsigned int time0=0; FILE *fp; struct q { int x1,x2,y1,y2; }q[100]={320,320,210,210},t={320,320,210,210},c; void push(struct q t); struct q pop(void); void sq(void); void chk(void); void initializare() { int gdriver = DETECT, gmode, errorcode;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
initgraph(&gdriver, &gmode, "c:\\borlandc\\bgi"); errorcode = graphresult(); if (errorcode != grOk)
{ printf("Eroare: %s\n", grapherrormsg(errorcode)); printf("Apasa orice tasta pentru iesire!"); getch(); exit(1); } } void push(struct q t) { f++; q[f].x1=t.x1; q[f].y1=t.y1; q[f].x2=t.x2; q[f].y2=t.y2; }; struct q pop(void) { r++; return(q[r-1]); }; //procedura de verificare void chk(void) { for(i=0;i<15;i++) { //verifica daca s-a capturat ceva if (((c.x2 - a[i][0] < 4) && (c.x2 - a[i][0] > - 4)) && ((c.y2 - a[i][1] < 4) && (c.y2 - a[i][1] > - 4)) && a[i][0] != 0) { s++; len+=4; time0=time0-25; delay(50); gotoxy(65,5); printf(" \a Score : %d",s); if(s >= 10) { closegraph(); printf("Felicitari ai castigat!"); printf(" \nApasa orice tasta pentru a iesi!"); while(!kbhit()) { sound(random(2000)); delay(100); } nosound(); exit(0); } setcolor(WHITE);
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
circle(a[i][0],a[i][1],2); a[i][0]=a[i][1]=0; }
} //verifica daca se intalneste capul cu corpul for(i=r;i<=f;i++) { if ((q[i].x1 == c.x2) && (q[i].y1 == c.y2)) { closegraph(); exit(0); } } //verifica daca s-a lovit capul de margine if(c.x2 <= 30 || c.x2 >= 500 || c.y2 <= 20 || c.y2 >= 460) { closegraph(); exit(0); } } main() { initializare(); randomize(); setbkcolor(LIGHTBLUE); c.x1=c.x2=320; c.y1=c.y2=210; setcolor(YELLOW); rectangle(30,20,500,460); setcolor(RED); for(i=0;i<10;i++) { a[i][0]=45+random(450); a[i][1]=30+random(425); circle(a[i][0],a[i][1],2); } setlinestyle(SOLID_LINE,2,3); while(1) { ch=toascii(getch()); while(!kbhit()) { t=c; switch(ch) { case 72 : // Sus t.x1=t.x2; t.y1=t.y2; t.y2=t.y1-5; break;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
case 80 : // Jos t.x1=t.x2; t.y1=t.y2; t.y2=t.y1+5;
break;
case 75 : // Stanga t.y1=t.y2; t.x1=t.x2; t.x2=t.x1-5; break; case 77 : // Dreapta t.y1=t.y2; t.x1=t.x2; t.x2=t.x1+5; break; case 27 : closegraph(); // Esc exit(0); default: printf("\a");break; } c=t; setcolor(LIGHTRED); push(t); line(t.x1,t.y1,t.x2,t.y2); if ((f - r) > len) { t=pop(); setcolor(LIGHTBLUE); line(t.x1,t.y1,t.x2,t.y2); } chk(); sq(); delay(50); gotoxy(65,10); textcolor(7); printf("Time : %u",time0++); if (time0 >= 1200 ) { closegraph(); delay(2000); getch(); exit(0); } }; }; } void sq(void) { if (r > 8) { for(i=r;i<=f;i++) q[i-r]=q[i]; f=f-r; r=0; }
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
return; }
PROIECT – sistemul solar Nota: Codul in C++
Program planete.cpp
#include <stdio.h> /* Program ce simuleaza miscarea de revolutie */ #include <graphics.h> /* a celor 9 planete din sistemul solar */ #include <stdlib.h> #include <conio.h> /* Program realizat de Irimia Bogdan */ #include <math.h> /* sub indrumarea */ #include <dos.h> #include <string.h> /* Conf.dr. Vlada Marin */ float rotmercur = 360.0/88.0, rotvenus = 360.0/225.0, rotpamant = 360.0/365.0; float rotluna = 360.0/28.0, rotmarte = 360.0/686.98; float rotjupiter = 360.0/4307.0, rotsaturn = 360.0/10731.0; float roturanus = 360.0/30660.0, rotneptun = 360.0/60115.5; float rotpluto = 360.0/90465.0; void soare(int raza) { setcolor(14); /* deseneaza soarele */ setfillstyle(1,14); fillellipse(0,0,raza,raza); } //---------------------------------------------------------- /* desenarea planetei */ void drawplanet(float deplasare, int razax, int razay, int culoare, int raza ,int saturn = 0, int luna = 0) { float u=0,x=0, y=0; u = 2*3.14/360*deplasare; x = (razax * cos(u)); y = (razay * sin(u)); setcolor(culoare); setfillstyle(1,culoare); fillellipse((int)x,(int)y, raza,raza); if (saturn == 1) { setcolor(7); ellipse((int)x,(int)y, 140,390,11,5); }
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
if (luna != 0) { setviewport(getmaxx()/4+(int)x+1, getmaxy()/2+(int)y+64,getmaxx()/2, getmaxy(), 0); drawplanet(luna, 12,17,59,2);
setviewport( getmaxx()/4+1, getmaxy()/2+64,getmaxx()/2, getmaxy(),0);
} } //----------------------------------------------------------- /* stergerea planetei */ void delplanet(float deplasare, int razax,int razay, int raza, int saturn=0, int luna = 0) { float u=0,x=0,y=0; u = 2*3.14/360 * deplasare; x = (razax * cos(u)); y = (razay * sin(u)); setcolor(0); setfillstyle(1,0); fillellipse(x, y, raza, raza); setcolor(0); if (saturn == 1) ellipse(x,y, 140,390,11,5); if (luna != 0) { setviewport( getmaxx()/4+(int)x+1, getmaxy()/2+(int)y+64, getmaxx()/2, getmaxy(), 0); delplanet(luna, 12,17,2); setviewport( getmaxx()/4+1, getmaxy()/2+64,getmaxx()/2, getmaxy(),0); } } //------------------------------------------------------------ /* Marcarea orbitelor planetelor din partea stanga */ void detpozitie(unsigned int contor,float deplasare,float rotatie,int razax,int razay) { float u=0, x=0, y=0; if (contor%8 == 0) { u = 2*3.14/360 * (deplasare - 7*rotatie); x = (razax * cos(u)); y = (razay * sin(u)); putpixel((int) x, (int)y, 7); } if (fabs(rotatie) <= 0.095 && contor%42 == 0 && contor>42)
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
{ u = 2*3.14/360 * (deplasare - 84*rotatie); x = (razax * cos(u)); y = (razay * sin(u)); putpixel((int) x, (int)y, 7); } }
//------------------------------------------------------------
/* marcarea orbitelor planetelor din partea dreapta */ void detpozitie2(unsigned int contor,float deplasare,float rotatie,int razax, int razay, int planeta) { float u=0, x=0, y=0; //jup =0.083 sat=0.033 uran=0.011 nep = 0.0059 pluto =0.0039 if (contor>0) { if (planeta == 1 && contor%361 == 0) u = 2*3.14/360 * (deplasare - 361*rotatie); if (planeta == 2 && contor%500 == 0) u = 2*3.14/360 * (deplasare - 500*rotatie); if (planeta == 3 && contor%600 == 0) u = 2*3.14/360 * (deplasare - 600*rotatie); if (planeta == 4 && contor%700 == 0) u = 2*3.14/360 * (deplasare - 700*rotatie); if (planeta == 5 && contor%800 == 0) u = 2*3.14/360 * (deplasare - 800*rotatie); x = (razax * cos(u)); y = (razay * sin(u)); putpixel((int) x, (int)y, 7); } } //--------------------------------------------------------------- /* Miscarea Planetei Mercur */ void mercur() { static float miscmercur = 0; static unsigned int cmercur = 0; delplanet(miscmercur,14,20,2); miscmercur += rotmercur; drawplanet(miscmercur, 14,20,230,2); detpozitie(cmercur++,miscmercur,rotmercur,14,20); } //------------------------------------------------------------ /* Miscarea Planetei Venus */ void venus() { static float miscvenus = 0; static unsigned int cvenus;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
delplanet(miscvenus,36,37,5); miscvenus -= rotvenus; drawplanet(miscvenus,36,37,56,5); detpozitie(cvenus++,miscvenus,-rotvenus,36,37); } //--------------------------------------------------------------
/* Miscarea Pamantului si a Lunii */
void pamantsiluna() { static float miscpamant = 0, miscluna = 0; static unsigned int cpamant; delplanet(miscpamant,61,63,6,0,miscluna); miscpamant += rotpamant; miscluna += rotluna; drawplanet(miscpamant,61,63,1,6,0,miscluna); // delay(2); detpozitie(cpamant++,miscpamant,rotpamant,61,63); } //-------------------------------------------------------------- /* Miscarea Planetei Marte */ void marte() { static float miscmarte = 0; static unsigned int cmarte = 0; delplanet(miscmarte,88,104,3); miscmarte += rotmarte; drawplanet(miscmarte,88,104,4,3); // delay(2); detpozitie(cmarte++,miscmarte,rotmarte,88,104); } //------------------------------------------------------------ /* Miscarea Planetei Jupiter */ void jupiter() { static float miscjupiter = 0; static unsigned int cjupiter = 0; delplanet(miscjupiter,140,155,15); miscjupiter += rotjupiter; drawplanet(miscjupiter,140,155,50,15); // delay(2); detpozitie(cjupiter++,miscjupiter,rotjupiter,140,155); } //----------------------------------------------------------- /* Miscarea Planetei Jupiter2 */ void jupiter2() { static float miscjupiter2 = 0;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
static unsigned int cjupiter2 = 0; delplanet(miscjupiter2,26,28,10); miscjupiter2 += rotjupiter; drawplanet(miscjupiter2,26,28,50,10); detpozitie2(cjupiter2++,miscjupiter2,rotjupiter,26,28,1); } //------------------------------------------------------------
/* Miscarea Planetei Saturn */ void saturn() { static float miscsaturn = 0; static unsigned int csaturn = 0; delplanet(miscsaturn,48,54,8,1); miscsaturn += rotsaturn; drawplanet(miscsaturn,48,54,22,8,1); detpozitie2(csaturn++,miscsaturn,rotsaturn,48,54,2); } //------------------------------------------------------------- /* Miscarea Planetei Uranus */ void uranus() { static float miscuranus = 0; static unsigned int curanus = 0; delplanet(miscuranus,97,106,4); miscuranus -= roturanus; drawplanet(miscuranus,97,106,23,4); detpozitie2(curanus++,miscuranus,-roturanus,97,106,3); } //------------------------------------------------------------- /* Miscarea Planetei Neptun */ void neptun() { static float miscneptun = 0; static unsigned int cneptun = 0; delplanet(miscneptun,140,143,3); miscneptun += rotneptun; drawplanet(miscneptun,140,143,9,3); detpozitie2(cneptun++,miscneptun,rotneptun,140,143,4); } //------------------------------------------------------------ /* Miscarea Planetei Pluto */ void pluto() { static float miscpluto = 0;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
static unsigned int cpluto = 0; float u,x,y; delplanet(miscpluto,151,220,1); miscpluto -= rotpluto; drawplanet(miscpluto,151,220,12,1); detpozitie2(cpluto++,miscpluto,-rotpluto,151,220,5); } //------------------------------------------------------------
void afisareplanete()
{ setcolor(7); outtextxy(8,15,"Planetele din acest cadru:"); setviewport(5,50,50,50,0); drawplanet(0,30,0,14,10); outtextxy(10,20,"Soare"); /* desenarea planetelor */ drawplanet(0,95,0,230,2); /* din cadrul 1 (partea stanga)*/ outtextxy(72,20,"Mercur"); drawplanet(0,156,0,56,5); outtextxy(136,20,"Venus"); drawplanet(0,215,0,1,6); outtextxy(195,20,"Pamant"); drawplanet(0,272,0,59,2); outtextxy(256,20,"Luna"); setcolor(7); /* incadrarea planetelor*/ setlinestyle(1,1,1); /* din cadrul 1 (stanga) */ line(2,-18,getmaxx()/2-12,-18); line(getmaxx()/2-12,-18,getmaxx()/2-12,90); line(2,90,70,90); line(getmaxx()/2-84,90,getmaxx()/2-12,90); line(getmaxx()/2-84,90,getmaxx()/2-84,40); line(getmaxx()/2-250,40,getmaxx()/2-84,40); line(getmaxx()/2-250,40,getmaxx()/2-250,90); line(2,90,2,-18); setviewport(5,105,200,200,0); /* desenare jupiter si marte */ drawplanet(0,30,0,4,3); outtextxy(10,16,"Marte"); drawplanet(0,272,0,50,10); outtextxy(245,20,"Jupiter"); setcolor(15); outtextxy(90,0,"Este anul: "); outtextxy(90,15,"si ziua: "); setcolor(15); setviewport(0,0,getmaxx(),getmaxy(),0); setlinestyle(0,1,1); } //----------------------------------------------------- /*functie pt crearea liniilor care delimiteaza partea stanga si cea dreapta*/ /* adica cadrul 1 si 2 */ void incadrare()
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
{ setcolor(15); line(0,0,0,getmaxy());/* se traseaza liniile cadrului 1 */ line(0,0,getmaxx()/2,0); line(getmaxx()/2,0,getmaxx()/2,getmaxy()); line(0,getmaxy(),getmaxx()/2,getmaxy()); line(3,5,3,getmaxy()-5); line(3,5,getmaxx()/2-3,5); line(getmaxx()/2-3,5,getmaxx()/2-3,getmaxy()-5); line(3,getmaxy()-5,getmaxx()/2-3,getmaxy()-5);
line(getmaxx()/2,0,getmaxx(),0); /* trasare linii cadru 2 */
line(getmaxx(),0,getmaxx(),getmaxy()); line(getmaxx(),getmaxy(),getmaxx()/2,getmaxy()); line(getmaxx()/2+3,5,getmaxx()-3,5); line(getmaxx()-3,5,getmaxx()-3,getmaxy()-5); line(getmaxx()-3,getmaxy()-5,getmaxx()/2+3,getmaxy()-5); line(getmaxx()/2+3,5,getmaxx()/2+3,getmaxy()-5); setviewport(350,25,360,40,0); drawplanet(0,0,0,22,8,1); /* desenare Saturn */ setcolor(22); outtextxy(-20,20,"Saturn"); drawplanet(0,0,0,22,8,1); setlinestyle(1,1,1); line(-25,-12,35,-12); line(-25,-12,-25,32); line(-25,32,35,32); line(35,32,35,-12); drawplanet(0,248,0,23,4); /* desenare Uranus */ outtextxy(228,20,"Uranus"); line(220,-12,280,-12); line(280,-12,280,32); line(280,32,220,32); line(220,32,220,-12); } //-------------------------------------------------------------------------- /* functie pentru desenarea planetelor Neptun si Pluto si incadrarea lor */ void neptunsipluto() { setviewport(350,435,360,470,0); drawplanet(0,2,0,9,3); outtextxy(-20,20,"Neptun"); setlinestyle(1,1,1); line(-25,-12,35,-12); line(-25,-12,-25,32); line(-25,32,35,32); line(35,32,35,-12); drawplanet(0,248,0,12,1); outtextxy(228,20,"Pluto"); line(220,-12,280,-12);
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
line(280,-12,280,32); line(280,32,220,32); line(220,32,220,-12); } //---------------------------------------------------------- void main() { int driver = DETECT, mod, error; unsigned int i=1; int anul,ziua; char an[10],zi[8];
initgraph(&driver, &mod, ""); error = graphresult(); if (error != grOk) { printf("Eroare: %s\n", grapherrormsg(error)); printf("Press any key... "); getch(); exit(1); } afisareplanete(); incadrare(); neptunsipluto(); setviewport( getmaxx()/4+1, getmaxy()/2+64,getmaxx()/2, getmaxy(),0); soare(10); setviewport( getmaxx()*3/4, getmaxy()/2,getmaxx(), getmaxy(),0); soare(3); while (!kbhit() && i<65535) { setviewport( getmaxx()/4+1, getmaxy()/2+64,getmaxx()/2, getmaxy(),0); mercur(); venus(); pamantsiluna(); marte(); jupiter(); setviewport( getmaxx()*3/4, getmaxy()/2,getmaxx(), getmaxy(),0); jupiter2(); saturn(); uranus(); neptun(); pluto(); setcolor(15); /* afisarea anului */ setviewport(185,105,210,135,1); /* si a zilei curente */ clearviewport(); setviewport(185,105,210,135,1); outtextxy(0,0,itoa(i/365,an,10)); outtextxy(0,15,itoa(i%366,zi,10)); i++; } getch();
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
closegraph(); }
Varianta in Java Script
sist-solar.html
<html>
<head>
<!-- /*************************************************************/ /* * Neata Paul, Facultatea de Matematica si Informatica, Universitatea Bucuresti, 2006 * * * Proiect - SIMULAREA SISTEMULUI SOLAR * * Program adaptat dupa "planete.cpp" realizat de Irimia Bogdan sub indrumarea Conf. Dr. Vlada Marin * * numele de variabile/funcii in englezo-romana. http://www.dustbunny.com/afk/planets/ */ /***************************************************************/ --> <title>Sistemul solar -- Neata Paul &[email protected]> 2006</title> <script type="text/javascript"> timeout = 1; // la ce interval de timp (milisecunde) se face miscarea notstarted = true; // se foloseste k sa nu lansam mai multe setTimeout-uri interval = 0; // aici se pastreza ce intarce setInterval contor = 0; // contorul care prin impartire la 365 da ziua si anul // (name, id, src, cur_depl, inc_depl, x_orb, y_orb, center, orb_factor, factor) // sorii - la sori pe post de x_orb si y_orb scriem coordonatele lor soare1 = new Planet("Soare", "centru1", "img/soare.gif", 0, 0, 220, 280, null, 0, 0); soare2 = new Planet("Areso", "centru2", "img/soare.gif", 0, 0, 770, 280, null, 0, 0); // planetele din centrul 1 mercur = new Planet("Mercur", "mercur", "img/mercur.gif", 0, 360.0/88.0, 14, 20, soare1, 8, 2.79); venus = new Planet("Venus", "venus", "img/venus.gif", 0, -360.0/225.0, 36, 37, soare1, 13, 2.63);
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
pamant = new Planet("Pamant", "pamant", "img/pamant.gif", 0, 360.0/365.0, 61, 63, soare1, 17, 2.84); luna = new Planet("Luna", "luna", "img/luna.gif", 0, 360.0/28.0, 12, 17, pamant, 0, 2.76); marte = new Planet("Marte", "marte", "img/marte.gif", 0, 360.0/686.98, 88, 104, soare1, 26, 3.0); jupiter = new Planet("Jupiter", "jupiter", "img/jupiter.gif", 0, 360.0/4307.0, 140, 155, soare1, 85, 2.3); // planetele din centrul 2 terjupi = new Planet("Terjupi", "terjupi", "img/jupiter.gif", 0, 360.0/4307.0, 26, 28, soare2, 600, 1.6); saturn = new Planet("Saturn", "saturn", "img/saturn.gif", 0, 360.0/10731.0, 48, 54, soare2, 700, 1.9);
uranus = new Planet("Uranus", "uranus", "img/uranus.gif", 0, -360.0/30660.0, 97, 106, soare2, 1100, 1.5);
neptun = new Planet("Neptun", "neptun", "img/neptun.gif", 0, 360.0/66115.5, 140, 143, soare2, 1300, 1.40); pluto = new Planet("Pluto", "pluto", "img/pluto.gif", 0, -360.0/90465.5, 151, 220, soare2, 1500, 1.50); // functia care contruieste obiectul de tip planeta // factorii se folosesc sa departeze (supraunitar) sau sa apropie(subunitar) planetele de centru function Planet(name, id, src, cur_depl, inc_depl, x_orb, y_orb, center, orb_factor, factor) { this.name = name; this.id = id; this.src = src: this.cur_depl = cur_depl; this.inc_depl = inc_depl; this.x_orb = x_orb; this.y_orb = y_orb; this.center = center; this.orb_factor = orb_factor; this.factor = factor; this.re_pos = re_pos; /* M E T O D A */ this.draw_orbit = draw_orbit; /* M E T O D A */ // ORBIT se scrie/zice in engleza la orbita ? return this; } // functia asta se apeleaza automat la incarcare si 'scrie' pe ecran textul si pozele function on_load() { document.bgColor = '#000000'; document.fgColor = '#00ff00'; notsarted = true; alert("SISTEMUL SOLAR - Neata Paul, grupa 433, anul IV, 2006\n\ Pentru alte informatii uitati-va in sursa.\n\n\ Pentru a porni/suspenda miscarea planetelor dati un clic pe suprafata HTML-ului.\n\ In titlul ferestrei sunt informatiile despre ani si zile.\n\n\
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Dimesiunile orbitelor au fost alterate, ficare, cu un factor.\n\ Daca vreti o afisare \"normala\"(nerecomandat), modificati, in sursa, factorul la 1 pentru fiecare planeta.\n\n\ Avand in vedere faptul ca JavaScript este interpretat diferit de la browser la browser, s-ar putea sa apara\ mici probleme la afisare."); //screen.availHeight/2+50; // punem sorii si apoi ii pozitionam insert_planet(soare1); insert_planet(soare2); place_img_at(soare1.id, soare1.x_orb, soare1.y_orb); place_img_at(soare2.id, soare2.x_orb, soare2.y_orb);
//trasam orbitele
if(confirm("Vreti sa afisati orbitele planetelor ? \nDaca da aveti grija ca asta dureaza ceva de tipul 10 sec pe un Pentium 4\n")) { mercur.draw_orbit(); venus.draw_orbit(); pamant.draw_orbit(); marte.draw_orbit(); jupiter.draw_orbit(); terjupi.draw_orbit(); saturn.draw_orbit(); uranus.draw_orbit(); neptun.draw_orbit(); pluto.draw_orbit(); } // planatele le punem aiurea si invocam o iteratie care le va aseza unde trebuie insert_planet(mercur); insert_planet(venus); insert_planet(pamant); insert_planet(luna); insert_planet(marte); insert_planet(jupiter); insert_planet(terjupi); ///////////////// insert_planet(saturn); insert_planet(uranus); insert_planet(neptun); insert_planet(pluto); main_iteration(); // k sa le puna unde trebuie } // insereaza o imagine in document function insert_planet(planet) { document.body.innerHTML += "" + "<IMG id='"+planet.id+"' src='"+planet.src+"' " + "style='position:absolute;'>" + "<br />"; } // se apeleaza cand dam click pe document
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
// daca sistemul solar merge atunci ii pune pauza iar daca nu il face sa mearga function on_click() { if(notstarted) { notstarted = false; interval = setInterval("main_iteration()", timeout); main_iteration() } else { notstarted = true; clearInterval(interval); } }
// functia asta se apeleaza "din timp in timp" si muta toate planetele (care trebuie mutate)
function main_iteration() { contor++; an = contor/365; zi = contor%366; // IExplorer //window.status = "anul "+parseInt(""+an)+" ziua "+parseInt(""+zi); // Mozilla document.title = "anul "+parseInt(""+an)+" ziua "+parseInt(""+zi); mercur.re_pos(); venus.re_pos(); pamant.re_pos(); luna.re_pos(); marte.re_pos(); jupiter.re_pos(); terjupi.re_pos(); saturn.re_pos(); uranus.re_pos(); neptun.re_pos(); pluto.re_pos(); } // functia de pozitionare a unei planate // c_x, c_y reprezinta coordonatele centrului in jurul caruia se face rotatia function re_pos() { img = document.getElementById(this.center.id); c_x = parseInt(img.style.left) + parseInt(img.width) / 2; c_y = parseInt(img.style.top) + parseInt(img.height) / 2; u = 2*Math.PI/360 * this.cur_depl; // unghiul in functie de deplasare x = c_x + this.factor * this.x_orb * Math.cos(u); // coordonatele y = c_y + this.factor * this.y_orb * Math.sin(u); // ... place_img_at(this.id, x, y); this.cur_depl += this.inc_depl; } // plaseaza centrul unei imagini la coordonatele date
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
function place_img_at(id, x, y) { img = document.getElementById(id); img.style.left = x - parseInt(img.width) / 2; img.style.top = y - parseInt(img.height) / 2; } // deseneaza orbita function draw_orbit() { img = document.getElementById(this.center.id); c_x = parseInt(img.style.left) + parseInt(img.width) / 2; c_y = parseInt(img.style.top) + parseInt(img.height) / 2; u = 0; x = 0;
y = 0;
for(this.cur_depl = 0; Math.abs(this.cur_depl) <= 360; this.cur_depl += this.orb_factor*this.inc_depl) { u = 2*Math.PI/360 * this.cur_depl; // unghiul in functie de deplasare x = c_x + this.factor * this.x_orb * Math.cos(u); // coordonatele y = c_y + this.factor * this.y_orb * Math.sin(u); // ... x -= 5; y -= 12; ch = '.'; document.body.innerHTML += "<div style='valign:top;align:left;color:#eeeeee;position:absolute;left:"+x+";top:"+y+"'>"+ch+"</div>" } this.cur_depl = 0; } </script> <noscript> Interpretarea JavaScript nu este activata in browser. <br /><br /> Vedeti Edit->Preferences (pe Mozilla) sau Tools->Internet Options (pe Internet Explorer) ! <br /><br /> </noscript> </head> <body background="img/back.bmp" onload="on_load();" onclick="on_click();"> <!-- N I M I C --> </body> </html>
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
PROIECT – ceas Nota: Codul in Pascal/Delphi; sa se scrie si codul in C++
uses dos,crt,graph; var i,Gd,Gm,x,y,r: integer; angle4,angle,angle1,angle2,angle3: integer; rad4,rad3,rad,rad1,rad2: real; temp,h,m,s,hunc: word; d : string; begin gd :=DETECT; initgraph(Gd,Gm,'c:\TP\BGI'); setbkcolor(15); {culoarea de fond este alba} x:=300; y:=250; { x SI y pentru centrul cercului } r:=150; { raza cercului } SetColor(9); {culoarea pentru cercuri este } SETLINESTYLE(solidln,0,3);{liniile} circle(x,y,r); { deseneaza cercul } circle(x,y,r+20); { deseneaza un cerc cu raza mai mare cu 20 decat primul} setcolor(4);{deseneaza cercuri rosii} for i:=1 to 148 do circle(x,y,i); setcolor(14); {deseneaza cercuri galbene}
for i:=3 to 17 do circle(x,y,r+i);
setcolor(4); {culoarea rosie pentru scris } for i:=1 to 12 do begin angle3:=i*30-90; { DESENEAZA NUMERELE } rad3:=angle3*pi/180; if i<10 then begin moveto(round(cos(rad3)*(r+35)+x),round(sin(rad3)*(r+35)+y)); Str(i, d); outtext(d) end else begin moveto(round(cos(rad3)*(r+44)+x),round(sin(rad3)*(r+44)+y)); Str(I, d); outtext(d); end; end; setcolor(2);{setez culoare verde pentru linii} for i:=1 to 60 do { deseneaza liniile pentru ceas } begin if (i mod 5 = 0) then begin angle4:=i*6-90; rad4:=angle4*pi/180; {linii mari} line( round(cos(rad4)*r+x), round(sin(rad4)*r+y), round(cos(rad4)*(r+20)+x), round(sin(rad4)*(r+20)+y)); end
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
else begin {lini mici} angle4:=i*6-90; rad4:=angle4*pi/180; line( round(cos(rad4)*r+x), round(sin(rad4)*r+y), round(cos(rad4)*(r+10)+x), round(sin(rad4)*(r+10)+y)); end; end; repeat gettime(h,m,s,hund); { obtin ora curenta de la PC} if temp<>s then begin setcolor(4);{culoarea rosie} line(x, y, round(cos(rad)*(r-10)+x), round(sin(rad)*(r-10)+y)); { DESENEAZA SECUNDELE } line(x, y, round(cos(rad1)*(r-30)+x), round(sin(rad1)*(r-30)+y)); { DESENEAZA ORELE } line(x, y, round(cos(rad2)*(r-15)+x), round(sin(rad2)*(r-15)+y)); { DESENEAZA MINUTELE } angle:=6*s-90; { UNGHIUL PENTRU SECUNDE } angle1:=30*h+(m div 15)-90; { UNGHIUL PENTRU ORE } angle2:=m*6-90; { UNGHIUL PENTRU MINUTE }
Rac:=angle*pi/180; { UNGHIUL RAZEI PENTRU SECUNDE}
Rad1:=angle1*pi/180 ; { UNGHIUL RAZEI PENTRU ORE} Rad2:=angle2*pi/180; { UNGHIUL RAZEI PENTRU MINUTE} setcolor(14); {culoarea galbena} line(x, y, round(cos(rad)*(r-10)+x), round(sin(rad)*(r-10)+y)); { DESENEAZA SECUNDELE} line(x, y, round(cos(rad1)*(r-30)+x), round(sin(rad1)*(r-30)+y)); { DESENEAZA ORELE } line(x, y, round(cos(rad2)*(r-15)+x), round(sin(rad2)*(r-15)+y)); { DESENAZA MINUTELE } temp:=s; end; until keypressed; { DESENEAZA CEASUL PANA SE APASA O TASTA } readln; closegraph; end.
PROIECT – fractali – multimi G. JULIA Nota: Codul in Pascal/Delphi; sa se scrie si codul in C++ Referinta:
M. Vlada, A,.Posea,…, Grafica pe calculator in limbajele Pascal si C, vol. II, , Implementare si
aplicatii, Ed. Tehnica,1992 pag. 3-94
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
program fractal_julia; uses graph; Type complex = object x, y : real; procedure InitializatCu( x1, y1 : real); procedure InmultitCu( z : complex); procedure AdunatCu( z : complex); function raza : real; end; Const XMin = -2; {fereastra virtuala de afisare} YMin = -0.81; XMax = 2; YMax = 0.81; MaxRaza = 25; MaxCulori = 30; {Numarul maxim de culori limiteaza si nr de iteratii} kz : complex = ( x:-1.3; y:0.1); var Gd, Gm : integer; {procedure initiaza} procedure complex.InitializatCu( x1, y1 : real); begin x := x1; y := y1; end; {procedura inmulteste} procedure complex.InmultitCu( z : complex ); var temp : complex; begin
temp.InitializatCu( x*z.x-y*z.y, x*z.y+z.x*y );
x := temp.x; y := temp.y; end; {procedura aduna} procedure complex.AdunatCu( z : complex ); begin x := x+z.x; y := y+z.y; end; {functia raza} function complex.raza : real; begin raza := x*x + y*y; end; {procedura julia} procedure FractalJulia; function culoare ( x, y : real) : byte; var c : word; z : complex; begin c := 1; z.InitializatCu( x, y ); repeat z.InmultitCu( z ); z.AdunatCu( kz ); c := c+1; until (z.raza > MaxRaza) or (c = MaxCulori); culoare := c: end; var x, y : integer; ScalaX, Scalay : real; begin ScalaX := (XMax-XMin)/getmaxx; ScalaY := (YMax-YMin)/getmaxy; for x := 1 to getmaxx do for y := 1 to getmaxy do
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
putPixel( x, y, culoare( XMin+x*ScalaX,YMin+y*ScalaY)); end; begin InitGraph( Gd, Gm, '' ); FractalJulia; readln; closeGraph; end.
PROIECT – fractali – multimi B. MANDELBROT Nota: Codul in Pascal/Delphi; sa se scrie si codul in C++
Referinta
M. Vlada, A,.Posea,…, Grafica pe calculator in limbajele Pascal si C, vol. II, , Implementare si
aplicatii, Ed. Tehnica,1992 pag. 3-94
program fractal_mandelbrot; uses graph; Type complex = object x, y : real; procedure InitializatCu( x1, y1 : real); procedure InmultitCu( z : complex); procedure AdunatCu( z : complex);
function raza : real;
end; Const XMin = -2.7; {fereastra virtuala de afisare} YMin = -1.5; XMax = 1; YMax = 1.5; MaxRaza = 20; MaxCulori = 32; {Numarul maxim de culori limiteaza si nr de iteratii} kz : complex = ( x:-1.3; y:0.1); var Gd, Gm : integer; procedure complex.InitializatCu( x1, y1 : real); begin x := x1; y := y1; end; procedure complex.InmultitCu( z : complex ); var temp : complex; begin temp.InitializatCu( x*z.x-y*z.y, x*z.y+z.x*y ); x := temp.x; y := temp.y; end; procedure complex.AdunatCu( z : complex ); begin x := x+z.x; y := y+z.y; end; function complex.raza : real; begin raza := x*x + y*y; end; procedure FractalJulia; function culoare ( x, y : real) : byte; var c : word; z : complex; begin c := 1; z.InitializatCu( 0, 0 );
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
kz.InitializatCu( x, y ); repeat z.InmultitCu( z ); z.AdunatCu( kz ); c := c+1; until (z.raza > MaxRaza) or (c = MaxCulori); culoare := c: end; var x, y : integer; ScalaX, Scalay : real; begin ScalaX := (XMax-(XMin))/getmaxx; ScalaY := (YMax-(YMin))/getmaxy; for x := 1 to getmaxx do for y := 1 to getmaxy do putPixel( x, y, culoare( XMin+x*ScalaX,YMin+y*ScalaY)); end; begin InitGraph( Gd, Gm, '' ); FractalJulia; readln; closeGraph; end.
PROIECT – cub si rotatii Nota: Codul in C++
//0****************************************************************** #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <dos.h> #include <string.h> #include <math.h> //1****************************************************************** void initg(){ int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver, &gmode, ""); errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ {printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1);/* return with error code */ } } //2******************************************************************* void endg(){ closegraph(); } //3******************************************************************* int round(double number) { double a; int b;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
b=number; a=(double)number-b; if (a>=0.5) return b+1;
else return b; } //3******************************************************************* int trans(int n)//schimba din lui oy de la (sus in jos) la (jos in sus) { int r,i; i=getmaxy(); r=i-n; return r; } //3***************************************************************** double rad(double n)//transforma grade in radian { return (double)M_PI*n/180; } //3***************************************************************** void d3d2(double a,double b,double c,double x1,double y1,double z1, double &x,double &y) { x=x1*cos(rad(a))+y1*cos(rad(b))+z1*cos(rad(c)); y=y1*sin(rad(a))+y1*sin(rad(b))+z1*sin(rad(c)); } //3*****************************************************************
void defpoint(double *x,double *y,double *z)
{ x[0]=0; y[0]=0; z[0]=0;//originea x[1]=100; y[1]=0; z[1]=0;//axa ox x[2]=0; y[2]=100; z[2]=0;//axa oy x[3]=0; y[3]=0; z[3]=100;//axa oy //coord cubului /* x[4]=0; y[4]=0; z[4]=0; //1 x[5]=50; y[5]=0; z[5]=0; //2 x[6]=50; y[6]=0; z[6]=50; //3 x[7]=0; y[7]=0; z[7]=50; //4 x[8]=0; y[8]=50; z[8]=50; //5 x[9]=0; y[9]=50; z[9]=0; //6 x[10]=50; y[10]=50; z[10]=0; //7 x[11]=50; y[11]=50; z[11]=50; //8 */ x[4]=0; y[4]=0; z[4]=0; //1 x[5]=50; y[5]=0; z[5]=0; //2 x[6]=50; y[6]=0; z[6]=70; //3 x[7]=0; y[7]=0; z[7]=70; //4 x[8]=0; y[8]=30; z[8]=70; //5 x[9]=0; y[9]=80; z[9]=0; //6 x[10]=50; y[10]=80; z[10]=0; //7 x[11]=50; y[11]=30; z[11]=70; //8
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
} //3***************************************************************** void desen(double *x,double *y,double *z) { double ox=getmaxx()/2,oy=getmaxy()/2,a,b,c,d; /* setcolor(15); d3d2(0,90,225,x[0],y[0],z[0],a,b); d3d2(0,90,225,x[1],y[1],z[1],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[2],y[2],z[2],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[3],y[3],z[3],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); */ setcolor(4); d3d2(0,90,225,x[4],y[4],z[4],a,b); d3d2(0,90,225,x[5],y[5],z[5],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[7],y[7],z[7],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[9],y[9],z[9],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[10],y[10],z[10],a,b); d3d2(0,90,225,x[5],y[5],z[5],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d)));
d3d2(0,90,225,x[11],y[11],z[11],c,d);
line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[9],y[9],z[9],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[6],y[6],z[6],a,b); d3d2(0,90,225,x[5],y[5],z[5],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[11],y[11],z[11],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[7],y[7],z[7],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[8],y[8],z[8],a,b); d3d2(0,90,225,x[7],y[7],z[7],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[11],y[11],z[11],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); d3d2(0,90,225,x[9],y[9],z[9],c,d); line(ox+round(a),trans(oy+round(b)),ox+round(c),trans(oy+round(d))); } //3**************************************************************** void rot_oz(double &x,double &y,double &z,double grad) { double x1=x,y1=y,z1=z; x=x1*cos(rad(grad))-y1*sin(rad(grad)); y=x1*sin(rad(grad))+y1*cos(rad(grad));
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
z=z1; } //3**************************************************************** void rot_ox(double &x,double &y,double &z,double grad) { double x1=x,y1=y,z1=z; x=x1; y=y1*cos(rad(grad))-z1*sin(rad(grad)); z=y1*sin(rad(grad))+z1*cos(rad(grad)); } //3**************************************************************** void rot_oy(double &x,double &y,double &z,double grad) { double x1=x,y1=y,z1=z; x=x1*cos(rad(grad))+z1*sin(rad(grad)); y=y1; z=-x1*sin(rad(grad))+z1*cos(rad(grad)); } //3**************************************************************** void rotplan(double xc,double yc,double zc,double &x,double &y,double z,double unghi) //cx,yc==punctul fata de care puctul x,y se roteste cu unghiul unghi { double x1=x,y1=y,z1=z;; x=xc+(x1-xc)*cos(rad(unghi))-(y1-yc)*sin(rad(unghi)); y=yc+(x1-xc)*sin(rad(unghi))+(y1-yc)*cos(rad(unghi)); z=z1; } //3*****************************************************************
void main(void){ initg(); double xx[20],yy[20],zz[20],grad=270; int i; defpoint(xx,yy,zz); setwritemode(1); desen(xx,yy,zz); //* //*********************************** getch(); for(i=0;i<360;i++) { delay(1); desen(xx,yy,zz); rot_ox(xx[4],yy[4],zz[4],1); rot_ox(xx[5],yy[5],zz[5],1); rot_ox(xx[6],yy[6],zz[6],1); rot_ox(xx[7],yy[7],zz[7],1); rot_ox(xx[8],yy[8],zz[8],1); rot_ox(xx[9],yy[9],zz[9],1); rot_ox(xx[10],yy[10],zz[10],1); rot_ox(xx[11],yy[11],zz[11],1); desen(xx,yy,zz);
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
} //*********************************** getch(); for(i=0;i<360;i++) { delay(1); desen(xx,yy,zz); rot_oy(xx[4],yy[4],zz[4],1); rot_oy(xx[5],yy[5],zz[5],1); rot_oy(xx[6],yy[6],zz[6],1); rot_oy(xx[7],yy[7],zz[7],1); rot_oy(xx[8],yy[8],zz[8],1); rot_oy(xx[9],yy[9],zz[9],1); rot_oy(xx[10],yy[10],zz[10],1); rot_oy(xx[11],yy[11],zz[11],1); desen(xx,yy,zz); } //*********************************** getch(); for(i=0;i<360;i++) { delay(1); desen(xx,yy,zz); rot_oz(xx[4],yy[4],zz[4],1); rot_oz(xx[5],yy[5],zz[5],1); rot_oz(xx[6],yy[6],zz[6],1); rot_oz(xx[7],yy[7],zz[7],1); rot_oz(xx[8],yy[8],zz[8],1); rot_oz(xx[9],yy[9],zz[9],1); rot_oz(xx[10],yy[10],zz[10],1);
rot_oz(xx[11],yy[11],zz[11],1);
desen(xx,yy,zz); } //*********************************** getch(); for(i=0;i<360;i++) { delay(10); desen(xx,yy,zz); rotplan(25,25,25,xx[4],yy[4],zz[4],1); rotplan(25,25,25,xx[5],yy[5],zz[5],1); rotplan(25,25,25,xx[6],yy[6],zz[6],1); rotplan(25,25,25,xx[7],yy[7],zz[7],1); rotplan(25,25,25,xx[8],yy[8],zz[8],1); rotplan(25,25,25,xx[9],yy[9],zz[9],1); rotplan(25,25,25,xx[10],yy[10],zz[10],1); rotplan(25,25,25,xx[11],yy[11],zz[11],1); desen(xx,yy,zz); } //*********************************** //*/ getch(); endg(); }
//9*****************************************************************
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
PROIECT – desen/aria unui poligon oarecare Nota: Codul in Java
Arie.java
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Arie extends JFrame{ private JButton buton = null; private Surface suprafata = null; private final Arie this2 = this; private MenuBar meniuBara; private Menu optiuni = null; private MenuItem itm1, itm2; public Arie(){ super("Aria poligonului"); initialize(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);
}
}); } private JButton getJButton(){ if (buton == null){ buton = new JButton("OK"); buton.setEnabled(false); buton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (buton.getText() == "OK"){ getCanvas().setGata(true); buton.setText("Calculeaza aria"); } else{ JOptionPane.showMessageDialog( this2, "Aria poligonului este "+getCanvas().getAria()+" pixeli", "Informatie", JOptionPane.INFORMATION_MESSAGE); } } });
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
} return buton; } private MenuBar getJMeniuBara() { if (meniuBara == null) { meniuBara = new MenuBar(); optiuni = new Menu("Optiuni"); itm1 = new MenuItem("Din nou..."); itm1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { getContentPane().remove(suprafata); suprafata = null; initialize(); buton.setText("OK"); buton.setEnabled(false); } }); itm2 = new MenuItem("Exit"); itm2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { hide(); dispose(); System.exit(0); }
});
optiuni.add(itm1); optiuni.add(itm2); meniuBara.add(optiuni); } return meniuBara; } private Surface getCanvas(){ if (suprafata == null){ suprafata = new Surface(); } return suprafata; } private void initialize(){ setSize(300,300); setLocation(200,100); this.setMenuBar(getJMeniuBara()); this.getContentPane().setLayout(new java.awt.BorderLayout()); this.getContentPane().add(getCanvas(), java.awt.BorderLayout.CENTER);
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
this.getContentPane().add(getJButton(), java.awt.BorderLayout.SOUTH);
setVisible(true); new Thread(){ public void run(){ while(getCanvas().getNumarPuncte()<3); buton.setEnabled(true); } }.start(); } public static void main(String[] args){ new Arie(); } }
Surface.java
import java.awt.*; import java.awt.event.*; import javax.swing.JPanel; public class Surface extends Canvas{ private int[] x = new int[30]; private int[] y = new int[30];
private int i=0;
private boolean gata = false; public Surface(){ this.setBackground(Color.red); this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e){ if (!gata){ x[i] = e.getX(); y[i] = e.getY(); i++; } repaint(); } }); } public void paint(Graphics g){ for (int j = 0; j < i; j++) g.fillOval(x[j],y[j],5,5); if (gata) g.fillPolygon(x,y,i); }
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
public void setGata(boolean val){ gata = val;
repaint(); } public int getNumarPuncte(){ return i; } public double getAria(){ //Joseph O'Rourke
int suma = 0; x[i] = x[0]; y[i] = y[0]; for(int j = 0; j < i; j++) suma = suma + x[j]*y[j+1]-x[j+1]*y[j]; suma = suma/2; return suma; } }
PROIECT – desen ROZA – petale
Nota: Codul in Java
Roza.java
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Roza extends JFrame{ private Surface suprafata = null; private MenuBar meniuBara; private Menu optiuni = null; private MenuItem itm1, itm2; private String x,y; public Roza(){ super("Roza"); Dimension marimeEcran = Toolkit.getDefaultToolkit().getScreenSize(); setSize(marimeEcran.width * 3/4, (int)(marimeEcran.height * 0.80)); setLocation( marimeEcran.width / 2 - this.getWidth() / 2, marimeEcran.height / 2 - this.getHeight() / 2- (int)(marimeEcran.height*0.01));
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
initialize(); addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e) { System.exit(0); } }); } private MenuBar getJMeniuBara() { if (meniuBara == null) { meniuBara = new MenuBar(); optiuni = new Menu("Optiuni"); itm1 = new MenuItem("Din nou..."); itm1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { getContentPane().remove(suprafata); suprafata = null; initialize(); } }); itm2 = new MenuItem("Exit"); itm2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { hide();
dispose();
System.exit(0); } }); optiuni.add(itm1); optiuni.add(itm2); meniuBara.add(optiuni); } return meniuBara; } private Surface getCanvas(){ if (suprafata == null){ suprafata = new Surface(); } return suprafata; } private void initialize(){ this.setMenuBar(getJMeniuBara()); this.getContentPane().setLayout(new java.awt.BorderLayout());
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
this.getContentPane().add(getCanvas(), java.awt.BorderLayout.CENTER); setVisible(true); while(!pasValid(getPas())); int pas = Integer.parseInt(x); while(!petaleValid(getPetale())); int petale = Integer.parseInt(y); suprafata.setPas(pas); suprafata.setPetale(petale); } private String getPas(){ x = null; while (x == null) x = JOptionPane.showInputDialog( this, "Introdu pasul!", "Intrebare", JOptionPane.QUESTION_MESSAGE); return x; } private String getPetale(){ y = null; while (y == null) y = JOptionPane.showInputDialog( this, "Introdu nr petale!", "Intrebare", JOptionPane.QUESTION_MESSAGE); return y;
}
private boolean pasValid(String x){ try{ Integer.parseInt(x); return true; } catch(NumberFormatException e){ JOptionPane.showMessageDialog( this, "Numar invalid", "Atentie", JOptionPane.ERROR_MESSAGE); return false; } } private boolean petaleValid(String x){ try{ Integer.parseInt(x); return true; } catch(NumberFormatException e){
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
JOptionPane.showMessageDialog( this, "Numar invalid", "Atentie", JOptionPane.ERROR_MESSAGE);
return false; } } public static void main(String[] args){ new Roza(); } }
Surface.java
import java.awt.*; import java.awt.event.*; public class Surface extends Canvas{ private int pas = 0; private int petale = 0; private int cul = 0; private int pasF, petaleF; private boolean pasSetat = false; private boolean petaleSetat = false; private Color[] culoare = {Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
public Surface(){ this.setBackground(Color.black); } public void paint(Graphics g){ if(pasSetat && petaleSetat){ int j = 0; double cont = 0; if (pas <= 0) pas = 180; if (petale <= 0) petale = 3; petale++; g.setColor(culoare[cul]); while(cont <= 2*Math.PI ){ j++; if (petale*j > 2*pas){ cul++; if (cul > 12) cul = 0; j = 0;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
g.setColor(culoare[cul]); } g.drawLine((int)(Math.sin(cont)*200)+330,(int)(Math.cos(cont)*200)+240, (int)(Math.sin(petale*cont)*200)+330,(int)(Math.cos(petale*cont)*200)+240); cont = cont + Math.PI / pas; } } init(); } public void setPas(int pas){ this.pas = pas; pasSetat = true; pasF = pas; repaint(); } public void setPetale(int petale){ this.petale = petale; petaleSetat = true; petaleF = petale; repaint(); } private void init(){ pas = pasF; petale = petaleF; cul = 0; } }
ALGORITMUL LUI BRESENHAM PENTRU SEGMENT SI CERC
Cod VB
VERSION 5.00 Begin VB.Form Form1 AutoRedraw = -1 'True BackColor = &H000080FF& Caption = "Form1" ClientHeight = 4725 ClientLeft = 165 ClientTop = 855 ClientWidth = 7335 DrawWidth = 3 LinkTopic = "Form1" ScaleHeight = 315 ScaleMode = 3 'Pixel ScaleWidth = 489
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
StartUpPosition = 3 'Windows Default Begin VB.TextBox txt4 Height = 375 Left = 2160 TabIndex = 4 Top = 3360 Width = 1095 End Begin VB.TextBox txt3 Height = 375 Left = 2160 TabIndex = 3 Top = 2760 Width = 1095 End Begin VB.TextBox txt2 Height = 375 Left = 2160 TabIndex = 2 Top = 2160 Width = 1095 End Begin VB.TextBox txt1 Height = 375 Left = 2160 TabIndex = 1 Top = 1560 Width = 1095 End Begin VB.CommandButton Command1 Caption = "DESENEAZA" Height = 375 Left = 5640 TabIndex = 0 Top = 4080
Width = 1335
End Begin VB.Label Lbl5 Alignment = 2 'Center BackColor = &H000080FF& Caption = "ALGORITMUL LUI BRESENHAM PENTRU DREAPTA SI CERC" BeginProperty Font Name = "MS Sans Serif" Size = 12 Charset = 0 Weight = 700 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 735 Left = 1200 TabIndex = 9 Top = 120 Width = 5295
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
End Begin VB.Label Lbl4 BackColor = &H000080FF& Caption = "Dati y1 :" BeginProperty Font Name = "Times New Roman" Size = 12 Charset = 0 Weight = 700 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 375 Left = 840 TabIndex = 8 Top = 3360 Width = 855 End Begin VB.Label Lbl3 BackColor = &H000080FF& Caption = "Dati y0 :" BeginProperty Font Name = "Times New Roman" Size = 12 Charset = 0 Weight = 700 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 375 Left = 840 TabIndex = 7 Top = 2760 Width = 1215
End
Begin VB.Label Lbl2 BackColor = &H000080FF& Caption = "Dati x1 :" BeginProperty Font Name = "Times New Roman" Size = 12 Charset = 0 Weight = 700 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 375 Left = 840 TabIndex = 6 Top = 2160 Width = 855 End Begin VB.Label Lbl1
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
BackColor = &H000080FF& Caption = "Dati x0 :" BeginProperty Font Name = "Times New Roman" Size = 12 Charset = 0 Weight = 700 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 375 Left = 840 TabIndex = 5 Top = 1560 Width = 855 End Begin VB.Menu mnuDreapta Caption = "&Dreapta" End Begin VB.Menu mnuCerc Caption = "&Cerc" End Begin VB.Menu mnuExit Caption = "&Exit" End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Dim ind As Integer Private Sub Command1_Click() If ind = 0 Then
If txt1.Text = "" Or txt2.Text = "" Or txt3.Text = "" Or txt4.Text = "" Then
MsgBox ("Trebuie sa introduceti valori in casutele de text") Else Call linie(txt1.Text, txt2.Text, txt3.Text, txt4.Text) End If ElseIf ind = 1 Then If txt1.Text = "" Or txt2.Text = "" Or txt3.Text = "" Then MsgBox ("Trebuie sa introduceti valori in casutele de text") Else Call cerc(txt1.Text, txt2.Text, txt3.Text) End If End If 'Lbl5.Visible = False End Sub Private Sub linie(x0 As Double, x1 As Double, y0 As Double, y1 As Double)
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Dim dy As Double Dim dx As Double Dim m As Double Dim y As Double Dim d As Double Dim pas As Boolean Dim a, b As Double Dim c, e As Double Dim ypas As Integer pas = Abs(y1 - y0) > Abs(x1 - x0) If (pas) Then a = x0 x0 = y0 y0 = a b = x1 x1 = y1 y1 = b End If If x0 > x1 Then c = x0 x0 = x1 x1 = c e = y0 y0 = y1 y1 = e End If dx = x1 - x0 dy = Abs(y1 - y0) d = 0 m = dy / dx y = y0 If y0 < y1 Then ypas = 1 Else
ypas = -1
End If For x = x0 To x1 If (pas) Then PSet (y, x), QBColor(5) Else PSet (x, y), QBColor(4) End If d = d + m If (d >= 0.5) Then y = y + ypas d = d - 1 End If Next x
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
txt1.Visible = False txt2.Visible = False txt3.Visible = False txt4.Visible = False Lbl1.Visible = False Lbl2.Visible = False Lbl3.Visible = False Lbl4.Visible = False End Sub Private Sub cerc(x0 As Integer, y0 As Integer, r As Integer) Dim y As Integer Dim x As Integer Dim dx As Integer Dim dy As Integer Dim f As Integer f = 1 - r dx = 0 dy = -2 * r x = 0 y = r PSet (x0, y0 + r) PSet (x0, y0 - r) PSet (x0 + r, y0) PSet (x0 - r, y0) While (x < y) If (f >= 0) Then y = y - 1 dy = dy + 2 f = f + dy End If
x = x + 1
dx = dx + 2 f = f + dx + 1 PSet (x0 + x, y0 + y) PSet (x0 - x, y0 + y) PSet (x0 + x, y0 - y) PSet (x0 - x, y0 - y) PSet (x0 + y, y0 + x) PSet (x0 - y, y0 + x) PSet (x0 + y, y0 - x) PSet (x0 - y, y0 - x) Wend txt1.Visible = False txt2.Visible = False txt3.Visible = False txt4.Visible = False
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Lbl1.Visible = False Lbl2.Visible = False Lbl3.Visible = False Lbl4.Visible = False End Sub Private Sub mnuDreapta_Click() ind = 0 Call afisare_linie Form1.Cls End Sub Private Sub mnuCerc_Click() ind = 1 Call afisare_cerc Form1.Cls End Sub Private Sub mnuElipsa_Click() ind = 2 End Sub Private Sub mnuExit_Click() End End Sub Private Sub afisare_linie() ind = 0 txt1.Text = "" txt2.Text = "" txt3.Text = "" txt4.Text = "" txt1.Visible = True txt2.Visible = True txt3.Visible = True txt4.Visible = True
Lbl1.Visible = True
Lbl2.Visible = True Lbl3.Visible = True Lbl4.Visible = True Lbl1.Caption = "Dati x0 :" Lbl2.Caption = "Dati x1 :" Lbl3.Caption = "Dati y0 :" Lbl4.Caption = "Dati y1 :" End Sub Private Sub afisare_cerc() ind = 1 txt1.Text = "" txt2.Text = "" txt3.Text = ""
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
txt1.Visible = True txt2.Visible = True txt3.Visible = True txt4.Visible = False Lbl1.Visible = True Lbl2.Visible = True Lbl3.Visible = True Lbl4.Visible = False
Lbl1.Caption = "Dati x0 :" Lbl2.Caption = "Dati y0 :" Lbl3.Caption = "Dati raza :" End Sub
Visual C++
Program.cs
using System; using System.Collections.Generic: using System.Windows.Forms; namespace Grafica { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main()
{
Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
Form1.cs
using System; using System.Collections.Generic: using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
using System.Windows.Forms; namespace Grafica { public partial class Form1 : Form { public int contor = 1; Point p0, p1; Graphics gr; int forma = 0;
Color culoare = new Color(); Bitmap bmp; int raza; public Form1() { InitializeComponent(); culoare = Color.Black; InitBitmap(); } private void InitBitmap() { bmp = new Bitmap(panel1.Width, panel1.Height); bmp.SetResolution(panel1.Width, panel1.Height); panel1.ResumeLayout(); panel1.BackgroundImage = (bmp as Image); panel1.Refresh(); } private void button1_Click(object sender, EventArgs e) { forma = 1; } private void button2_Click(object sender, EventArgs e) { forma = 2; }
//private void button3_Click(object sender, EventArgs e) //{ // forma = 3; //} private void button4_Click(object sender, EventArgs e) { culoare = Color.Black; } private void button10_Click(object sender, EventArgs e) { culoare = Color.White; }
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
private void button5_Click(object sender, EventArgs e) { culoare = Color.DarkGray; } private void button11_Click(object sender, EventArgs e) { culoare = Color.Gray; } private void button6_Click(object sender, EventArgs e) { culoare = Color.DarkRed; } private void button12_Click(object sender, EventArgs e) { culoare = Color.Red; } private void button7_Click(object sender, EventArgs e) { culoare = Color.YellowGreen; } private void button13_Click(object sender, EventArgs e) { culoare = Color.Yellow; } private void button8_Click(object sender, EventArgs e) { culoare = Color.DarkGreen; } private void button14_Click(object sender, EventArgs e) { culoare = Color.Green; } private void button9_Click(object sender, EventArgs e)
{
culoare = Color.DarkBlue; } private void button15_Click(object sender, EventArgs e) { culoare = Color.Blue; } private Button button1; private Button button2; private Button button3; private Button button4; private Button button5;
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
private Button button6; private Button button7; private Button button8; private Button button9; private Button button10; private Button button11; private Button button12; private Button button13; private Button button14; private Button button15; private void panel1_Paint(object sender, PaintEventArgs e) { gr = Graphics.FromImage(bmp); switch (forma) { case 1: { Algorithms alg = new Algorithms(); alg.Bresenham_line(p0.X, p1.X, p0.Y, p1.Y, gr, culoare); break; } case 2: { Algorithms alg = new Algorithms(); double dist = Math.Sqrt(Math.Pow((p1.X - p0.X), 2) + Math.Pow((p1.Y - p0.Y), 2)); raza = (int)Math.Round(dist); alg.rasterCircle(p0.X + (p1.X - p0.X) / 2, p0.Y + (p1.Y - p0.Y) / 2, raza / 2, gr, culoare); break; } #region //case 3: // { // Algorithms alg = new Algorithms(); // double dist = Math.Sqrt(Math.Pow((p1.X - p0.X), 2) + Math.Pow((p1.Y - p0.Y), 2)); // raza = (int)Math.Round(dist); // int raza1;
// double dist1 = Math.Sqrt(Math.Pow(raza, 2) - Math.Pow(raza / 2, 2));
// raza1 = (int)Math.Round(dist1); // alg.PlotEllipse(p0.X,p0.Y, raza / 2, 30, gr, culoare); // break; // } #endregion } } private void panel1_MouseClick(object sender, MouseEventArgs e)
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
{ if (contor != 0) { if (contor % 2 == 0) p0 = e.Location; else { p1 = e.Location; panel1.BackgroundImage = (Image)bmp; panel1.Refresh(); } contor++; //panel1.BackgroundImage = (Image)bmp; //panel1.Refresh(); } } private void panel1_MouseDown(object sender, MouseEventArgs e) { contor = 1; p0 = e.Location; //panel1.BackgroundImage = (Image)bmp; //panel1.Refresh(); } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (contor % 2 != 0) { p1 = e.Location; } } private void panel1_MouseUp(object sender, MouseEventArgs e) { p1 = e.Location; contor++; panel1.BackgroundImage = (Image)bmp; panel1.Refresh(); } } }
Algorithms.cs
using System; using System.Collections.Generic: using System.Text; using System.Drawing; using System.Windows.Forms; namespace Grafica { class Algorithms {
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
public void Bresenham_line(int x0, int x1, int y0, int y1, Graphics gr, Color culoare) { bool verif; if (Math.Abs(y1 - y0) - Math.Abs(x1 - x0) > 0) verif = true; else verif = false; if (verif) { int aux = x0; x0 = y0; y0 = aux; aux = x1; x1 = y1; y1 = aux; } if (x0 > x1) { int aux = x0; x0 = x1; x1 = aux; aux = y0; y0 = y1; y1 = aux; } int deltax = x1 - x0; int deltay = Math.Abs(y1 - y0); int error = -deltax / 2; int ystep; int y = y0; if (y0 < y1) ystep = 1; else ystep = -1; Pen Pen = new Pen(culoare, 2); for (int x = x0; x <= x1; x++) { if (verif) gr.DrawLine(Pen, new Point(y, x), new Point(y + 2, x + 2)); else gr.DrawLine(Pen, new Point(x, y), new Point(x + 2, y + 2));
error = error + deltay;
if (error > 0) { y = y + ystep; error = error - deltax; } } } public void rasterCircle(int x0, int y0, int radius, Graphics gr, Color culoare) {
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
int f = 1 - radius; int ddF_x = 0; int ddF_y = -2 * radius; int x = 0; int y = radius; Pen Pen = new Pen(culoare, 2); while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y;
} x++; ddF_x += 2; f += ddF_x + 1; gr.DrawLine(Pen, new Point(x0 + x, y0 + y), new Point(x0 + x + 2, y0 + y + 2)); gr.DrawLine(Pen, new Point(x0 - x, y0 + y), new Point(x0 - x + 2, y0 + y + 2)); gr.DrawLine(Pen, new Point(x0 + x, y0 - y), new Point(x0 + x + 2, y0 - y + 2)); gr.DrawLine(Pen, new Point(x0 - x, y0 - y), new Point(x0 - x + 2, y0 - y + 2)); gr.DrawLine(Pen, new Point(x0 + y, y0 + x), new Point(x0 + y + 2, y0 + x + 2)); gr.DrawLine(Pen, new Point(x0 - y, y0 + x), new Point(x0 - y + 2, y0 + x + 2)); gr.DrawLine(Pen, new Point(x0 + y, y0 - x), new Point(x0 + y + 2, y0 - x + 2)); gr.DrawLine(Pen, new Point(x0 - y, y0 - x), new Point(x0 - y + 2, y0 - x + 2)); } } } }
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
Algoritmul Cohen-Sutherland – CLIPPING
DecupareSegmente.java
import java.awt.*; import java.applet.*; import java.awt.event.*; class Point { double x,y; Point(double thisx, double thisy) { x=thisx; y=thisy; }
}
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
public class DecupareSegmente extends Frame { public static void main(String[] args){new DecupareSegmente();} DecupareSegmente() { super("Decupare Segmente Prin Algoritmul Cohen - Sutherland"); addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e){System.exit(0);}}); setSize(500, 400); add("Center", new CvSegmente()); setCursor(Cursor.getPredefinedCursor(CROSSHAIR_CURSOR)); show(); } } class CvSegmente extends Canvas { final int xMax = 500,yMax = 400; private int firstX, firstY,lastX,lastY,points = 0; //punctele dreptunghiului dupa care facem decupajul static double xLeft=100.0, xRight=400.0,yBottom=100.0, yTop=300.0; Point P0,P1; CvSegmente() { resize( xMax, yMax ); this.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent evt) { if(points == 0) { firstX=evt.getX(); firstY=evt.getY(); points++;} else if (points == 1) {lastX=evt.getX(); lastY=evt.getY(); points = 0; P0 = new Point((double)firstX,(double)firstY); P1 = new Point((double)lastX,(double)lastY); paint(getGraphics());} }}); show(); } public void paint(Graphics g) { g.setColor(Color.red); g.drawString("Dati click in doua puncte ale ferestei si se va afisa in interiorul dreptunghiului",20,20); g.drawString("segmentul determinat de catre cele 2 puncte ",20, 40); g.setColor(Color.black); g.drawRect((int)xLeft,(int)yBottom, (int)(xRight-xLeft), (int)(yTop-yBottom)); if(CohenSutherland(P0,P1)) { g.setColor(Color.blue); g.drawLine((int)P0.x,(int)P0.y, (int)P1.x,(int)P1.y); }
}
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
private static int Test(Point P) { int Cod = 0; if(P.y > yTop) Cod += 1; // deasupra dreptunghiului WT else if(P.y < yBottom) Cod += 2; // sub dreptunghi WB if(P.x > xRight) Cod += 4; // in dreapta dreptunghiului WR else if(P.x < xLeft) Cod += 8; //in stanga dreptunghiului WL return Cod; } private static boolean VerifNotOk(int Cod1, int Cod2) { if ((Cod1 & Cod2) != 0 ) return true; return(false); } private static boolean VerifOk(int Cod1, int Cod2) { if ( (Cod1 == 0) && (Cod2 == 0) ) return(true); return(false); } static boolean CohenSutherland(Point P0,Point P1) { int Cod0,Cod1; while(true) { Cod0 = Test(P0); Cod1 = Test(P1); if( VerifNotOk(Cod0,Cod1) ) return(false); if( VerifOk(Cod0,Cod1) ) return(true); if(Cod0 == 0) { double tempCoord; int tempCod; tempCoord = P0.x; P0.x= P1.x; P1.x = tempCoord; tempCoord = P0.y; P0.y= P1.y; P1.y = tempCoord; tempCod = Cod0; Cod0 = Cod1; Cod1 = tempCod; } if( (Cod0 & 1) != 0 ) { P0.x += (P1.x - P0.x)*(yTop - P0.y)/(P1.y - P0.y); P0.y = yTop; } else if( (Cod0 & 2) != 0 ) { P0.x += (P1.x - P0.x)*(yBottom - P0.y)/(P1.y - P0.y); P0.y = yBottom; } else if( (Cod0 & 4) != 0 ) {
Conf. Dr. Marin Vlada, Universitatea din Bucuresti
www.ad-astra.ro/marinvlada
P0.y += (P1.y - P0.y)*(xRight - P0.x)/(P1.x - P0.x); P0.x = xRight; } else if( (Cod0 & 8) != 0 ) { P0.y += (P1.y - P0.y)*(xLeft - P0.x)/(P1.x - P0.x); P0.x = xLeft; } } } }