Tải bản đầy đủ - 0 (trang)
Chapter 14.  Introducing Java 3D

Chapter 14.  Introducing Java 3D

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

Java3D

TheJava3DAPIprovidesacollectionofhigh-levelconstructs

forcreating,rendering,andmanipulatinga3Dscenegraph

composedofgeometry,materials,lights,sounds,andmore.

Java3DwasdevelopedbySunMicrosystems,andthemost

recentstablereleaseisVersion1.3.1.



ThereisaVersion1.3.2,butit'sabugfixreleaseunderreviewasI

writethisinDecember2004.Forexample,ararelyoccurringbugwith

theJ3DTimerclasshasbeenfixed.

Bythetimeyoureadthis,Version1.3.2willhavebeenfinalized(an

FCSreleasewillbeavailable).



TherearetwoJava3Dvariants:oneimplementedontopof

OpenGL,andtheotheraboveDirectXGraphics.OpenGLisa

popularsoftwareAPIforwriting3D(and2D)graphics

applicationsacrossawiderangeofhardwareandoperating

systems(http://www.opengl.org/).It'salow-levelAPIbased

aroundagraphicspipelineforpixelandvertexmanipulation.



Priortothe1.3.2bugfixrelease,aprogrammerhadtochoosewhether

todownloadtheOpenGLversionofJava3DortheDirectX

implementationsincetheywereofferedasseparateinstallers.With

Version1.3.2(build7andlater),bothversionsareinasingle

download.



DirectXGraphicssupportsatraditionalgraphicspipeline,

describingallgeometryintermsofverticesandpixels.It'spart



ofDirectX,acollectionofrelatedgamingmodulesaimedatMS

Windows(http://www.microsoft.com/directx).Theother

DirectXAPIssupport3Daudio,networking,inputdevice

integration,multimedia,andinstallationmanagement.



DirectXorOpenGL?

Often,thedebateaboutwhichversionofJava3Disbetterisa

debateabouttherelativemeritsofDirectXGraphicsand

OpenGL.

Inmosttechnicalareas,DirectXGraphicsandOpenGLare

almostequivalentsincebotharebasedonthesamegraphics

pipelinearchitectureandideasflowbetweenthetwo.Themost

significantdifferencesbetweenthetwoAPIsareunrelatedto

theirfunctionality.OpenGLisportedtoawiderangeof

platformsandOSs,andDirectXislimitedtoPCsrunning

WindowsandtheXbox.DirectXiscontrolledbyMicrosoftalone,

andtheOpenGLArchitectureReviewBoard(ARB)allowsinput

frommanypartners.

TheDirectXGraphicsversionofJava3Disonlyavailablefor

Windows,wheresomeusersreportthatit'smarginallyfaster

thantheOpenGLimplementation.However,I'venevernoticed

anydifferencewhenI'vetriedbothsystems.

ThefutureseemsbrightestfortheOpenGLversion,whichisthe

mainfocusofthecurrent"bugfix"releaseofJava3D,Version

1.3.2.I'llusethestableOpenGLversion(1.3.1)intherestof

thisbook.Itcanbedownloadedfrom

http://java.sun.com/products/java-media/3D/,togetherwith

ampledocumentationandalongtutorial.



TheFCSreleaseofVersion1.3.2willbeavailablebythetimeyouread

this.Youcanobtainitfromhttps://java3d.dev.java.net/.



TheSceneGraph

Java3Dusesascenegraphtoorganizeandmanagea3D

application.Theunderlyinggraphicspipelineishidden,replaced

byatree-likestructurebuiltfromnodesrepresenting3D

models,lights,sounds,thebackground,thecamera,andmany

othersceneelements.

Thenodesaretyped,themaindivisionbeingbetweenGroupand

Leafnodes.AGroupnodeisonewithchildnodes,groupingthe

childrensooperationssuchastranslations,rotations,and

scalingcanbeappliedenmasse.Leafnodesaretheleavesof

thegraph(didyouguessthat?),whichoftenrepresentthe

visiblethingsinthescenesuchasthemodels,butmaybe

nontangibleentities,suchaslightingandsounds.Additionally,a

Leafnode(e.g.,fora3Dshape)mayhavenodecomponents,

specifyingcolor,reflectivity,andotherattributesoftheleaf.

Thescenegraphcancontainbehaviors,nodesholdingcodethat

canaffectothernodesinthegraphatruntime.Typicalbehavior

nodesmoveshapes,detectandrespondtoshapecollisions,and

cyclelightingfromdaytonight.

Scenegraphisused,ratherthanscenetree,becauseit's

possiblefornodestobeshared(i.e.,havemorethanone

parent).

BeforelookingatarealJava3Dscenegraph,Figure14-1

showshowthescenegraphideacanbeappliedtodefiningthe

contentsofanoffice.



Figure14-1.Scenegraphforanoffice



TheofficeGroupnodeistheparentofLeafnodesrepresentinga

deskandtwochairs.EachLeafutilizesgeometry(shape)and

colornodecomponents,andthechairgeometryinformationis

shared.Thissharingmeansthatbothchairswillhavethesame

shapebutwillbecoloreddifferently.

ThechoiceofsymbolsinFigure14-1comesfromastandard

symbolset(showninFigure14-2),usedinallofthisbook's

Java3Dscenegraphdiagrams.I'llexplaintheVirtualUniverse

andLocalenodesandtheReferencerelationshipinduecourse.



SomeJava3Dscenegraphnodes

TheJava3DAPIcanbeviewedasasetofclassesthatsubclass

theGroupandLeafnodesinvariousways.TheLeafclassis

subclassedtodefinedifferentkindsof3Dshapesand

environmentalnodes(i.e.,nodesrepresentinglighting,sounds,

andbehaviors).



Figure14-2.Scenegraphsymbols



ThemainshapeclassiscalledShape3D,whichusestwonode

componentstodefineitsgeometryandappearance;these

classesarecalledGeometryandAppearance.

TheGroupclasssupportsbasicnodepositioningandorientation

foritschildrenandissubclassedtoextendthoseoperations.

Forinstance,BranchGroupallowschildrentobeaddedorremoved

fromthegraphatruntime;transformGrouppermitstheposition

andorientationofitschildrentobechanged.



TheHelloUniversescenegraph

ThestandardfirstexampleforJava3Dprogrammersis

HelloUniverse.(ItappearsinChapter1ofSun'sJava3Dtutorial.)

Itdisplaysarotatingcoloredcube,asinFigure14-3.

ThescenegraphforthisapplicationisgiveninFigure14-4.

VirtualUniverseisthetopnodeineveryscenegraphand



representsthevirtualworldspaceanditscoordinatesystem.



Localeactsasthescenegraph'slocationinthevirtualworld.



BelowtheLocalenodearetwosubgraphstheleftbranchisthe

contentbranchgraph,holdingprogram-specificcontentsuchas

geometry,lighting,textures,andtheworld'sbackground.The

contentbranchgraphdifferssignificantlyfromoneapplication

toanother.

TheColorCubeiscomposedfromaShape3Dnodeandassociated

GeometryandAppearancecomponents.Itsrotationiscarriedoutby

aBehaviornode,whichaffectsthetransformGroupparentofthe

ColorCube'sshape.



Figure14-3.Arotatingcoloredcube



Figure14-4.ScenegraphforHelloUniverse



TherighthandbranchbelowLocaleistheviewbranchgraph,

whichspecifiestheusers'position,orientation,andperspective

astheylookintothevirtualworldfromthephysicalworld(e.g.,

frominfrontofamonitor).TheViewPlatformnodestoresthe

viewer'spositioninthevirtualworld;theViewnodestateshow

toturnwhattheviewerseesintoaphysicalworldimage(e.g.,

a2Dpictureonthemonitor).TheCanvas3DnodeisaJavaGUI

componentthatallowsthe2DimagetobeplacedinsideaJava

applicationorapplet.

TheVirtualUniverse,Locale,andviewbranchgraphoftenhavethe

samestructureacrossdifferentapplicationssincemost

programsuseasingleLocaleandviewthevirtualworldasa2D

imageonamonitor.Fortheseapplications,therelevantnodes

canbecreatedwithJava3D'sSimpleUniverseutilityclass,



relievingtheprogrammermuchgraphconstructionwork.



Java3DStrengths

ThecorestrengthsofJava3Dareitsscenegraph,its

performance,collectionofuniquefeatures,thefactthatit's

Javaandcancalluponanenormousnumberofsupport

packagesandAPIs,anditsextensivedocumentationand

examples.



TheSceneGraph

Thescenegraphhastwomainadvantages:itsimplifies3D

programmingandacceleratestheresultingcode.Thescene

graphhideslow-level3Dgraphicselementsandallowsthe

programmertomanageandorganizea3Dscene.Ascene

graphsupportsmanycomplexgraphicalelements.

AttheJava3Dimplementationlevel,thescenegraphisusedto

groupshapeswithcommonproperties,carryoutviewculling,

occlusionculling,levelofdetailselection,executionculling,and

behaviorpruning,alloptimizationsthatmustbecodeddirectly

bytheprogrammerinlower-levelAPIs.Java3DutilizesJava's

multithreadingtocarryoutparallelgraphtraversaland

rendering,bothusefuloptimizations.



Performance

Java3Disdesignedwithperformanceinmind,whichit

achievesatthehighlevelbyscenegraphoptimizationsandat

thelowlevelbybeingbuiltontopofOpenGLorDirectX

Graphics.

Someprogrammer-specifiedscenegraphoptimizationsare

availablethroughcapabilitybits,whichstatewhatoperations



can/cannotbecarriedoutatruntime(e.g.,prohibitingashape

frommoving).Java3Dalsopermitstheprogrammertobypass

thescenegraph,eithertotallybymeansofanimmediatemode,

orpartiallyviathemixedmode.Immediatemodegivesthe

programmergreatercontroloverrenderingandscene

management,butitisn'toftenrequired.Retainedmode

programsonlyusethescenegraphAPI.Alltheexamplesinthis

bookemployretainedmode.



UniqueFeatures

Java3D'sviewmodelseparatesthevirtualandphysicalworlds

throughtheViewPlatformandViewnodes.Thismakesit

straightforwardtoreconfigureanapplicationtoutilizemany

outputdevices,fromamonitor,tostereoglasses,toCAVEs.

VirtualworldbehavioriscodedwithBehaviornodesinthescene

graphandistriggeredbyevents.Amongotherthings,this

offersadifferentstyleofanimationbasedonrespondingto

eventsinsteadoftheusualupdateredraw/cycleyou'veseenin

allmy2Dgamesprograms.

ThecoreJava3DAPIpackage,javax.media.j3d,supportsbasic

polygonsandtriangleswithinascenegraph;thecom.sun.j3d

packagesaddarangeofutilityclassesincludingColorCubeand

SimpleUniverse,mouseandkeyboardnavigationbehaviors,audio

devicehandling,andloadersforseveral3Dfileformats.

Geometrycompressionispossible,oftenreducingsizebyan

orderofmagnitude.WhenthisiscombinedwithJava'sNIOand

networking,itfacilitatesthereadytransferoflargequantitiesof

databetweenapplicationssuchasmultiplayergames.

Java3Dallows2Dand3Daudiooutput,ambientand

spatializedsound.Unfortunately,thesoundsystemhasbugs.

Consequently,spatializedsoundisn'tavailablebydefaultinJava



3D1.3.2.Version1.4mayofferaJOALMixerclassinstead,i.e.,a

JOAL-basedaudiodevice.JOALisaJavabindingfora3Daudio

APIcalledOpenAL,whichissupportedbymanysoundcards.



JavaIntegration

Java3DisJavaandoffersobjectorientation(classes,

inheritance,polymorphism),threads,exceptionhandling,and

more.Java3DcaneasilymakeuseofotherJavaAPIs,suchas

JMFandJAI.TheJavaMediaFramework(JMF)includes

mechanismsforplayingaudioandvideosegmentsandcanbe

extendedtosupportnewformsoraudioandvideo

(http://java.sun.com/products/java-media/jmf).JavaAdvanced

Imaging(JAI)providesmanyadvancedimageprocessing

features,includingover100imagingoperators,tilingoflarge

images,network-basedcapabilities,andthemeanstoaddnew

imageprocessingfeatures(http://java.sun.com/products/javamedia/jai).



DocumentationandExamples

TheJava3Ddistributioncomeswithabout40smalltomedium

examples.They'reagreathelpbutsomewhatlackingin

documentation.Fortunately,moreresourcesareonline.Sun's

Java3Dtutorialisavailableat

http://java.sun.com/products/java-media/3D/collateral/.The

tutorialisagoodintroductiontoJava3Dbutcanconfuse

beginners.BenMoxonhasagoodintroductoryJava3Dtutorial

basedaroundgettingaMilkShape3Dfiguretomoveovera

hillyterrain

(http://www.newview.co.uk/e/tutorials/java3d/index.jsp)andis

calledTheLittlePurpleDudeWalks.



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

Chapter 14.  Introducing Java 3D

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

×