Post on 09-Apr-2018
8/7/2019 algoritmul bresenham
1/39
Cuprins:
1. Introducere2. Arc de cerc . Algoritmul DDA
3. Aplicatie
1
8/7/2019 algoritmul bresenham
2/39
Algoritmul de linie de Bresenham este un algoritm care determincare puncte dimensionale ar trebui s fie reprezentate grafic cu scopul de aforma o apropiere de o linie dreapt ntre dou puncte date. Acesta este deobicei folosite pentru a trage linii pe ecranul unui computer, n care sefolosete numai numere ntregi, scderea i trecerea de bii, care sunt toateoperaiuni foarte ieftine n arhitecturi standard. Aceasta este unul dintre celemai timpurii algoritmi de dezvoltare n domeniul de grafica pe calculator. Oextensie minora la algoritmul de origine, de asemenea, se ocupa cudesenarea de cercuri. . n timp ce algoritmi, cum ar fi algoritmul lui Wu,sunt, de asemenea, utilizate frecvent in grafica pe calculator deoareceacestea pot sprijini viteza i simplitatea algoritmului linie Bresenhamnseamn c acesta este nc important. Algoritmul este folosit n hardware,cum ar fi plotere n cipuri grafice moderne de plci grafice.. Acesta poate fi,de asemenea, gasit in bibliotecile multor software-ul. Deoarece acestalgoritm este foarte simplu, nu este adesea pus n aplicare n nici unfirmware-ul sau hardware-ul modern de plci grafice.
Eticheta "Bresenham" este utilizata astzi pentru o familie ntreag dealgoritmi de prelungire sau modificarea algoritmului Bresenham original allui. A se vedea referinele n continuare mai jos.
Algoritmul va fi iniial prezentat numai pentru octant n care segmentul seduce n jos i la dreapta (x0 x1 iy0 y1), precum i proiecia sa orizontal
x1 -x0 este mai lung dect Yproiecie vertical 1 - Y0 (linie are o pant maimic de 1 i mai mare dect 0.) n aceast octant, pentru fiecare coloan xntrex0 ix1, exist exact un rnd Y(calculat prin algoritmul) care conine
un pixel de linie, n timp ce fiecare rnd ntre y 0 i y 1 poate conine maimulte pixeli raster.
Algoritmul lui Bresenham alege Y intreg care corespunde cel mai apropiatcentru de pixeli care este idealul (fracionat)y pentru acelaiX; pe coloanesuccesive Y poate rmne acelai sau s creasc pn la 1. Ecuaia generala liniei prin obiective este dat de:
2
8/7/2019 algoritmul bresenham
3/39
Din moment ce tim coloan,x, rndul pixelilor lui,y, este dat de rotunjireaacestuia functie de cel mai apropiat numr ntreg:
Panta (y1 -y0) / (x1 - x 0) depinde de obiectivul coordonatelor, dar poate ficalculat, iar Y ideal pentru valori succesive ale luix numr ntreg, poate ficalculat pornind de la Y 0 i n mod repetat, adugnd pant .
n practic, algoritmul poate urmri, n loc de o valoare mare a lui Y, ovaloare mic a erorii ntre -0,5 i 0,5: distana vertical ntre valorile
rotunjite si exacte ale lui Y, pentru X curent. De fiecare dat cnd x estecrescut, eroarea este sporit datorita pantei lor; n cazul n care depete 0.5,
y este crescut cu 1 iar eroarea este decrementata de 1.0
urmtoarelea secventa de cod returneaza valoare absolut:
linie de funcie (x0, x1, y0, y1)
int
deltax := x1 - x0 deltaxint:
= x1 - x0 int deltay := y1 - y0 deltay int: = y1 - y0 real error := 0 Eroare real: = 0
real deltaerr := deltay / deltax // Assume deltax != 0 (line isnot vertical), deltaerr real: = deltay / deltax / / presupunem deltax!
= 0 (linie nu este vertical),// note that this division needs to be done in a way that
preserves the fractional part / / Act de faptul c aceast diviziune
trebuie s se fac ntr-un mod care pstreaz o parte fracionat
int y := y0 int y: = y0 for x fromx0 to x1pentru x de la x0 la x1
plot(x,y) plot (x, y)error := error + deltaerr error: = eroare de + deltaerr
if abs(error) 0.5 thenn cazul n care abs (eroare) 0,5,
atunciy := y + 1 Y: = y + 1error := error - 1.0 error: = eroare - 1.0
3
8/7/2019 algoritmul bresenham
4/39
Versiunea de mai sus afiseaza linii care coboara spre dreapta. Ne-amdori, desigur, s fie n msur s trag toate liniile.. Primul caz este ceea cene permite s elaboreze linii care nc mai au panta in jos dar din capatul
opus . Aceasta este o simpl cale de reprezentare de puncte iniial n cazul ncare x0>x1. Mai complicat este de a determina cum s elaboreze linii caremerg in sus. . Pentru a face acest lucru, vom verifica dacy 0Y1; dac esteaa, modificam pasul y cu -1 n loc de 1. n sfrit, avem n continuarenevoie pentru a generaliza un algoritm de la desena linii n toate direciile.Pn acum am fost doar n msur s elaboreze linii cu o panta. Pentru a ficapabili s elaboreze linii, cu o pant mai mare, vom profita de faptul c olinie abrupt se poate reflecta n ntreaga linie Y = x pentru a obine o liniecu o pant mic. Efectul este pentru a comutax i variabilele Y,Codul arata
astfel:
function line(x0, x1, y0, y1) linie de funcie (x0, x1, y0, y1) boolean steep := abs(y1 - y0) > abs(x1 - x0) boolean abrupt: = abs
(y1 - y0)> abs (x1 - x0) if steep thenn cazul n care abrupte, atunci
swap(x0, y0) swap (x0, y0)swap(x1, y1) swap (x1, y1)
if x0 > x1 thenn cazul n care x0> x1, apoiswap(x0, x1) swap (x0, x1)
swap(y0, y1) swap (y0, y1)
int deltax := x1 - x0 deltax int: = x1 - x0 int deltay := abs(y1 - y0) deltay int: = abs (y1 - y0) real error := 0 Eroare real: = 0
real deltaerr := deltay / deltax deltaerr real: = deltay / deltax
int ystep ystep int
int y := y0 int y: = y0 if y0 < y1 then ystep := 1 else ystep := -1 n cazul n care Y0
8/7/2019 algoritmul bresenham
5/39
Problema cu aceast abordare este c aceste calculatoare funcioneazrelativ lent pe numerele fractionare cum ar fi error i deltaerr n plus,erori pot acumula peste multe completri n virgul mobil. Lucrul cunumere ntregi, va fi mai rapid i mai precis. Trucul pe care le folosim este
de a multiplica toate numerele de fracionare de mai sus prin deltax carene permite s le exprimam ca numere ntregi. Singura problem rmas esteconstanta 0,5 de a face cu acest lucru, vom schimba initializarea de errorvariabile, si inversand-o pentru o optimizare suplimentar de micidimensiuni. Nou program arata astfel:
function line(x0, x1, y0, y1) linie de funcie (x0, x1, y0, y1)
boolean steep := abs(y1 - y0) > abs(x1 - x0) boolean abrupt: = abs
(y1 - y0)> abs (x1 - x0)
if steep thenn cazul n care abrupte, atunciswap(x0, y0) swap (x0, y0)
swap(x1, y1) swap (x1, y1)
if x0 > x1 thenn cazul n care x0> x1, apoiswap(x0, x1) swap (x0, x1)swap(y0, y1) swap (y0, y1)
int deltax := x1 - x0 deltax int: = x1 - x0
int deltay := abs(y1 - y0) deltay int: = abs (y1 - y0)
int error := deltax / 2 eroare int: = deltax / 2 int ystep ystep int
int y := y0 int y: = y0 if y0 < y1 then ystep := 1 else ystep := -1 n cazul n care Y0
8/7/2019 algoritmul bresenham
6/39
Algoritmul a fost dezvoltat de Jack E. Bresenham n 1962, la IBM. n anul2001 Bresenham a scris:
"Am fost de lucru n laboratorul de calcul de la IBM, San Joselaborator de dezvoltare. Un plotter CalComp a fost ataat la un IBM
1401, prin intermediul mainii de scris, 1407 consol. Algoritmul afost n utilizarea n producie pn n vara anului 1962, eventual, o
lun sau cam asa ceva mai devreme. Programele n acele zile au fostn mod liber schimbate ntre corporaii att de CalComp (Jim
Newland i Calvin Hefte). Cnd m-am ntors la Stanford, n toamna
1962, am pus o copie n biblioteca comp Stanford Center.O descriere a liniei de tragere de rutin a fost acceptat pentru
prezentare la 1963 ACM Conveniei Naionale n Denver, Colorado..Acesta a fost un an n care procedurile nu au fost publicate, numai
ordinea de zi i subiecte ntr-o problem de Comunicaii a ACM..Opersoan din sistemele IBM Oficial ma ntrebat dup ce am fcutprezentarea mea,daca doresc sa imi fie publicat proiectul.. "Am fostfericit si de acord, i auimprimat-o n 1965. "
Algoritmul Bresenham mai trziu a fost modificat pentru a producecercuri, algoritmul rezultat fiind uneori cunoscut fie ca algoritmul "cerc"Bresenham sau algoritm de punctul de mijloc cerc.Algoritmul Bresenham
poate fi interpretat ca o uore modificare ADD (folosind 0.5 ca pragul deeroare n loc de 0,). Principiul de a folosi o eroare de incrementare, n loc de
operaiuni de divizare care are alte aplicaii in grafica.. Este posibil s seutilizeze aceast tehnic pentru a calcula U, V, coordonatele n timpul rasterscanda de textura poligoane cartografiate. Bresenham, de asemenea, a
publicat un Run-Slice (spre deosebire de Run-Length), algoritmul de calcul.
O extindere a algoritmului care se ocup de linii groase, a fost creat de AlanMurphy la IBM.
6
http://translate.googleusercontent.com/translate_c?hl=en&ie=UTF-8&sl=en&tl=ro&u=http://en.wikipedia.org/wiki/IBM_1401&prev=_t&rurl=translate.google.com&usg=ALkJrhj6NdvaaX5C-HlPM7Q6oYthXpygAAhttp://translate.googleusercontent.com/translate_c?hl=en&ie=UTF-8&sl=en&tl=ro&u=http://en.wikipedia.org/wiki/IBM_1401&prev=_t&rurl=translate.google.com&usg=ALkJrhj6NdvaaX5C-HlPM7Q6oYthXpygAAhttp://translate.googleusercontent.com/translate_c?hl=en&ie=UTF-8&sl=en&tl=ro&u=http://en.wikipedia.org/wiki/IBM_1401&prev=_t&rurl=translate.google.com&usg=ALkJrhj6NdvaaX5C-HlPM7Q6oYthXpygAAhttp://translate.googleusercontent.com/translate_c?hl=en&ie=UTF-8&sl=en&tl=ro&u=http://en.wikipedia.org/wiki/IBM_1401&prev=_t&rurl=translate.google.com&usg=ALkJrhj6NdvaaX5C-HlPM7Q6oYthXpygAA8/7/2019 algoritmul bresenham
7/39
ARC DE CERC. ALGORITMUL DDA
ARC DE CERC.
Arcul de cerc este o parte a circumferintei cercului. Atunci lungimea arculuieste o fractiune a circumferintei pe care o acopera. Lungimea este
proportional cu dimensiunea unui unghi la central opus arcului. Dinconvenient vom numi acest unghi unghiul unui arc de cerc.
Arcurile de cerc sunt masurate prin doua cai:ca masurare a unhiului centralsau ca lungimea arcului insusi.Masurarea unghiului central(in grade)
Arcul rosu masoara 120o
Arcul albastru masoara240o
Masurare in functie de lungimea arcului(in radiani)Formula:s = rs = lungime arculuir= radianii cercului = masurarea unghiului central in radiani
7
8/7/2019 algoritmul bresenham
8/39
Arcul rosu: r= 2 si = 2/3, decis = 4/3
Arcul albastru: r= 2 si = 4/3, decis = 8/3
Lungimea arcului de cerc
Unghiul centrului are 360o si este proportional cu circumferinta. Folosindproportionaliatea avem:
Formula de mai sus ne permite sa calculam orice valoare daca se dau celelalte doua
valori.Calculul lungimii unui arc
Din formula putem calcula lungimea unui arc de cerc.Exemplu:
Daca circumferinta cercului este de 54 cm, care este lungimea unghiului ABC?
8
8/7/2019 algoritmul bresenham
9/39
Solutie:
Lungimea arcului = x 54= 18 cm
Exemplu: daca radianul uni cerc este 5cm si unghiul arcului este 110o , care este lungimeaarcului?
Solutie:
Circumferinta= 2r
lungimea arcului = x 2 x 5 = 9,6cm
9
8/7/2019 algoritmul bresenham
10/39
Aplicatie
// MainFrame.cpp : implementation of the CMainFrame class//
#include "stdafx.h"
#include "spp.h"
#include
#include "MainFrame.h"
#define PI 3.1415926
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
float k=0;
float r1=6.0,r2=4.0,r3=2.0;
/////////////////////////////////////////////////////////////////////////////
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
10
8/7/2019 algoritmul bresenham
11/39
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_SETFOCUS()
ON_WM_QUERYNEWPALETTE()
ON_WM_PALETTECHANGED()
ON_WM_ACTIVATEAPP()
ON_WM_KEYDOWN()
ON_WM_TIMER()
ON_WM_CREATE()
ON_WM_LBUTTONDOWN()
ON_WM_DESTROY()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
VB_WIDTH = 1024;
VB_HEIGHT = 768;
VB_DEPTH = 32;
m_bFullScreen = FALSE;
11
8/7/2019 algoritmul bresenham
12/39
m_hDC = NULL;
m_hRC = NULL;
m_cxClient = 0;
m_cyClient = 0;
m_hPal = NULL;
m_bAppIsActive = FALSE;
// Ask The User Which Screen Mode They Prefer
if (MessageBox("Would You Like To Run In Fullscreen Mode?", "StartFullScreen?",MB_YESNO|MB_ICONQUESTION)==IDYES)
{
m_bFullScreen=TRUE;// Windowed Mode
}
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
KillGLWindow(); // Shutdown
}
12
8/7/2019 algoritmul bresenham
13/39
/////////////////////////////////////////////////////////////////////////////
// CMainFrame PreCreateWindow
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if (!CFrameWnd::PreCreateWindow(cs))
return FALSE;
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS,&m_DMsaved); // save the current display state
if (m_bFullScreen)// Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings;// Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings));// Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings);
// Size Of The Devmode StructuredmScreenSettings.dmPelsWidth = VB_WIDTH;
// Selected Screen Width
dmScreenSettings.dmPelsHeight = VB_HEIGHT;// Selected Screen Height
13
8/7/2019 algoritmul bresenham
14/39
dmScreenSettings.dmBitsPerPel = VB_DEPTH;// Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE:CDS_FULLSCREEN Gets Rid Of Start Bar.
if(ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or UseWindowed Mode.
if (MessageBox("The Requested Fullscreen Mode Is NotSupported By\nYour Video Card. Use Windowed Mode Instead?","NeHeGL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
m_bFullScreen=FALSE;// Windowed Mode Selected.
}
else
{
// Pop Up A Message Box Letting User Know TheProgram Is Closing.
MessageBox("Program Will NowClose.","ERROR",MB_OK|MB_ICONSTOP);
14
8/7/2019 algoritmul bresenham
15/39
return FALSE;
}
}}
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
cs.cx = VB_WIDTH;
cs.cy = VB_HEIGHT;
if (m_bFullScreen)// Are We Still In Fullscreen Mode?
{
cs.dwExStyle=WS_EX_APPWINDOW;// Window Extended Style
cs.style=WS_POPUP;// Windows Style
ShowCursor(FALSE);
// Hide Mouse Pointer}
else
15
8/7/2019 algoritmul bresenham
16/39
{
cs.dwExStyle=WS_EX_APPWINDOW |WS_EX_WINDOWEDGE; // Window Extended Style
cs.style=WS_OVERLAPPEDWINDOW;// Windows Style
cs.y = (int) GetSystemMetrics(SM_CYSCREEN) / 2 - cs.cy / 2;
cs.x = (int) GetSystemMetrics(SM_CXSCREEN) / 2 - cs.cx / 2;
}
cs.lpszClass = AfxRegisterWndClass(CS_OWNDC|CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,
LoadCursor(NULL,IDC_ARROW), NULL, NULL);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{CFrameWnd::AssertValid();
}
16
8/7/2019 algoritmul bresenham
17/39
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnCreateClient
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs,
CCreateContext* pContext)
{
// TODO: Add your specialized code here and/or call the base class
BOOL bRet = CFrameWnd::OnCreateClient(lpcs, pContext);
if (bRet)
{
GLuintPixelFormat;// Holds The Results After Searching For A
Match
static PIXELFORMATDESCRIPTOR pfd=// pfd Tells Windows How We Want
Things To Be
17
8/7/2019 algoritmul bresenham
18/39
{
sizeof(PIXELFORMATDESCRIPTOR),// Size Of This Pixel Format
Descriptor1,
// Version Number
PFD_DRAW_TO_WINDOW |// Format Must Support
Window
PFD_SUPPORT_OPENGL |// Format Must Support OpenGL
PFD_DOUBLEBUFFER,// Must Support Double
Buffering
PFD_TYPE_RGBA,// Request An RGBA Format
VB_DEPTH,// Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0,// No Alpha Buffer
0,// Shift Bit Ignored
0,// No Accumulation
Buffer0, 0, 0, 0,
// Accumulation Bits Ignored
16,// 16Bit Z-Buffer
(Depth Buffer)
18
8/7/2019 algoritmul bresenham
19/39
0,// No Stencil Buffer
0,// No Auxiliary Buffer
PFD_MAIN_PLANE,// Main Drawing Layer
0,// Reserved
0, 0, 0// Layer Masks Ignored
};
if ( !( m_hDC = ::GetDC ( m_hWnd ) ) ) {// Did We Get A Device Context?
KillGLWindow (); // Reset The Display
MessageBox ( "Can't Create A GL Device Context.","ERROR", MB_OK | MB_ICONEXCLAMATION );
return FALSE;
}
if ( !( PixelFormat = ChoosePixelFormat ( m_hDC, &pfd ) ) ){ // Did Windows Find A Matching Pixel Format?
19
8/7/2019 algoritmul bresenham
20/39
KillGLWindow ();// Reset The Display
MessageBox ( "Can't Find A Suitable PixelFormat.","ERROR", MB_OK | MB_ICONEXCLAMATION );
return FALSE;
}
if ( !SetPixelFormat ( m_hDC, PixelFormat, &pfd ) ){// Are We Able To Set The Pixel Format?
KillGLWindow ();// Reset The Display
MessageBox ( "Can't Set The PixelFormat.", "ERROR",MB_OK | MB_ICONEXCLAMATION );
return FALSE;
}
if ( !( m_hRC = wglCreateContext ( m_hDC ) ) ) {// Are We Able To Get A Rendering Context?
KillGLWindow (); // Reset The Display
MessageBox( " Can't Create A GL Rendering Context.","ERROR", MB_OK | MB_ICONEXCLAMATION );
return FALSE;
20
8/7/2019 algoritmul bresenham
21/39
}
if ( !wglMakeCurrent ( m_hDC, m_hRC ) ) {// Try To Activate The Rendering Context
KillGLWindow ();// Reset The Display
MessageBox ( "Can't Activate The GL RenderingContext.", "ERROR", MB_OK | MB_ICONEXCLAMATION );
return FALSE;
}
if ( !InitGL () ) {// Initialize Our Newly Created GL
Window
KillGLWindow ();// Reset The Display
MessageBox ( "Initialization Failed.", "ERROR", MB_OK| MB_ICONEXCLAMATION );
return FALSE;
}
m_bAppIsActive = TRUE;
}
21
8/7/2019 algoritmul bresenham
22/39
return bRet;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnPaint
void CMainFrame::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CMainFrame::OnPaint() for painting messages
::ValidateRect ( m_hWnd, NULL );
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnSize
void CMainFrame::OnSize(UINT, int cx, int cy)
{
22
8/7/2019 algoritmul bresenham
23/39
m_cxClient = cx;
m_cyClient = cy;
ReSizeGLScene( cx, cy );
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnSetFocus
void CMainFrame::OnSetFocus(CWnd* pOldWnd)
{
OnQueryNewPalette();
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnCreateClient
BOOL CMainFrame::OnQueryNewPalette()
{
Invalidate();
return TRUE;
}
23
8/7/2019 algoritmul bresenham
24/39
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnPaletteChanged
void CMainFrame::OnPaletteChanged(CWnd* pFocusWnd)
{
if ((pFocusWnd != this) && (!IsChild(pFocusWnd)))
OnQueryNewPalette();
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnActivateApp
void CMainFrame::OnActivateApp(BOOL bActive, HTASK hTask)
{
CFrameWnd::OnActivateApp(bActive, hTask);
m_bAppIsActive = bActive;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame RenderGLScene
24
8/7/2019 algoritmul bresenham
25/39
void draw_circle(float r, float z)
{
float angle=0.0,n=365,i=0,x=0,y=0;
glBegin(GL_LINE_STRIP);
glVertex3f(r,0,0);
for(i=0;i=-1.5;h=h-0.03)
for(R=10.0;R>=8;R=R-0.05)
{
glColor3f(0.6/(0.13*R),0.4/(0.13*R),0.8/(0.13*R));
draw_circle(R,h);
}
25
8/7/2019 algoritmul bresenham
26/39
glColor3f(0.4,1.0,0.0);
draw_circle(r_1,r_1*(-0.2));
draw_circle(r_2,r_2*(-0.2));
draw_circle(r_3,r_3*(-0.2));
glBegin(GL_LINES);
glVertex3f(8,0,-0.5);
glVertex3f(-8,0,-0.5);
glVertex3f(0,8,-0.5);
glVertex3f(0,-8,-0.5);
glEnd();
}
void drawfan(float k1)
{
float angle2,x,y,j;
glBegin(GL_TRIANGLE_FAN);
glColor3f(1,0,0);
glVertex3f(0,0,-0.5);
glColor3f(0,1,0);
for(j=k1;j
8/7/2019 algoritmul bresenham
27/39
glVertex3f(8*cos(angle2),8*sin(angle2),-0.5);
}
glEnd();
}
void DrawCoordination(float length)
{
glBegin(GL_LINES);
glColor3f(0.7,0,0);
glVertex3f(0,0,-0.5);
glVertex3f(length,0,-0.5);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.7,0,0);
glVertex3f(length, 0, -0.5);
glVertex3f((1-0.2)*length, 0.05*length, -0.5);
glVertex3f((1-0.2)*length, -0.05*length, -0.5);
glVertex3f(length, 0, -0.5);
glVertex3f((1-0.2)*length, 0, 0.05*length-0.5);
glVertex3f((1-0.2)*length, 0, -0.05*length-0.5);
glEnd();
}
27
8/7/2019 algoritmul bresenham
28/39
void CMainFrame::RenderGLScene()
{
if (!m_bAppIsActive)
return;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear Screen And Depth Buffer
glLoadIdentity();
// EXAMPLE OPENGL CODESTART ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
static GLfloat xrot;// X Rotation
static GLfloat yrot;// Y Rotation
static GLfloat zrot;// Z Rotation
glPushMatrix();// Push Matrix Onto Stack (Copy The
Current Matrix)
glLoadIdentity();
// Reset The Current ModelviewMatrix
glTranslatef(0.0f,0.0f,-40.0f);// Move Into The Screen 40.0
28
8/7/2019 algoritmul bresenham
29/39
glRotatef(-60, 1, 0, 0);
// glRotatef(xrot,1.0f,0.0f,0.0f);
// glRotatef(yrot,0.0f,1.0f,0.0f);
// glRotatef(zrot,0.0f,0.0f,1.0f);
DrawCoordination(15);
glPushMatrix();
glRotatef(90, 0, 0, 1);
DrawCoordination(15);
glPopMatrix();
drawx(r1,r2,r3);
// glPushMatrix();
// glRotatef(zrot, 0, 0, 1);
drawfan(k);
// glPopMatrix();
glPopMatrix();// Pop Matrix Off The Stack
xrot+=1.5f;
yrot+=1.5f;
29
8/7/2019 algoritmul bresenham
30/39
zrot+=1.5f;// Scaderea variabila de
rotatie pentru Quad
//////////////////////////////////////////////////////////////////////////////
// EXAMPLE OPENGL CODEEND //////////////////////////////////////////////////////////
// Swap our scene to the front
SwapBuffers(m_hDC);
Invalidate(FALSE);
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnCreateClient
GLvoid CMainFrame::ReSizeGLScene(GLsizei width, GLsizei height)// Resize And Initialize The GL Window
{
if ( height==0) {
// Prevent A Divide By Zero By
height=1;// Making Height Equal One
30
8/7/2019 algoritmul bresenham
31/39
}
glViewport(0,0,width,height);// Reset The Current Viewport
glMatrixMode(GL_PROJECTION);// Select The Projection Matrix
glLoadIdentity();
// Reset The Projection Matrix
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);// Calculate The Aspect Ratio Of The Window
glMatrixMode(GL_MODELVIEW);// Select The Modelview Matrix
glLoadIdentity();// Reset The Modelview Matrix
}
//////////////////////////////////////////////////////////////////////////////
// CMainFrame InitGL
int CMainFrame::InitGL(GLvoid)// All Setup For OpenGL Goes Here
31
8/7/2019 algoritmul bresenham
32/39
{
// EXAMPLE DIRECT SOUND CODE
START //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// EXAMPLE DIRECT SOUND CODEEND ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
glShadeModel(GL_SMOOTH);// Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);// Black Background
glClearDepth(1.0f);// Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL);// The Type Of Depth Testing
To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);// Really Nice Perspective Calculations
glEnable(GL_TEXTURE_2D);
// Enable Texture Mapping
return TRUE;// Initialization Went OK
}
32
8/7/2019 algoritmul bresenham
33/39
//////////////////////////////////////////////////////////////////////////////
// CMainFrame KillGLWindow
GLvoid CMainFrame::KillGLWindow(GLvoid)// Properly Kill The Window
{
if (m_bFullScreen)// Are We In Fullscreen
Mode?{
if (!ChangeDisplaySettings(NULL,CDS_TEST)) {// if the shortcut doesn't work
ChangeDisplaySettings(NULL,CDS_RESET);// Do it anyway (to get the values out of the
registry)
ChangeDisplaySettings(&m_DMsaved,CDS_RESET);// change it to the saved settings
} else {
ChangeDisplaySettings(NULL,CDS_RESET);
}
ShowCursor(TRUE); // Show Mouse Pointer
}
33
8/7/2019 algoritmul bresenham
34/39
if ( m_hRC ) {// Do We Have A Rendering
Context?
if ( !wglMakeCurrent ( NULL, NULL ) ) {// Are We Able To Release The DC And RCContexts?
MessageBox ( "Release Of DC And RC Failed.","SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION );
}
if ( !wglDeleteContext ( m_hRC ) ) {// Are We Able To Delete The RC?
MessageBox ( "Release Rendering Context Failed.","SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION );
}
m_hRC = NULL;// Set RC To NULL
}
if ( m_hDC && !::ReleaseDC ( m_hWnd, m_hDC ) ) {// Are We Able To Release The DC
MessageBox ( "Release Device Context Failed.", "SHUTDOWNERROR", MB_OK | MB_ICONINFORMATION );
m_hDC = NULL;
// Set DC To NULL}
if ( m_hWnd && !::DestroyWindow ( m_hWnd ) ) {// Are We Able To Destroy The Window?
34
8/7/2019 algoritmul bresenham
35/39
MessageBox( "Could Not Release m_hWnd.", "SHUTDOWNERROR", MB_OK | MB_ICONINFORMATION );
m_hWnd = NULL;// Set m_hWnd To NULL
}
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame OnKeyDown
void CMainFrame::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
CFrameWnd::OnKeyDown(nChar, nRepCnt, nFlags);
// TODO: Add your message handler code here and/or call default
switch ( nChar ) {
case VK_ESCAPE:
PostMessage ( WM_CLOSE );
break;
} // end switch
35
8/7/2019 algoritmul bresenham
36/39
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
SetTimer(1,100,NULL);
SetTimer(2,5,NULL);
return 0;
}
void CMainFrame::OnDestroy()
{
CFrameWnd::OnDestroy();
KillTimer(1);
KillTimer(2);
}
void CMainFrame::OnTimer(UINT nIDEvent)
{
switch(nIDEvent)
{
case 1:
r1=r1+0.5;r2=r2+0.5;r3=r3+0.5;
if(r1>=8) r1=0;
36
8/7/2019 algoritmul bresenham
37/39
if(r2>=8) r2=0;
if(r3>=8) r3=0;
case 2:
k=k+0.5;
}
Invalidate();
CFrameWnd::OnTimer(nIDEvent);
}
void CMainFrame::OnLButtonDown(UINT nFlags, CPoint point)
{
AfxMessageBox(",\n\t\t\txin");
CFrameWnd::OnLButtonDown(nFlags, point);
}
37
8/7/2019 algoritmul bresenham
38/39
38
8/7/2019 algoritmul bresenham
39/39