【文档说明】计算机图形学computer-graphics课件7.ppt,共(45)页,1.108 MB,由小橙橙上传
转载请保留链接:https://www.ichengzhen.cn/view-77496.html
以下为本文档部分文字说明:
InputandInteractionYuanfengZhouShandongUniversitySoftwareCollege1Objectives•Introducethebasicinputdevices-Phys
icalDevices-LogicalDevices-InputModes•Event-driveninput•Introducedoublebufferingforsmoothanimations•ProgrammingeventinputwithGLUT2ProjectSke
tchpad•IvanSutherland(MIT1963)establishedthebasicinteractiveparadigmthatcharacterizesinteractivecomputerg
raphics:-Userseesanobjectonthedisplay-Userpointsto(picks)theobjectwithaninputdevice(lightpen,mouse,trackball)-Ob
jectchanges(moves,rotates,morphs)-Repeat3InteractionwithGraphicsSystem4ChangeImageReacttoChangeGraphicsSystemUserInputDeviceDisplayGraph
icalInput•Devicescanbedescribedeitherby-Physicalproperties•Mouse•Keyboard•Trackball(Thinkpad)-Logicalproperti
es•WhatisreturnedtoprogramviaAPI(ApplicationProgrammingInterface)–Aposition–Anobjectidentifier•Modes-
Howandwheninputisobtained•Requestorevent5LogicalProperties6ApplicationModelApplicationProgramGraphicsSystemOutputDevicesInputDevicesAPIFunctionC
allsorProtocolDataWM_LBUTTONDOWN#defineON_BN_LBUTTONDOWN(id,memberFxn)voidCMyProgram::OnLButtonDown(UINTnF
lags,CPointpoint){processingcode…CButton::OnLButtonDown(nFlags,point);}PhysicalDevices7mousetrackballlightpendatatabletjoystickspaceba
llLogicalDevices•ConsidertheCandC++code-C++:cin>>x;-C:scanf(“%d”,&x);•Whatistheinputdevice?-Can’ttellfromthecode-Couldbekeyb
oard,file,outputfromanotherprogram•Thecodeprovideslogicalinput-Anumber(anint)isreturnedtotheprogramregardlessofthep
hysicaldevice8GraphicalLogicalDevices•Graphicalinputismorevariedthaninputtostandardprogramswhichisusuallynumbers,char
acters,orbits•TwoolderAPIs(GKS77’,PHIGS90’)definedsixtypesoflogicalinput:-Locator:returnaposition-Pick:returnIDofanobject-Keyboard:retu
rnstringsofcharacters-Stroke:returnarrayofpositions-Valuator:returnfloatingpointnumber-Choice:returnoneofnitems910XWindowInput•TheXWindowS
ystemintroducedaclient-servermodelforanetworkofworkstations-Client:OpenGLprogram-GraphicsServer:bitmapdisplaywithapointingdevicea
ndakeyboardDisplayListinOpenGL•Matrixcomputation•Imagedisplay•Light,material•Texture•Polygonalobjects
display11DisplayListinOpenGL•voidglNewList(GLuintlist,GLenummode);•mode:GL_COMPILEandGL_COMPILE_AND_EXECUTE•voidglEndList(void);•NOTincludedinDisplay
List:•glDeleteLists()glIsEnable()•glFeedbackBuffer()glIsList()•glFinish()glPixelStore()•glGenLists()glRenderMode()•glGet*()gl
SelectBuffer()12DisplayListinOpenGL•Example:GLuintlistName=1;voidmyinit(void){glNewList(listName,GL_COMPILE);glColor3f(1.0,0.0,0
.0);glBegin(GL_TRIANGLES);glVertex2f(0.0,0.0);glVertex2f(1.0,0.0);glVertex2f(0.0,1.0);glEnd();glTranslatef(
1.5,0.0,0.0);glEndList();glShadeModel(GL_FLAT);}13voidCALLBACKdisplay(void){GLuinti;glClear(GL_COLOR_BUFFER_B
IT);glColor3f(0.0,1.0,0.0);glPushMatrix();for(i=0;i<5;i++)glCallList(listName);drawLine();glPopMatrix();glFl
ush();}InputMode•Inputdevicescontainatriggerwhichcanbeusedtosendasignaltotheoperatingsystem-Buttononm
ouse-Pressingorreleasingakey•Whentriggered,inputdevicesreturninformation(theirmeasure)tothesystem-Mouser
eturnspositioninformation-KeyboardreturnsASCIIcode14RequestMode•Inputprovidedtoprogramonlywhenusertriggersthedevice•
Typicalofkeyboardinput-Canerase(backspace),edit,correctuntilenter(return)key(thetrigger)isdepressed151.Programrequestsmeasureofadeviceandblocks.2.
Measureprocessmaintainscurrentmeasure.3.Triggerprocesssignalsmeasureprocesstoreturnmeasure.request_locator(device_id,&measure);EventMode•Mostsys
temshavemorethanoneinputdevice,eachofwhichcanbetriggeredatanarbitrarytimebyauser•Eachtriggergeneratesaneventwh
osemeasureisputinaneventqueuewhichcanbeexaminedbytheuserprogram16glutMainLoop();EventTypes•Window:resize,expose,iconif
y•Mouse:clickoneormorebuttons•Motion:movemouse•Keyboard:pressorreleaseakey•Idle:nonevent-Definewhatshouldbedoneifnoothereve
ntisinqueue17Callbacks•Programminginterfaceforevent-driveninput•Defineacallbackfunctionforeachtypeofeventthegraphicssystemrecognizes
•Thisuser-suppliedfunctionisexecutedwhentheeventoccurs•GLUTexample:glutMouseFunc(mymouse)18mousecall
backfunction19GLUTcallbacksGLUTrecognizesasubsetoftheeventsrecognizedbyanyparticularwindowsystem(Windows,X,Macintosh)-glutDisplayFunc-glutMous
eFunc-glutReshapeFunc-glutKeyboardFunc-glutIdleFunc-glutMotionFunc-glutPassiveMotionFuncGLUTEventLoop•Recallthatthelastlineinmain
.cforaprogramusingGLUTmustbeglutMainLoop();whichputstheprograminaninfiniteeventloop•Ineachpassthroughtheeve
ntloop,GLUT-looksattheeventsinthequeue-foreacheventinthequeue,GLUTexecutestheappropriatecallbackfunctionifoneisdefined-ifnocallbackisdefinedfo
rtheevent,theeventisignored20Usingglobals•TheformofallGLUTcallbacksisfixed-voidmydisplay()-voidmymouse(GLintbutton,GLintstate,GLintx,GLin
ty)•Mustuseglobalstopassinformationtocallbacks21floatt;/*global*/voidmydisplay(){/*drawsomethingthatdependsont}GL
UTDisplayEventTrigger:GLUTdeterminesthatthewindowneedstoberedisplayed.Adisplayeventisgeneratedwhenthewindo
wisfirstdrawn.Callbackfunctionform:voiddisplay();Registration:glutDisplayFunc(display);ThedisplaycallbackisexecutedwheneverGLUTdeterminesthatthew
indowshouldberefreshed,forexampleWhenthewindowisfirstopenedWhenthewindowisreshapedWhenawindowisexposedWhentheuserprogramdecid
esitwantstochangethedisplay23Postingredisplays•Manyeventsmayinvokethedisplaycallbackfunction-Canlead
tomultipleexecutionsofthedisplaycallbackonasinglepassthroughtheeventloop•WecanavoidthisproblembyinsteadusingglutPostRedisplay();whichsetsaf
lag.•GLUTcheckstoseeiftheflagissetattheendoftheeventloop•Ifsetthenthedisplaycallbackfunctionisexecuted24AnimatingaDisplay•Whenwe
redrawthedisplaythroughthedisplaycallback,weusuallystartbyclearingthewindow-glClear()thendrawthealtereddisplay•Problem:thedrawingofinformationinthef
ramebufferisdecoupledfromthedisplayofitscontents-Graphicssystemsusedualportedmemory•Hencewecanseepartiallydrawndisplay-Seetheprograms
ingle_double.cforanexamplewitharotatingcubeGLUTMouseEventTrigger:Anymousebuttonisdepressedorreleased.Callbackfunction
form:voidmouse_callback_func(intbutton,intstate,intx,inty);Registration:glutMouseFunc(mouse_callback_function);GLUTDefi
nedMouseConstantsGLUT_LEFT_BUTTONGLUT_MIDDLE_BUTTONGLUT_RIGHT_BUTTONGLUT_UPGLUT_DOWNSystemswithonlyonemousebuttoncano
nlygenerateaGLUT_LEFT_BUTTONcallback.GLUTReshapeEventTrigger:ActivewindowisresizedCallbackfunctionform:voidreshape_func(GLsizeiw,GLsizeih);Reg
istration:glutReshapeFunc(reshape_func);GLUTMoveEventTrigger:Themouseismovedwhileoneormoremousebuttons
arepressed.Callbackfunctionform:voidmotion_func(intx,inty);Registration:glutMotionFunc(motion_func);GLUTKeyboardEve
ntTrigger:Anykeyisdepressed.Callbackfunctionform:voidkeyboard_function(unsignedcharkey,intx,inty);Registration:glutKeyboardFunc(keyboard_function);
OtherDefinedEventsinGLUTglutPassiveMotionFuncglutVisibilityFuncglutEntryFuncglutSpecialFuncglutSpaceballMotionFuncglutSpaceballRotateFuncglutS
paceballButtonFuncglutButtonBoxFuncglutDialsFuncglutTabletMotionFuncglutTabletButtonFuncglutMenuStatusFuncExample:Simpl
eSquareDrawingProgram•Openawindow.•Clearittoblack.•Drawaboxatlocationofthemouseeachtimetheleftbuttonisclicked.
ColorofboxshouldberandomlyselectedfromRGBspace.•Clearwindowwhenresized.•Quitwhenrightbuttonisclicked.SquarePro
gramSourceCodeSlide1/*ThisprogramillustratestheuseoftheglutlibraryforinterfacingwithaWindowSystem*//*Theprogramopensawindow,clearsittoblack,the
ndrawsaboxatthelocationofthemouseeachtimetheleftbuttonisclicked.TherightbuttonexitstheprogramTheprogramalsoreactscorrectlywhen
thewindowismovedorresizedbyclearingthenewwindowtoblack*/#include<GL/gl.h>#include<GL/glut.h>/*globals*/GLsizeiwh=500,ww=500;/*initialwindowsize
*/GLfloatsize=3.0;/*halfsidelengthofsquare*/SquareProgramSourceCodeSlide2voiddrawSquare(intx,inty){y=wh-y;glColor3f((char)random()%256,
(char)random()%256,(char)random()%256);glBegin(GL_POLYGON);glVertex2f(x+size,y+size);glVertex2f(x-size,y+size);glVertex2f(x-s
ize,y-size);glVertex2f(x+size,y-size);glEnd();glFlush();}SquareProgramSourceCodeSlide3voidmyReshape(GLsizeiw,GLsizeih){/*adjust
clippingbox*/glMatrixMode(GL_PROJECTION);glLoadIdentity();glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,-1.0,1.0);
glMatrixMode(GL_MODELVIEW);glLoadIdentity();/*adjustviewportandclear*/glViewport(0,0,w,h);glClearColor(0.0,0.0
,0.0,0.0);glClear(GL_COLOR_BUFFER_BIT);glFlush();/*setglobalsizeforusebydrawingroutine*/ww=w;wh=h;}SquareProgramSourceCodeSlide4voidmyinit(void){gl
Viewport(0,0,ww,wh);/*Pick2DclippingwindowtomatchsizeofscreenwindowThischoiceavoidshavingtoscaleobjectcoordi
nateseachtimewindowisresized*/glMatrixMode(GL_PROJECTION);glLoadIdentity();glOrtho(0.0,(GLdouble)ww,0.0,(GLdouble)wh,-1.0,
1.0);/*setclearcolortoblackandclearwindow*/glClearColor(0.0,0.0,0.0,0.0);glClear(GL_COLOR_BUFFER_BIT);glF
lush();/*callbackroutineforreshapeevent*/glutReshapeFunc(myReshape);}SquareProgramSourceCodeSlide5voidmouse(intbtn,intstate,intx,inty){if(btn==GLUT_R
IGHT_BUTTON&state==GLUT_DOWN)exit();}intmain(intargc,char**argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glut
CreateWindow("square");myinit();glutReshapeFunc(myReshape);glutMouseFunc(mouse);glutMotionFunc(drawSquare);glutMainLoop();}Outputof“Square”p
rogramImplementingChoice:MenusinGLUT•Foursteps:-Createmenu:glutCreateMenu(menu);-Definemenuentries:glutAddMenuEntry-Attachmenutoamou
sebutton:gluAttachMenu-Definecallbackfunction:voidmenu(intid);CreatingaMenuinGLUTintglutCreateMenu(void(*func)(intvalue));Create
sanewpop-upmenu.Returnsauniqueintegeridentifierforthemenu.Takesasargumentapointertoasinglecallbackfunctionthattakesanintegerargumen
t.Theintegerargumentofthecallbackismappedtothemenuchoice.Setsthecurrentmenutothenewlycreatedmenu.MenuIdentifierCall
backFunctionChoiceAssociatingaMenuwithaMouseKeyvoidglutAttachMenu(intbutton);Associatestheselectedbuttonwiththecurrentmenu.buttonisselectedfr
omtheGLUTdefinedbuttonconstants:GLUT_LEFT_BUTTON,GLUT_MIDDLE_BUTTON,GLUT_RIGHT_BUTTONAddingEntriestotheMenuvoidglutAddMenuE
ntry(char*name,intvalue);Stringtoappearinmenuentry.Valuetobepassedtocallbackfunction.Addsamenuentrytothebottomofthecurrentmenu.Buildinga
Sub-menuvoidglutAddSubMenu(char*name,intmenu);Stringtodisplayinthemenuitemfromwhichtocascadesub-menu.Identifierofmenutocascadefro
mthissub-menuitem.DoubleBuffering•Insteadofonecolorbuffer,weusetwo-FrontBuffer:onethatisdisplayedbutnotwrittento-BackBuffer:onethatiswrittentobutnotd
isplayed•Programthenrequestsadoublebufferinmain.c-glutInitDisplayMode(GL_RGB|GL_DOUBLE)-Attheendofthedisplay
callbackbuffersareswapped43voidmydisplay(){glClear(GL_COLOR_BUFFER_BIT|….)./*drawgraphicshere*/.glutSwapBuffers()}44Usingt
heidlecallback•Theidlecallbackisexecutedwhenevertherearenoeventsintheeventqueue-glutIdleFunc(myidle)-Usefulforanimationsv
oidmyidle(){/*changesomething*/t+=dtglutPostRedisplay();}Voidmydisplay(){glClear();/*drawsomethingthatdependsont*/glutSwapBuffers();}45Usingglo
bals•TheformofallGLUTcallbacksisfixed-voidmydisplay()-voidmymouse(GLintbutton,GLintstate,GLintx,GLinty)•Mustuseglobalstopassinforma
tiontocallbacksfloatt;/*global*/voidmydisplay(){/*drawsomethingthatdependsont}