【文档说明】计算机图形学computer-graphics课件7.ppt,共(45)页,1.108 MB,由小橙橙上传
转载请保留链接:https://www.ichengzhen.cn/view-77496.html
以下为本文档部分文字说明:
InputandInteractionYuanfengZhouShandongUniversitySoftwareCollege1Objectives•Introducethebasicinputdevices-PhysicalDevices-LogicalDev
ices-InputModes•Event-driveninput•Introducedoublebufferingforsmoothanimations•ProgrammingeventinputwithGLU
T2ProjectSketchpad•IvanSutherland(MIT1963)establishedthebasicinteractiveparadigmthatcharacterizesinteractivecomputergraphics:-Use
rseesanobjectonthedisplay-Userpointsto(picks)theobjectwithaninputdevice(lightpen,mouse,trackball)-Objectchanges(moves,rotates,morphs)-Rep
eat3InteractionwithGraphicsSystem4ChangeImageReacttoChangeGraphicsSystemUserInputDeviceDisplayGraphic
alInput•Devicescanbedescribedeitherby-Physicalproperties•Mouse•Keyboard•Trackball(Thinkpad)-Logicalproperties•WhatisreturnedtoprogramviaAPI(Appl
icationProgrammingInterface)–Aposition–Anobjectidentifier•Modes-Howandwheninputisobtained•Requestorevent5LogicalProperties6Applica
tionModelApplicationProgramGraphicsSystemOutputDevicesInputDevicesAPIFunctionCallsorProtocolDataWM_LBUTTONDOWN#defineON_BN_LBUTTONDOWN(id,memberFxn)v
oidCMyProgram::OnLButtonDown(UINTnFlags,CPointpoint){processingcode…CButton::OnLButtonDown(nFlags,point);}PhysicalDevices7mousetrackballligh
tpendatatabletjoystickspaceballLogicalDevices•ConsidertheCandC++code-C++:cin>>x;-C:scanf(“%d”,&x);•Whatist
heinputdevice?-Can’ttellfromthecode-Couldbekeyboard,file,outputfromanotherprogram•Thecodeprovideslogicalinput-Anumb
er(anint)isreturnedtotheprogramregardlessofthephysicaldevice8GraphicalLogicalDevices•Graphicalinputismorevariedthaninputtostandardprogramswhichisusu
allynumbers,characters,orbits•TwoolderAPIs(GKS77’,PHIGS90’)definedsixtypesoflogicalinput:-Locator:returnaposition-Pick:returnIDofanobject-K
eyboard:returnstringsofcharacters-Stroke:returnarrayofpositions-Valuator:returnfloatingpointnumber-Choice:returnoneofnitems910XWindowI
nput•TheXWindowSystemintroducedaclient-servermodelforanetworkofworkstations-Client:OpenGLprogram-GraphicsServer:bitmapdisplaywithapointingde
viceandakeyboardDisplayListinOpenGL•Matrixcomputation•Imagedisplay•Light,material•Texture•Polygonalobjectsdisplay11D
isplayListinOpenGL•voidglNewList(GLuintlist,GLenummode);•mode:GL_COMPILEandGL_COMPILE_AND_EXECUTE•voidglEndList(void);•NOTincludedinDisplayList:•glD
eleteLists()glIsEnable()•glFeedbackBuffer()glIsList()•glFinish()glPixelStore()•glGenLists()glRenderMode()•glGet*()glSelec
tBuffer()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_BIT);glColor3
f(0.0,1.0,0.0);glPushMatrix();for(i=0;i<5;i++)glCallList(listName);drawLine();glPopMatrix();glFlush();}InputMo
de•Inputdevicescontainatriggerwhichcanbeusedtosendasignaltotheoperatingsystem-Buttononmouse-Pressingorreleasingakey•Whentriggered
,inputdevicesreturninformation(theirmeasure)tothesystem-Mousereturnspositioninformation-KeyboardreturnsASCIIcode14RequestMode•Inputprovided
toprogramonlywhenusertriggersthedevice•Typicalofkeyboardinput-Canerase(backspace),edit,correctuntilenter(return)key(the
trigger)isdepressed151.Programrequestsmeasureofadeviceandblocks.2.Measureprocessmaintainscurrentmeasure.3.Triggerprocesssign
alsmeasureprocesstoreturnmeasure.request_locator(device_id,&measure);EventMode•Mostsystemshavemorethanoneinputdevice,eachofwhichcanbetrigg
eredatanarbitrarytimebyauser•Eachtriggergeneratesaneventwhosemeasureisputinaneventqueuewhichcanbeexaminedby
theuserprogram16glutMainLoop();EventTypes•Window:resize,expose,iconify•Mouse:clickoneormorebuttons•Motion:mov
emouse•Keyboard:pressorreleaseakey•Idle:nonevent-Definewhatshouldbedoneifnoothereventisinqueue17Callbacks•Programminginte
rfaceforevent-driveninput•Defineacallbackfunctionforeachtypeofeventthegraphicssystemrecognizes•Thisuser-suppliedf
unctionisexecutedwhentheeventoccurs•GLUTexample:glutMouseFunc(mymouse)18mousecallbackfunction19GLUTcallbacksGLUTrecognizesasubsetoft
heeventsrecognizedbyanyparticularwindowsystem(Windows,X,Macintosh)-glutDisplayFunc-glutMouseFunc-glutReshapeFunc-glutKeyboardF
unc-glutIdleFunc-glutMotionFunc-glutPassiveMotionFuncGLUTEventLoop•Recallthatthelastlineinmain.cforaprogramusingGLUTmustbeglutMainLoop();whi
chputstheprograminaninfiniteeventloop•Ineachpassthroughtheeventloop,GLUT-looksattheeventsinthequeue-foreacheventinthequ
eue,GLUTexecutestheappropriatecallbackfunctionifoneisdefined-ifnocallbackisdefinedfortheevent,theeventisignored20Usinggloba
ls•TheformofallGLUTcallbacksisfixed-voidmydisplay()-voidmymouse(GLintbutton,GLintstate,GLintx,GLinty)•Mustuseglo
balstopassinformationtocallbacks21floatt;/*global*/voidmydisplay(){/*drawsomethingthatdependsont}GLUTD
isplayEventTrigger:GLUTdeterminesthatthewindowneedstoberedisplayed.Adisplayeventisgeneratedwhenthewindowisfirstdrawn.Callbackfunctio
nform:voiddisplay();Registration:glutDisplayFunc(display);ThedisplaycallbackisexecutedwheneverGLUTdeterminesthatthewindowshouldberefreshed,forexa
mpleWhenthewindowisfirstopenedWhenthewindowisreshapedWhenawindowisexposedWhentheuserprogramdecidesitwantstochangethedisplay23
Postingredisplays•Manyeventsmayinvokethedisplaycallbackfunction-Canleadtomultipleexecutionsofthedisplaycallbackonasinglepassthroughtheeventloop•We
canavoidthisproblembyinsteadusingglutPostRedisplay();whichsetsaflag.•GLUTcheckstoseeiftheflagissetat
theendoftheeventloop•Ifsetthenthedisplaycallbackfunctionisexecuted24AnimatingaDisplay•Whenweredrawthedisplaythroughthedisplaycallback,weus
uallystartbyclearingthewindow-glClear()thendrawthealtereddisplay•Problem:thedrawingofinformationintheframebufferisdecoupledfromthedisplayofitscontent
s-Graphicssystemsusedualportedmemory•Hencewecanseepartiallydrawndisplay-Seetheprogramsingle_double.cforan
examplewitharotatingcubeGLUTMouseEventTrigger:Anymousebuttonisdepressedorreleased.Callbackfunctionform:voidmouse_callback_func(intbutton,int
state,intx,inty);Registration:glutMouseFunc(mouse_callback_function);GLUTDefinedMouseConstantsGLUT_LEFT_BU
TTONGLUT_MIDDLE_BUTTONGLUT_RIGHT_BUTTONGLUT_UPGLUT_DOWNSystemswithonlyonemousebuttoncanonlygenerateaGLUT_LEFT_BUTTONcallback.GLUTReshapeEventTrigger
:ActivewindowisresizedCallbackfunctionform:voidreshape_func(GLsizeiw,GLsizeih);Registration:glutReshapeFunc(reshape_func);GLUTMoveEventTrigge
r:Themouseismovedwhileoneormoremousebuttonsarepressed.Callbackfunctionform:voidmotion_func(intx,inty);Registration:glutMotionFunc(motio
n_func);GLUTKeyboardEventTrigger:Anykeyisdepressed.Callbackfunctionform:voidkeyboard_function(unsignedcharkey,intx,inty);Registration:
glutKeyboardFunc(keyboard_function);OtherDefinedEventsinGLUTglutPassiveMotionFuncglutVisibilityFuncglutEntryFuncglutSpecialFuncglutSpacebal
lMotionFuncglutSpaceballRotateFuncglutSpaceballButtonFuncglutButtonBoxFuncglutDialsFuncglutTabletMotionFuncglutTabletButtonFuncglutMenuStatusFuncExa
mple:SimpleSquareDrawingProgram•Openawindow.•Clearittoblack.•Drawaboxatlocationofthemouseeachtimetheleftbuttoniscl
icked.ColorofboxshouldberandomlyselectedfromRGBspace.•Clearwindowwhenresized.•Quitwhenrightbuttonisclicked.SquarePr
ogramSourceCodeSlide1/*ThisprogramillustratestheuseoftheglutlibraryforinterfacingwithaWindowSystem*//*Theprogramo
pensawindow,clearsittoblack,thendrawsaboxatthelocationofthemouseeachtimetheleftbuttonisclicked.TherightbuttonexitstheprogramThe
programalsoreactscorrectlywhenthewindowismovedorresizedbyclearingthenewwindowtoblack*/#include<GL/gl.h>#include<GL/glut.h>/*global
s*/GLsizeiwh=500,ww=500;/*initialwindowsize*/GLfloatsize=3.0;/*halfsidelengthofsquare*/SquareProgramSour
ceCodeSlide2voiddrawSquare(intx,inty){y=wh-y;glColor3f((char)random()%256,(char)random()%256,(char)random()%256);glBegin(GL_POLY
GON);glVertex2f(x+size,y+size);glVertex2f(x-size,y+size);glVertex2f(x-size,y-size);glVertex2f(x+size,y-size);glEnd();glFlush();}Squa
reProgramSourceCodeSlide3voidmyReshape(GLsizeiw,GLsizeih){/*adjustclippingbox*/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);glClear
Color(0.0,0.0,0.0,0.0);glClear(GL_COLOR_BUFFER_BIT);glFlush();/*setglobalsizeforusebydrawingroutine*/ww=w;wh=h;}SquareProgramSourceCodeSlide4voi
dmyinit(void){glViewport(0,0,ww,wh);/*Pick2DclippingwindowtomatchsizeofscreenwindowThischoiceavoidshavingtoscaleobjectcoordinateseac
htimewindowisresized*/glMatrixMode(GL_PROJECTION);glLoadIdentity();glOrtho(0.0,(GLdouble)ww,0.0,(GLdouble)wh,-1.0,1.0);/*setclearcolortoblackan
dclearwindow*/glClearColor(0.0,0.0,0.0,0.0);glClear(GL_COLOR_BUFFER_BIT);glFlush();/*callbackroutineforreshapeevent*/glutRe
shapeFunc(myReshape);}SquareProgramSourceCodeSlide5voidmouse(intbtn,intstate,intx,inty){if(btn==GLUT_RIGHT_BUTTO
N&state==GLUT_DOWN)exit();}intmain(intargc,char**argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutCreateWindow
("square");myinit();glutReshapeFunc(myReshape);glutMouseFunc(mouse);glutMotionFunc(drawSquare);glutMainLoop();}Outputof“Square”programImplementing
Choice:MenusinGLUT•Foursteps:-Createmenu:glutCreateMenu(menu);-Definemenuentries:glutAddMenuEntry-Attachmenutoamousebutton:gluAttachMenu-Definec
allbackfunction:voidmenu(intid);CreatingaMenuinGLUTintglutCreateMenu(void(*func)(intvalue));Createsanewpop-u
pmenu.Returnsauniqueintegeridentifierforthemenu.Takesasargumentapointertoasinglecallbackfunctionthattakesanintegerargument.Theintege
rargumentofthecallbackismappedtothemenuchoice.Setsthecurrentmenutothenewlycreatedmenu.MenuIdentifierCallbackFuncti
onChoiceAssociatingaMenuwithaMouseKeyvoidglutAttachMenu(intbutton);Associatestheselectedbuttonwiththecurrentmenu.buttonisselectedfromtheGLUTdefin
edbuttonconstants:GLUT_LEFT_BUTTON,GLUT_MIDDLE_BUTTON,GLUT_RIGHT_BUTTONAddingEntriestotheMenuvoidglutAddMenuEntry(char*name,intvalue);
Stringtoappearinmenuentry.Valuetobepassedtocallbackfunction.Addsamenuentrytothebottomofthecurrentmenu.BuildingaSub-menuvoidglutAddS
ubMenu(char*name,intmenu);Stringtodisplayinthemenuitemfromwhichtocascadesub-menu.Identifierofmenutocas
cadefromthissub-menuitem.DoubleBuffering•Insteadofonecolorbuffer,weusetwo-FrontBuffer:onethatisdispl
ayedbutnotwrittento-BackBuffer:onethatiswrittentobutnotdisplayed•Programthenrequestsadoublebufferinmain.c-glutInitDisplay
Mode(GL_RGB|GL_DOUBLE)-Attheendofthedisplaycallbackbuffersareswapped43voidmydisplay(){glClear(GL_COLOR_BUFFER_BIT|….)./*drawgraphicshere*/.glutSwa
pBuffers()}44Usingtheidlecallback•Theidlecallbackisexecutedwhenevertherearenoeventsintheeventqueue-glutIdleFunc(myi
dle)-Usefulforanimationsvoidmyidle(){/*changesomething*/t+=dtglutPostRedisplay();}Voidmydisplay(){glClear();/*dra
wsomethingthatdependsont*/glutSwapBuffers();}45Usingglobals•TheformofallGLUTcallbacksisfixed-voidmydisplay()-voi
dmymouse(GLintbutton,GLintstate,GLintx,GLinty)•Mustuseglobalstopassinformationtocallbacksfloatt;/*global*/voidmydisplay(){/*drawsomethingthatdepend
sont}