Vous êtes sur la page 1sur 4

8/5/13

openFrameworks

VectorMaths
2012/02/2310:00:00KeithPasko

Movingthroughspacerequiresknowledgeofwherethingsareandwheretheyaregoing.VectorMathsistheclassof mathematicsthatgivesusunderstandingcontroloverthesethingsinspace,allowingforelegant,intuitive,andgeneral descriptionsofcomplexstructuresandmovement.Vectorsareattheheartofanimation,particlesystems,and3dgraphicsin fact,vectormaths/linearalgebrahavemademuchofmoderncomputersciencepossible. Let'sjumpintosometechnicaldetailsShhhhh,hushnow,itwillallbeoversoonenough.Avectorrepresentsadirectionand magnitudeinanabstract"space"forourcurrentpurposes,wecanjustthinkofthis"space"asthecommon2dor3dworld.In theseworlds,wehavestandard"basisvectors"andanorigineverythingelseintheworldiscreatedfromthesefundamentals. For3d,thestandardoriginis(0,0,0),andstandardbases[1,0,0],[0,1,0],[0,0,1](itisthesamefor2d,butwithoutthe3rd component,i.e.[0,0]origin,[1,0],[0,1]bases).Toputaperhapsmorefamiliarnametothese,wecancallthemthex,y,andz directions.Theallowedoperationsonthesevectorsareadditionandscalarmultiplicationwiththese,wecangenerateany vectorinspace.

Vectoroperations

scalarmultiplication
Let'ssaywewanttogo3.14units"totheright"("alongx","alongthefirstbasis").Wemultiplybycomponent,sotheresultis[1* 3.14,0*3.14,0*3.14]=[3.14,0,0].Similarly,ifwewanttogo"up"("alongy","alongthesecondbasis")by1.71,wehave[0,1,0] *1.71=[1*1.71,0*1.71,0*1.71]=[0,1.71,0].Wecanseethatmultiplyingbyascalar,fittingly,scalesthevector,keepingthe directionthesame(orreversingit,ifthescalarisnegative).

InOF,thiscanbedonewiththe*operatororwithscale/getScaled: 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 o f V e c 3 f v ( 1 , 2 , 3 ) ; r e t u r n v * 3 . 1 4 ; / / r e t u r n s o f V e c 3 f ( 3 . 1 4 , 6 . 2 8 , 9 . 4 2 ) ; r e t u r n v . g e t S c a l e d ( 3 . 1 4 ) ; / / a l s o r e t u r n s o f V e c 3 f ( 3 . 1 4 , 6 . 2 8 , 9 . 4 2 ) ; v . s c a l e ( 3 . 1 4 ) ; / / i n t e r n a l l y s c a l e s v t o o f V e c 3 f ( 3 . 1 4 , 6 . 2 8 , 9 . 4 2 ) ; / / w o r k s w i t h v e c 2 f a n d v e c 4 f a s w e l l o f V e c 2 f v ( 0 , 1 ) ; r e t u r n v * 2 . 7 1 8 ; / / r e t u r n s o f V e c 3 f ( 0 , 2 . 7 1 8 , 0 ) ; o f V e c 4 f v ( 0 , 1 , 4 , 3 ) ; r e t u r n v * 2 . 7 1 8 ; / / r e t u r n s o f V e c 4 f ( 0 , 2 . 7 1 8 , 1 0 . 8 7 2 , 8 . 1 5 4 ) ; / / n o t e t h e r e i s a l s o a * o p e r a t o r w h i c h i s N O T s c a l a r m u l t i p l i c a t i o n o f V e c 3 f v 1 ( 1 , 2 , 3 ) ; o f V e c 3 f v 2 ( 2 , 3 , 4 ) ; r e t u r n v 1 * v 2 ; / / r e t u r n s o f V e c 3 f ( 2 , 6 , 1 2 ) ; / / t h i s i s c o m p o n e n t w i s e m u l t i p l i c a t i o n b e t w e e n t w o v e c t o r s , a n d i s f a r l e s s c o m m o n t h a n s c a l a r m u l t i p l i c a t i o n

TheOFreferencecanbefoundhere

