Tải bản đầy đủ - 0 (trang)
Chapter 15.  A 3D Checkerboard: Checkers3D

Chapter 15.  A 3D Checkerboard: Checkers3D

Tải bản đầy đủ - 0trang

mustbeintegratedwithJava'sSwingcomponents.AllJava3D

applicationsrequireascenegraph,andCheckers3Dshowshowto

addbasicshapes,lighting(ambientanddirectional),anda

background.Thescenegraphdiagramactsasavisualformof

documentation,andatextualversionofitsinformationcanbe

generatedeasily,withthehelpofDanielSelman'sJava3dTree

package.(I'llsupplydetailsattheendofthischapter).

ThefloorandsphereutilizeJava3D'sQuadArray,Text2D,andSphere

geometryclasses:thefloorisaseriesofquadrilateralsina

QuadArray,andlabelsareplacedalongthemainaxesofthefloor

usingText2Dobjects.Thesphereshowshowa3Dshapeis

colored,lit,andpositionedinspace.Theuserlooksintothe3D

worldfromaviewpoint.You'llseehowitcanbeinitially

positioned,andhowitcanbemovedduringexecutionbyusing

Java3D'sOrbitBehaviorclass.



ClassDiagramsforCheckers3D

TheclassdiagramsinFigure15-2showallthepublicand

privatedataandmethodsfortheCheckers3Dapplication.



Figure15-2.ClassdiagramsforCheckers3D



Checkers3Disthetop-levelJFramefortheapplication.WrapCheckers3D



isaJPanelholdingthescenegraph,whichisviewableviaa

Canvas3Dobject.CheckerFloorcreatesthesubgraphforthefloor

(e.g.,tiles,axes,etc.),withallthesamecoloredtiles

representedbyasingleColoredTilesobject.



ThesourcecodeforthisexampleisintheCheckers3D/directory.



IntegratingJava3DandSwing

Checkers3DisaJFramewhereGUIcontrols,suchasSwingtext



fieldsandbuttons,wouldbeplacedifnecessary.Inthis

example,itcreatesaninstanceofWrapCheckers3D(aJPanel)and

placesitinthecenterofaBorderLayout:



c.setLayout(newBorderLayout());

WrapCheckers3Dw3d=newWrapCheckers3D();//panelfor

c.add(w3d,BorderLayout.CENTER);



TheCanvas3DviewontothesceneiscreatedinsideWrapCheckers3D:

publicWrapCheckers3D()

{

setLayout(newBorderLayout());

//otherinitializationcode

GraphicsConfigurationconfig=

SimpleUniverse.getPreferredConfiguration();

Canvas3Dcanvas3D=newCanvas3D(config);

add("Center",canvas3D);

//otherinitializationcode}



SomecaremustbetakenwhenusingCanvas3Dsinceit'sa

heavyweightGUIelement(athinlayeroveranOS-generated

window).Heavyweightcomponentsaren'teasilycombinedwith

Swingcontrols,whicharelightweight;thecontrolsaremostly

generatedbyJava.ProblemsareavoidediftheCanvas3Dobjectis

embeddedinaJPanel;thenthepanelcanbesafelyintegrated

withtherestoftheSwing-builtapplication.



There'sadetaileddiscussionoftheissuesrelatedtocombiningCanvas3D

andSwingatj3d.org

(http://www.j3d.org/tutorials/quick_fix/swing.html).



Comparedtoapplicationsinearlierchapters,there'sno

update/drawanimationloop.ThisisunnecessarybecauseJava

3Dcontainsitsownmechanismformonitoringchangesinthe

sceneandinitiatingrendering.Hereisthealgorithmin

pseudocodeform:

while(true){

processuserinput;

if(exitrequest)break;

performbehaviors;

if(scenegraphhaschanged)

traversescenegraphandrender;

}



Behaviorsarescenegraphnodescontainingcodethatcan

influenceotherpartsofthegraph,suchasmovingshapesor

changingthelighting.Theymaybeusedformonitoringthe

graph,passingdetailstothenon-3Dpartsoftheapplication.

Thedetailsaremorecomplicatedthanthispseudocode

suggestsforexample,Java3Dusesmultithreadingtocarryout

paralleltraversalandrendering.However,havingageneralidea

oftheprocesswillhelpyouworkthroughthecodeintherestof

thischapter.



SceneGraphCreation

ThescenegraphiscreatedbytheconstructorforWrapCheckers3D:

publicWrapCheckers3D()

{

//initializationcode



GraphicsConfigurationconfig=

SimpleUniverse.getPreferredConfiguration();

Canvas3Dcanvas3D=newCanvas3D(config);

add("Center",canvas3D);

canvas3D.setFocusable(true);//givefocustothecan

canvas3D.requestFocus();

su=newSimpleUniverse(canvas3D);





createSceneGraph();

initUserPosition();//setuser'sviewpoint

orbitControls(canvas3D);//controlsformovingthevie

su.addBranchGraph(sceneBG);

}



TheCanvas3Dobjectisinitializedwithaconfigurationobtained

fromgetPreferredConfiguration();thismethodqueriesthe

hardwareforrenderinginformation.SomeolderJava3D

programsdon'tbotherinitializingaGraphicsConfigurationobject,

usingnullastheargumenttotheCanvas3Dconstructorinstead.

Thisisbadprogrammingpractice.

canvas3Disgivenfocussokeyboardeventswillbesentto



behaviorsinthescenegraph.Behaviorsareoftentriggeredby



keypressesandreleases,buttheymaybetriggeredbytimers,

framechanges,andeventsgeneratedbyJava3Dinternally.

Therearen'tanybehaviorsinCheckers3D,soit'snotnecessaryto

setthefocus.I'velefttheselinesinsincethey'reneededin

almosteveryotherprogramwe'llconsider.

ThesuSimpleUniverseobjectcreatesastandardviewbranch

graphandtheVirtualUniverseandLocalenodesofthescene

graph.createSceneGraph()setsupthelighting,thesky

background,thefloor,andfloatingsphere;initUserPosition()

andorbitControls()handleviewerissues.Theresulting

BranchGroupisaddedtothescenegraphattheendofthe

method:



privatevoidcreateSceneGraph()

{

sceneBG=newBranchGroup();

bounds=newBoundingSphere(newPoint3d(0,0,0),BOUNDSIZE



lightScene();//addthelights

addBackground();//addthesky

sceneBG.addChild(newCheckerFloor().getBG());//add

floatingSphere();//addthefloatingsphere

sceneBG.compile();//fixthescene

}//endofcreateSceneGraph()



VariousmethodsaddsubgraphstosceneBGtobuildthecontent

branchgraph.sceneBGiscompiledoncethegraphhasbeen

finalizedtoallowJava3Dtooptimizeit.Theoptimizationsmay

involvereorderingthegraphandregroupingandcombining

nodes.Forexample,achainoftransformGroupnodescontaining

differenttranslationsmaybecombinedintoasinglenode.



Anotherpossibilityistogroupalltheshapeswiththesame

appearancepropertiestogether,sotheycanberenderedmore

quickly.

boundsisaglobalBoundingSphereusedtospecifytheinfluenceof



environmentnodesforlighting,background,andthe

OrbitBehaviorobject.Theboundingsphereisplacedatthecenter

ofthesceneandaffectseverythingwithinaBOUNDSIZEunits

radius.BoundingboxesandpolytopesareavailableinJava3D.

ThescenegraphbytheendofWrapCheckers3D()isshownin

Figure15-3.

The"FloorBranch"nodeismyinventiontohidesomedetails

untillater.MissingfromFigure15-3istheviewbranchpartof

thescenegraph.



LightingtheScene

Oneambientandtwodirectionallightsareaddedtothescene

bylightScene().Anambientlightreacheseverycornerofthe

world,illuminatingeverythingequally.

Color3fwhite=newColor3f(1.0f,1.0f,1.0f);

//Setuptheambientlight

AmbientLightambientLightNode=newAmbientLight(white);

ambientLightNode.setInfluencingBounds(bounds);

sceneBG.addChild(ambientLightNode);



Thecolorofthelightisset,theambientsourceiscreatedalong

withboundsandaddedtothescene.TheColor3f()constructor

takesRed/Green/Bluevaluesbetween0.0fand1.0f(1.0fbeing

"full-on").



Adirectionallightmimicsalightfromadistantsource,hitting

thesurfacesofobjectsfromaspecifieddirection.Themain

differencefromanambientlightistherequirementfora

directionvector.



Vector3flight1Direction=newVector3f(-1.0f,-1.0f,-1.0

//left,down,backwards

DirectionalLightlight1=newDirectionalLight(white,ligh

light1.setInfluencingBounds(bounds);

sceneBG.addChild(light1);



Figure15-3.PartialscenegraphforCheckers3D



Thedirectionisthevectorbetween(0,0,0)and(-1,-1,-1);

thelightcanbeimaginedtobemultipleparallellineswiththat

direction,originatingatinfinity.

PointandspotlightsaretheotherformsofJava3Dlighting.

Pointlightspositionthelightinspace,emittinginalldirections.

Spotlightsarefocusedpointlights,aimedinaparticular

direction.



TheScene'sBackground

Abackgroundforascenecanbespecifiedasaconstantcolor

(asshownhere),astaticimage,oratexture-mappedgeometry

suchasasphere:

Backgroundback=newBackground();

back.setApplicationBounds(bounds);

back.setColor(0.17f,0.65f,0.92f);//skycolor

sceneBG.addChild(back);



FloatingSpheres

SphereisautilityclassfromJava3D'scom.sun.j3d.utils.geometry



package,asubclassofthePrimitiveclass,whichisaGroupnode

withaShape3Dchild(seeFigure15-3).Itsgeometryisstoredina

Java3DTRiangleStripArray,whichspecifiesthesphereasanarray

ofconnectedtriangles.Idon'thavetoadjustthisgeometry,but

thesphere'sappearanceandpositiondorequirechanges.

TheAppearancenodeisacontainerforreferencesoftomuch

information,includingcoloring,line,point,polygon,rendering,

transparency,andtextureattributes.

ColouringAttributesfixesthecolorofashapeandisunaffectedby



scenelighting.Forashaperequiringinteractionbetweencolor

andlight,theMaterialcomponentisemployed.Forlighttoaffect

ashape'scolor,threeconditionsmustbemet:

Theshape'sgeometrymustincludenormals.

Theshape'sAppearancenodemusthaveaMaterialcomponent.

TheMaterialcomponentmusthaveenabledlightingwith

setLightingEnable().

TheutilitySphereclasscanautomaticallycreatesnormals,sothe

firstconditioniseasilysatisfied.



ColoringtheSpheres

TheJava3DMaterialcomponentcontrolswhatcolorashape

exhibitswhenlitbydifferentkindsoflights:



Materialmat=newMaterial(ambientColor,emissiveColor,

diffuseColor,specularColor,sh



Theambientcolorargumentspecifiestheshape'scolorwhenlit

byambientlight:thisgivestheobjectauniformcolor.The

emissivecolorcontributesthecolorthattheshapeproduces(as

foralightbulb);frequently,thisargumentissettoblack

(equivalenttooff).Thediffusecoloristhecoloroftheobject

whenlit,withitsintensitydependingontheanglethelight

beamsmakewiththeshape'ssurface.



Thediffuseandambientcolorsareoftensettobethesame,which

matchesthewayreal-worldobjectsarecoloredwhenlit.



Theintensityofthespecularcolorparameterisrelatedtohow

muchtheshapereflectsfromitsshinyareas.Thisiscombined

withtheshininessargument,whichcontrolsthesizeofthe

reflectivehighlights.



Thespecularcolorisoftensettowhite,matchingthespecularcolor

producedbymostobjectsintherealworld.



InCheckers3D,therearetwodirectionallights,whichcreatetwo

shinypatchesonthetopofthefloatingsphere(seeFigure151).Thefloortilesareunlitsincetheircolorissetintheshape's

geometry(moreonthislaterinthechapter).

ThecodeinfloatingSphere()thathandlesthesphere's



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 15.  A 3D Checkerboard: Checkers3D

Tải bản đầy đủ ngay(0 tr)

×