addition
Nowlet'ssaywewanttogo3.14unitstotheright,andthen1.71unitsupwecanaddthetwovectorswe'vejustcreated

www.openframeworks.cc/tutorials/maths/001_vector_maths.html

1/4

8/5/13

openFrameworks
[3.14,0,0]+[0,1.71,0]=[3.14+0,0+1.71,0+0]=[3.14,1.71,0].Thisiscalled"componentwiseaddition",aswejustaddthe differentcomponentsofeachvector(i.e.x+x,y+y,z+z).Thiscanbevisualizedbyputtingonevectoratthetipoftheother vector

1 2 3

o f V e c 3 f v 1 ( 3 . 1 4 , 0 , 0 ) ; o f V e c 3 f v 2 ( 0 , 1 . 7 1 , 0 ) ; r e t u r n v 1 + v 2 ; / / r e t u r n s o f V e c 3 f ( 3 . 1 4 , 1 . 7 1 , 0 ) ;

TheOFreferencecanbefoundhere

application
Whocares?Howisthisuseful?Let'stakeasimpleexamplewehavetwopointsaandbinspace,andwewanttomovefrom onetotheother.Rememberthatadditionislikeputtingavectoratthetipofanothervector?Well,weknowthatifweaddthe directionfromatob(we'llcallitc)toa,we'llgetb:a+c=b.Thevectorwe'relookingforisc=ba.

Great,nowweknowthedirectionfromatob(c=ba).Again,thismeansthatifweaddctothetipofa,we'llendupatb.Ifwe multiplycbyvariousnumbersbetween0and1,wecanprogressivelymovefromatob.

Pippip,nowwecanshootparticlesfromonepositiontoanotherwitheaseusingournewvectormaths.Alloftheseoperations andconceptsworkexactlythesamewayin3dtogofromonepointtoanotherin3d,weonceagaindoa+delta*(ba)nothing elseneeded!

www.openframeworks.cc/tutorials/maths/001_vector_maths.html

2/4

8/5/13

openFrameworks

Otherhelpfuloperations

length/normalization
Thelengthofavectoristhesquarerootofthesumofthesquaresofthecomponents.Huh?Inperhapslessobscureterms, length(x,y,...)=sqrt(x x+y y+...)e.gthelengthofavector(3,4)=sqrt(33+44)=sqrt(25)=5.Rememberour"aim"example, goingfromatob?Well,nowweknowhowfarapartinspaceaandbarethelengthofc(ba),informationcrucialfor simulations,amongmanyothergraphicsapplications.Thelengthofavectorisoftendenotedby|v|or||v||ifyouseethisonthe wikipediazsomewhere,nowyouknowwhatitmeans. Normalizationistheconceptofdividingavectorbyitslength,turningitintoa"unitvector",orvectorpointedinthesame direction,butwithalengthof1thismakessurethatthelengthofthevectordoesn't"contaminate"anyoperationsonit.Imagine ifourbasisvectorfromthefirstexamplewasn'tnormalizedsay(1,0,0)was(25504.77707,0,0),then3.14*basis1=(80085,0,0), whichisabitcounterintuitive(itsmorenaturaltothinkthatthevector(3.14,0,0)actuallygoes3.14unitsinthexdirection,not 80085units).Nowwhenweseev/|v|,weknowitisthenormalizedvectorinthevdirectionholla. 1 2 3 o f V e c 3 f v 1 ( 3 . 1 4 , 9 . 1 1 , 1 . 2 3 4 ) ; r e t u r n v 1 . l e n g t h ( ) ; / / r e t u r n s s q r t ( 3 . 1 4 * 3 . 1 4 + 9 . 1 1 * 9 . 1 1 + 1 . 2 3 4 * 1 . 2 3 4 ) = 9 . 7 1 4 6 5 v 1 . n o r m a l i z e ( ) ; r e t u r n v 1 . l e n g t h ( ) ; / / r e t u r n s 1 .

dotproduct/projection/reflection
Thedotproductcanbeaconfusingthing.Inkeepingwiththesomewhatanalretentivenatureofthistutorial,let'sjuststartwitha definitionthedotproductofaandb[letscallitdot(a,b)]=|a||b|cos(theta),wherethetaistheanglebetweenthetwovectors, and|a|and|b|arethelengthsofaandb,asdescribedinthelastsection.Great,butwhyisthatuseful?Well,firstofall,it enablesustofindtheanglebetweenanytwovectorsinanydimension(2d,3d,...10d?)sincedot(a,b)=|a||b|cos(theta),theta, theanglebetweenthevectors,isequaltoacos(dot(a,b)/|a|*|b|)(amotivationforlearningnormalizing,asitquitesimplifiesthis calculation...ifaandbareunitvectors,thisisjustacos(dot(a,b))). Ifyoudon'tcareexactlywhattheangleitselfbetweenthemisandjustcareaboutthecosine(andagainassumeaandbare normalized)thendot(a,b)=cos(theta),quitetidy.Whywouldwecareaboutthecosineonly?Recallthatthecosineispositive whenthetaisbetweenpi/2(90deg)andpi/2(90deg),sothedotproductisthemeasureofhowmuchthevectorsarepointing "inthesamedirection"toacertainextent.Ifthreshold<=dot(a,b)<=1.,thismeansthatthevectorsarepointinginroughlythe samedirection,withinthethreshold.Ifdot(a,b)isnegative,theyareindifferentdirections(morethan90degapart)inthe extreme(1),theyarefacingexactlyopposite.Asaconcreteexample,diffuselightingusesthedotproducttodetermine illuminationofaface,asitisrelatedtohowmuchthefacedirection(normal)anddirectionfromfacetolightarealigned.

Asyoucanseefromthediagram,wecanusethedotproducttocomputetheprojectionofonevectorontotheotheritisjust |b|dot(a,|b|).Wecanalsofindthesmallestdistancefromavectoratoavectorb,sinceitiseinthediagram,theperpendicular projection.Wecanevencomputethereflectionofavectoracrossanother,sinceitisde(=2da,or2|b|dot(a,|b|)a).The beautyofthisforulationisthatthisabstractstomultipledimensionsifyouwanttofindtheprojectionofavectoronaplane,you projectontothefirstbasis,projectontothesecondbasis,andadd.Allthiscomesfromjusttheinnocentlookingdotproduct. InOF,ourveryhandydotproductisjustthemethod"dot" 1 2 3 o f V e c 3 f v 1 ( 1 , 2 , 3 ) ; o f V e c 3 f v 2 ( 4 , 5 , 6 ) ; r e t u r n v 1 . d o t ( v 2 ) ; / / r e t u r n s 1 * 4 + 2 * 5 + 3 * 6 = 3 2 ;

OFreferencecanbefoundhere

hardcorenerdingactionforthemath-minded

www.openframeworks.cc/tutorials/maths/001_vector_maths.html

3/4

8/5/13

openFrameworks
Forthehardcore,our"space"isavectorspace,whichmustbe"closedunderadditionandscalarmultiplication,"whichisthe fancywayofsayingthatallcombinationsofadditionandscalarmultiplicationarealsovectorsinthatsamespace.Thestandard basesareusuallyreferredtoby"e",iee1,e2,e3,etcwealsonotethatwearemostoftendiscussinganorthonormalbasis, whichmeansthate1,e2,ande3allhavelength1,andareeachat90degreestooneanother.Inthedifferenceexample,ifwe assumeaandbarealongapath,thencisoneapproximationofthepathtangent.**Beforetheubernerdsoutthereslapmy handforbeingincomplete,thereareafewothertechnicalrequirementstobeavectorspacethesecanbefoundhere http://en.wikipedia.org/wiki/Vector_space.Thedotproductisalsocalledtheinnerproduct,andwithlengthandthisinnnerproduct defined,wegetan"innerproductspace".Inlinearalgebraterms,thisinnerproductisdescribedbytransposingtheobjectand multiplyinge.g.dot(a,b)=a(transpose)*bthesquarelengthofavectorisoftenwrittenasv(transpose)*v.Projectionontoa subspacerepresentedbyamatrixissimilar,A(transpose)*A*x(whereAcouldrepresentthebasisvectorsofaplane,for example).

www.openframeworks.cc/tutorials/maths/001_vector_maths.html

4/4

Vous aimerez peut-être aussi