Professional Documents
Culture Documents
Phn 1............................................................................................................................. 9
Lp trnh ha vi Java 2D..........................................................................................9
Chng 1.................................................................................................................. 10
Tng quan v Java 2D API.......................................................................................10
1.1 Enhanced Graphics, Text, and imaging..........................................................10
1.2 Rendering Model............................................................................................ 11
1.2.1 Coordinate Systems................................................................................. 12
1.2.1.1 User Space....................................................................................... 12
1.2.1.2 Device Space....................................................................................13
1.2.2 Transforms...............................................................................................14
1.2.3 Fonts.........................................................................................................15
1.2.4 Images......................................................................................................16
1.2.5 Fills and Strokes.......................................................................................17
1.2.6 Composites...............................................................................................18
Backward Compatibility and Platform independence.......................................... 19
1.3.1 Backward Compatibility..........................................................................19
1.3.2 Platform independence............................................................................ 21
1.4 The Java 2D API Packages.........................................................................21
Chng 2:................................................................................................................. 25
Rendering with Graphics2D..................................................................................... 25
2.1 Cc lp v giao din....................................................................................... 26
2.2 Rendering Concepts........................................................................................27
2.2.1 Rendering Process....................................................................................28
2.2.2 Controlling Rendering Quality................................................................ 29
2.2.3 Stroke Attributes......................................................................................31
2.2.4 Fill Attributes...........................................................................................32
Qu trnh x l theo phin............................................................................ 34
2.2.5 Clipping Paths..........................................................................................34
2.2.6 Transformations.......................................................................................35
2.2.6.1 Constructing an AffineTransform....................................................37
2.2.7 Composite Attributes............................................................................... 38
2.2.7.1 Managing Transparency.................................................................. 39
2.2.7.2 Transparency and images.................................................................40
2.3 Thit lp Graphics2Context............................................................................40
2.3.1 Setting Rendering Hints...........................................................................40
2.3.2 Specifying Stroke Attributes....................................................................41
2.3.2.1 Setting the Stroke Width..................................................................41
2.3.2.2 Specifying Join and Endcap Styles..................................................42
2.3.2.3 Setting the Dashing Pattern..............................................................42
2.3.3 Specifying Fill Attributes.........................................................................44
2.3.3.1 Filling a Shape with a Gradient....................................................... 44
2.3.3.2 Filling a Shape with a Texture.........................................................45
2.3.4 Setting the Clipping Path......................................................................... 46
2.3.5 Setting the Graphics2D Transform..........................................................48
2.3.6 Specifying a Composition Style.............................................................. 51
2.3.6.1 Using the Source Over Compositing Rule.......................................51
2.3.6.2 Increasing the Transparency of Composited Objects...................... 52
2.4 Rendering Graphics Primitives.......................................................................53
2.4.1 Drawing a Shape......................................................................................54
2.4.2 Filling a Shape.........................................................................................55
http://tailieuhay.com
http://tailieuhay.com
http://tailieuhay.com
http://tailieuhay.com
http://tailieuhay.com
Li ni u
S pht trin ca khoa hc, k thut, ngh thut, kinh doanh, v
cng ngh lun lun ph thuc vo kh nng truyn t thng tin ca
chng ta, hoc thng qua cc bit d liu lu tr trong microchip hoc
thng qua giao tip bng ting ni. Cu chm ngn t xa xa mt hnh
nh c gi tr hn c vn li" hay "trm nghe khng bng mt thy" cho
thy ngha rt ln ca hnh nh trong vic chuyn ti thng tin. Hnh
nh bao gi cng c cm nhn nhanh v d dng hn, c bit l trong
trng hp bt ng v ngn ng. Do khng c g ngc nhin khi m
ngay t khi xut hin my tnh, cc nh nghin cu c gng s dng n
pht sinh cc nh trn mn hnh. Trong sut gn 50 nm pht trin ca
http://tailieuhay.com
http://tailieuhay.com
http://tailieuhay.com
Phn 1
Lp trnh ha vi Java 2D
http://tailieuhay.com
Chng 1
Tng quan v Java 2D API
http://tailieuhay.com
10
Rendering Model
Kiu t trt ha n gin khng c g thay i khi thm vo Java
http://tailieuhay.com
11
(0,0)
http://tailieuhay.com
12
y
Figure 1-1
Khng gian ngi s dng biu din mt cch tru tng ng nht
cho cc h to ca tt c cc thit b c lin quan.Cn khng gian thit
b cho mt thit b c th c th c cng gc ta v hng ca cc trc
hoc l c th khng.Ngoi ra cc ta ca khng gian ngi s dng
c th chuyn i mt cch t ng vo khng gian thit b ph hp mi
khi mt i tng ha c t trt,thng th cc chng trnh driver
ca cc thit b thc hin iu ny.
1.2.1.2 Device Space
Java 2D API nh ngha 3 mc thng tin cu hnh h tr cho vic
chuyn i t khng gian ngi s dng sang khng gian thit b. Thng
tin ny c cha trong 3 lp :
GraphicsEnvironment
GraphicsDevice
GraphicsConfiguration
Hai trong s chng s biu din tt c cc thng tin cn thit cho vic
xc nh thit bi t trt v cho vic chuyn i ta t khng gian ngi
http://tailieuhay.com
13
hnh
ph
hp
ca
thit
biu
din
bi
lp
tng
GraphicsConfiguration.Mt
tng
kiu
http://tailieuhay.com
14
http://tailieuhay.com
15
http://tailieuhay.com
16
http://tailieuhay.com
17
http://tailieuhay.com
18
http://tailieuhay.com
19
http://tailieuhay.com
20
http://tailieuhay.com
21
http://tailieuhay.com
22
cc phn
http://tailieuhay.com
23
http://tailieuhay.com
24
Chng 2:
Rendering with Graphics2D
http://tailieuhay.com
25
Cc lp v giao din.
Bng cho sau y s lit k cc giao din v lp trong vic kt hp
M t
nh ngha cc phng thc cho vic kt hp mt
i tng v gc vi cng ha c nh du.
CompositeContex
Paint
trnh.
M rng: Transparency
nh ngha cc mu sc cho vic t hoc v. c
thc thi bi i tng
PaintContext
Color,Gradient-Paint v
TexturePaint.
nh ngha mt mi trng ti u v c lp cho
vic v.Cc thao tc v c ty chn bi ngi lp
Stroke
trnh.
To ra mt i tng Shape m cc ng vin ca
n oc to bng.c thc thi bi phng thc
BasicStroke.
Cc lp v m t s lc v chng:
Lp
AffineTransform
M t
Miu t mt php bin i 2D affine ,m thc hin
(java.awt.geom)
http://tailieuhay.com
26
BasicStroke
Color
GradientPaint
Shape.
Thc thi: Paint
nh ngha mt mu t mu loang tuyn tnh cho i
tng Shape.Mu ny s thay i t mu C1 (ti im
Graphics2D
TexturePaint
to
ra
tu
tng
BufferedImage.
2.2
Rendering Concepts
t trt mt i tng ha s dng Java 2D API, cn thit lp
http://tailieuhay.com
27
http://tailieuhay.com
28
http://tailieuhay.com
29
http://tailieuhay.com
30
http://tailieuhay.com
31
32
http://tailieuhay.com
33
http://tailieuhay.com
34
http://tailieuhay.com
35
parents origin
Phng to mt thnh phn d dng quan st.
Cc tnh hung khc m ngi cung cp i tng Graphics2D
mun chuyn i cho qu trnh to bng hiu qu .
Phng thc setTransform method c xem nh thit lp i
tng Graphics2D tr lai php bin i ban u sau qu trnh to bng
ha ,vn bn v nh c chuyn i:
Aff i n e T r a n s f o r m
aT
g2d . g e t T r a n s f o r m ( ) ;
g2d . t r a n s f o r m ( . . . ) ;
g2 d . d r a w ( . . . ) ;
g2d . s e t T r a n s f o r m ( a T ) ;
http://tailieuhay.com
36
http://tailieuhay.com
37
Graphics2D
phng
bng
cch
gi
thc
setComposite.
ca interface
http://tailieuhay.com
38
ng cnh ca i tng
39
2.3
Thit lp Graphics2Context
cu hnh ng cnh Graphics2D cho qu trnh to bng phi s
40
qu a l i t y H i n t s
new
Ren d e r i n g H i n t s ( R e n d e r i n g H i n t s . K E Y _ A N T i A L i A S
iNG ,
Ren d e r i n g H i n t s . V A L U E _ A N T i A L i A S _ O N ) ;
qua l i t y H i n t s . p u t ( R e n d e r i n g H i n t s . K E Y _ R E N D E R
iNG ,
Ren d e r i n g H i n t s . V A L U E _ R E N D E R _ Q U A L i T Y ) ;
g2 . s e t R e n d e r i n g H i n t s ( q u a l i t y H i n t s ) ;
2.3.2 Specifying Stroke Attributes
Mt i tng BasicStroke s nh ngha cc tnh cht uwoc p
dng cho ng vin bao quanh mt i tng Shape, gm c rng v
kiu ng (dashing pattern), lm th no cc on thng c kt hp
vi nhau. khi to cc thuc tnh v ng nt trong ng cnh
Graphics2D ,th khi to mt i tng BasicStroke v chuyn n vo
phng thc setStroke
2.3.2.1 Setting the Stroke Width
khi to rng ng nt th khi to i tng BasicStroke vi
rng mong mun v sau gi phng thc setStroke
http://tailieuhay.com
41
wid e S t r o k e
new
Bas i c S t r o k e ( 1 2 . 0 f ) ;
g2. s e t S t r o k e ( w i d e S t r o k e ) ;
2.3.2.2 Specifying Join and Endcap Styles
khi to cho cc kiu join v endcap ,cn to mt i tng
BasicStroke vi cc thuc tnh mong mun .
Trong v d cho sau y, rng ng nt c khi to vi 12 im
v cc kiu join v endcap c s dng thay cho cc gia tri mc nh:
rou n d S t r o k e
new
Ba s i c S t r o k e ( 4 . 0 f ,
Bas i c S t r o k e . C A P _ R O U N D ,
Bas i c S t r o k e . J O i N _ R O U N D ) ;
g2. s e t S t r o k e ( r o u n d S t r o k e ) ;
2.3.2.3 Setting the Dashing Pattern
Cc kiu ng phc tp c th d dng c nh ngha vi mt i
tng BasicStroke.
Khi to mt i tng BasicStroke ,phi xc nh 2 tham s kim
sot kiu ng:
dash - l mt mng biu din kiu ng. Cc phn t xen k
ca mng biu din kch thc nt gch v khong cch gia cc nt
gch .
Phn t 0 biu din nt gch u tin, phn t th 1 biu din khong
trng u tin.
http://tailieuhay.com
42
flo a t
das h 1 [ ]
Bas i c S t r o k e
{10 . 0 f } ;
new
bs
Bas i c S t r o k e ( 5 . 0 f ,
Bas i c S t r o k e . C A P _ B U T T ,
Ba s i c S t r o k e . J O i N _ M i T E R ,
10 . 0 f ,
das h 1 ,
0.0 f ) ;
g2 . s e t S t r o k e ( b s ) ;
Li n e 2 D
10 . 0 f ,
lin e
new
10 0 . 0 f ,
Lin e 2 D . F l o a t ( 2 0 . 0 f ,
10. 0 f ) ;
g2 . d r a w ( l i n e ) ;
fl o a t [ ]
4.0 f ,
bs
da s h 2
2.0 f ,
=
{6. 0 f ,
4.0 f ,
2.0 f ,
4.0 f } ;
new
Ba s i c S t r o k e ( 5 . 0 f ,
Bas i c S t r o k e . C A P _ B U T T ,
Ba s i c S t r o k e . J O i N _ M i T E R ,
10 . 0 f ,
das h 2 ,
0.0 f ) ;
g2 . s e t S t r o k e ( b s ) ;
g2 . d r a w ( l i n e )
http://tailieuhay.com
43
http://tailieuhay.com
44
Gr a d i e n t P a i n t
gp
Gra d i e n t P a i n t ( 5 0 . 0 f ,
50 . 0 f ,
25 0 . 0 f ,
=
50 . 0 f ,
new
Col o r . b l u e
Col o r . g r e e n ) ;
g2 . s e t P a i n t ( g p ) ;
g2. f i l l R e c t ( 5 0 ,
50,
200 ,
200 ) ;
Create
of
size
buffered
image
texture
patch
//5x5
http://tailieuhay.com
45
bi
new
Bufferedimage(5,
5,
Bufferedimage.TYPE_iNT_RGB);
Graphics2D
big
bi.createGraphics();
big.setColor(Color.green);
big.fillRect(0,0,5,5);
big.setColor(Color.lightGray);
big.fillOval(0,0,5,5);
//
Create
buffered
texture
paint
from
the
image
Rectangle
TexturePaint
new
tp
Rectangle(0,0,5,5);
new
TexturePaint(bi,r,TexturePaint.NEAREST_NEiGHBOR)
;
//
Add
the
texture
paint
to
the
graphics
context. g2.setPaint(tp);
//
with
Create
the
and
render
rectangle
filled
texture. g2.fillRect(0,0,200,200);
}
2.3.4 Setting the Clipping Path
nh ngha mt khung nhn:
1. Khi to mt i tng Shape m biu din vng mun to
bng.
2. Gi phng thc Graphics2D.setClip s dng i tung
http://tailieuhay.com
46
pub l i c
voi d
Gra p h i c s 2 D
//
The
pai n t ( G r a p h i c s
g2
wid t h
g)
(Gr a p h i c s 2 D )
and
hei g h t
get S i z e ( ) . w i d t h ;
int
get S i z e ( ) . h e i g h t ;
//
the
Cre a t e
an
ell i p s e
cl i p p i n g
g;
of
int
the
and
use
can v a s
it
as
pat h
Ell i p s e 2 D
new
El l i p s e 2 D . F l o a t ( w / 4 . 0 f , h / 4 . 0 f ,
w/2 . 0 f , h / 2 . 0 f ) ;
g2. s e t C l i p ( e ) ;
//
Fil l
wit h i n
the
can v a s .
the
cl i p
Onl y
the
are a
is
ren d e r e d
pa t h ,
set t i n g
g2. s e t C o l o r ( C o l o r . c y a n ) ;
g2. f i l l R e c t ( 0 , 0 , w , h ) ;
//
Cha n g e
it
to
//
the
the
the
cl i p p i n g
int e r s e c t i o n
cu r r e n t
cli p
of
and
new
rec t a n g l e .
Rec t a n g l e
new
47
//
Fil l
the
wit h i n
the
//
ren d e r e d
is
new
can v a s .
Onl y
the
are a
cli p
g2 . s e t C o l o r ( C o l o r . m a g e n t a ) ;
g2. f i l l R e c t ( 0 , 0 , w , h ) ;
php
quay
bng
cch
gi
AffineTransform.
getRotateinstance.
3. Gi phng thc Graphics2D.transform thm vo cc php
http://tailieuhay.com
48
Aff i n e T r a n s f o r m
Rec t a n g l e 2 D
aT
g2. g e t T r a n s f o r m ( ) ;
rec t
new
Rec t a n g l e 2 D . F l o a t ( 1 . 0 , 1 . 0 , 2 . 0 , 3 . 0 ) ;
Aff i n e T r a n s f o r m
rot a t e 4 5
Aff i n e T r a n s f o r m . g e t R o t a t e i n s t a n c e ( M a t h . P
i/4 . 0 , 0 . 0 , 0 . 0 )
g2. t r a n s f o r m ( r o t a t e 4 5 ) ;
g2 . d r a w ( r e c t ) ;
g2. s e t T r a n s f o r m ( a T ) ;
//
Def i n e
http://tailieuhay.com
the
ren d e r i n g
tra n s f o r m
49
at
new
Aff i n e T r a n s f o r m ( ) ;
//
mak e
//
App l y
roo m
for
ro t a t e d
tra n s l a t i o n
tra n s f o r m
to
the
tex t .
at. s e t T o T r a n s l a t i o n ( 4 0 0 . 0 ,
40 0 . 0 ) ;
g2 . t r a n s f o r m ( a t ) ;
//
Cre a t e
rot a t e
the
rot a t i o n
tra n s f o r m
tex t
at. s e t T o R o t a t i o n ( M a t h . P i
//
Re n d e r
J a v a
for
fou r
at
(in t
to
cop i e s
90
i
deg r e e
=
0;
2.0 ) ;
of
the
str i n g
ang l e s
i
g2. d r a w S t r i n g ( J a v a ,
<
4;
0.0 f ,
i++ )
0.0 f ) ;
g2 . t r a n s f o r m ( a t ) ;
}
Aff i n e T r a n s f o r m
http://tailieuhay.com
rot a t e 4 5
50
rot a t e 4 5 ) ;
ac
=AlphaComposite.getinstance(AlphaComposite.SRC_OV
ER);
http://tailieuhay.com
51
phng
thc
setComposite
thm
tung
AlphaComposite
ac
=AlphaComposite.getinstance(AlphaComposite.SRC_O
VER, .5f);
pub l i c
voi d
Gra p h i c s 2 D
g2
pai n t ( G r a p h i c s
=
(Gr a p h i c s 2 D )
g)
g;
g2 . s e t C o l o r ( C o l o r . r e d ) ;
g2. t r a n s l a t e ( 1 0 0 , 5 0 ) ;
//
rad i a n s = d e g r e e
http://tailieuhay.com
pi e
180
52
set
Cre a t e
to
a
Al p h a C o m p o s i t e
Aff i n e T r a n s f o r m ( ) ) ;
ide n t i t y
new
alp h a
ac
com p o s i t e
Al p h a C o m p o s i t e . g e t i n s t a n c e ( A l p h a C o m p o s i t e . S
RC _ O V E R , 0 . 5 f ) ;
g2. s e t C o m p o s i t e ( a c ) ;
g2 . s e t C o l o r ( C o l o r . g r e e n ) ;
g2. f i l l R e c t ( 5 0 , 0 , 1 0 0 , 1 0 0 ) ;
g2 . s e t C o l o r ( C o l o r . b l u e ) ;
g2 . f i l l R e c t ( 1 2 5 , 7 5 , 1 0 0 , 1 0 0 ) ;
g2 . s e t C o l o r ( C o l o r . y e l l o w ) ;
g2 . f i l l R e c t ( 5 0 , 1 2 5 , 1 0 0 , 1 0 0 ) ;
g2 . s e t C o l o r ( C o l o r . p i n k ) ;
g2. f i l l R e c t ( - 25, 7 5 , 1 0 0 , 1 0 0 ) ;
}
2.4
http://tailieuhay.com
53
drawRoundRect,
drawOval,
drawArc,drawPolyline,
drawPolygon, draw3DRect.
Khi mt i tng Shape c v , th ng bin ca n s c to
nt bng i tng Stroke trong ng cnh Graphics2D
Bng vic thit lp i tng BasicStroke ph hp trong ng cnh
Graphics2D ,th c th v ng thng vi rng v mu nt gch bt
k . i tng BasicStroke cng nh ngha cc thuc tnh endcap v
join ca ng thng .
to bng cho cc ng bin ca i tng shape:
1. Khi to cho i tng BasicStroke
2. Gi phng thc Graphics2D.setStroke
3. Khi to cho i tng Shape.
4. Gi phng thc Graphics2D.draw(shape).
Trong v d sau,i tng GeneralPath c s dng nh ngha
mt ngi sao v mt i tng BasicStroke c thm vo ng cnh
Graphics2D nh ngha cho cc cnh ca ngi sao vi cc thuc tnh
join .
pub l i c
voi d
http://tailieuhay.com
pai n t ( G r a p h i c s
g)
54
//
g2
cre a t e
(Gr a p h i c s 2 D )
and
g2. s e t S t r o k e ( n e w
//
Cre a t e
pat h
set
g;
the
st r o k e
Bas i c S t r o k e ( 4 . 0 f ) ) ;
sta r
usi n g
gen e r a l
obj e c t
Gen e r a l P a t h
new
Ge n e r a l P a t h ( G e n e r a l P a t h . N O N _ Z E R O ) ;
p. m o v e T o ( -
10 0 . 0 f ,
25. 0 f ) ;
p. l i n e T o ( +
10 0 . 0 f ,
25. 0 f ) ;
p. l i n e T o ( -
50 . 0 f ,
100 . 0 f ) ;
p. l i n e T o ( +
0.0 f ,
p. l i n e T o ( +
50 . 0 f ,
100 . 0 f ) ;
+
100 . 0 f ) ;
p.c l o s e P a t h ( ) ;
//
tra n s l a t e
of
can v a s
ori g i n
to w a r d s
ce n t e r
g2 . t r a n s l a t e ( 1 0 0 . 0 f ,
100 . 0 f ) ;
//
re n d e r
the
sta r ' s
pat h
g2 . d r a w ( p ) ;
}
http://tailieuhay.com
55
dng
Graphics2D.setColor
hay
Graphics2D.setPaint.
1. Khi to i tng Shape.
2. Gi phng thc Graphics2D.fill to bng i tng
Shape.
Trong v d sau y ,phng thc setColor c gi nh ngha
mu t l green fill cho mt i tng Rectangle2D.
pub l i c
voi d
Gra p h i c s 2 D
pai n t ( G r a p h i c s
g2
g)
(Gr a p h i c s 2 D )
g;
g2 . s e t P a i n t ( C o l o r . g r e e n ) ;
Rec t a n g l e 2 D
r2
new
Rec t a n g l e 2 D . F l o a t ( 2 5 , 2 5 , 1 5 0 , 1 5 0 ) ;
g2. f i l l ( r 2 ) ;
}
http://tailieuhay.com
56
57
http://tailieuhay.com
58
Frame
Fra m e ( G r a p h i c s C o n f i g u r a t i o n
Rec t a n g l e
bo u n d s
f.s e t L o c a t i o n ( 1 0
new
gc) ;
gc. g e t B o u n d s ( ) ;
+
bou n d s . x ,
10
bo u n d s . y ) ;
http://tailieuhay.com
59
vir t u a l B o u n d s
new
Rec t a n g l e ( ) ;
Gra p h i c s E n v i r o n m e n t
ge
Gra p h i c s E n v i r o n m e n t . g e t L o c a l G r a p h i c s E n v i r o
nme n t ( ) ;
Gr a p h i c s D e v i c e [ ]
gs
ge. g e t S c r e e n D e v i c e s ( ) ;
for
(in t
j++ )
Gra p h i c s D e v i c e
gd
0;
<
gs. l e n g t h ;
gs[ j ] ;
Gr a p h i c s C o n f i g u r a t i o n [ ]
gc
gd . g e t C o n f i g u r a t i o n s ( ) ;
for
(in t
i++ )
0;
<
gc . l e n g t h ;
vi r t u a l B o u n d s
vi r t u a l B o u n d s . u n i o n ( g c [ i ] . g e t B o u n d s ( ) ) ;
}
}
http://tailieuhay.com
60
/*
* Transform.java
* 1.0
* 27/03/06
* Day la doan chuong trinh mieu ta cac phep bien
doi.
*/
import java.awt.*;
import javax.swing.*;
/*
* Chuong trinh nay tao bong mot hinh duoc chon
boi nguoi su dung.Voi cac phuong
* thuc paint,stroke, va rendering cung duoc lua
chon boi nguoi su dung.
*/
/**
* @author Administrator
*
*/
public class Transform extends JApplet implements
itemListener, ActionListener {
/**
*
http://tailieuhay.com
61
JLabel
primLabel,
lineLabel,
paintLabel,
transLabel, strokeLabel;
TransPanel display;
static
JComboBox
primitive,
line,
paint,
trans, stroke;
JButton redraw;
layOut
new
GridBagLayout();
getContentPane().setLayout(layOut);
GridBagConstraints
new
GridBagConstraints();
c.weightx = 1.0;
c.fill = GridBagConstraints.BOTH;
primLabel = new JLabel();
primLabel.setText("Hnh gc");
http://tailieuhay.com
62
primLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(primLabel, c);
getContentPane().add(primLabel);
lineLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(lineLabel, c);
getContentPane().add(lineLabel);
paintLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(paintLabel, c);
getContentPane().add(paintLabel);
c.gridwidth
GridBagConstraints.RELATiVE;
transLabel = new JLabel();
transLabel.setText("Cc php bin i");
transLabel.setFont(newFont);
http://tailieuhay.com
63
transLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(transLabel, c);
getContentPane().add(transLabel);
c.gridwidth
GridBagConstraints.REMAiNDER;
strokeLabel = new JLabel();
strokeLabel.setText("T trt");
strokeLabel.setFont(newFont);
strokeLabel.setHorizontalAlignment(JLabel.CENTER)
;
layOut.setConstraints(strokeLabel, c);
getContentPane().add(strokeLabel);
GridBagConstraints
ls
new
GridBagConstraints();
ls.weightx = 1.0;
ls.fill = GridBagConstraints.BOTH;
primitive = new JComboBox(new Object[] {
"Hnh ch nht", "Hnh elip",
primitive.additemListener(this);
newFont = newFont.deriveFont(0, 14.0f);
primitive.setFont(newFont);
layOut.setConstraints(primitive, ls);
getContentPane().add(primitive);
http://tailieuhay.com
64
line
new
JComboBox(new
Object[]
line.additemListener(this);
line.setFont(newFont);
layOut.setConstraints(line, ls);
getContentPane().add(line);
paint
new
JComboBox(new
Object[]
ls.gridwidth
GridBagConstraints.RELATiVE;
trans
new
JComboBox(new
Object[]
trans.additemListener(this);
trans.setFont(newFont);
layOut.setConstraints(trans, ls);
getContentPane().add(trans);
ls.gridwidth
GridBagConstraints.REMAiNDER;
http://tailieuhay.com
65
new
JComboBox(new
Object[]
GridBagConstraints
button
new
GridBagConstraints();
button.gridwidth
GridBagConstraints.REMAiNDER;
redraw = new JButton("V li");
redraw.addActionListener(this);
redraw.setFont(newFont);
layOut.setConstraints(redraw, button);
getContentPane().add(redraw);
GridBagConstraints
tP
new
GridBagConstraints();
tP.fill = GridBagConstraints.BOTH;
tP.weightx = 1.0;
tP.weighty = 1.0;
tP.gridwidth
GridBagConstraints.REMAiNDER;
display = new TransPanel();
layOut.setConstraints(display, tP);
display.setBackground(Color.white);
getContentPane().add(display);
http://tailieuhay.com
66
validate();
display.setTrans(trans.getSelectedindex());
display.renderShape();
}
@SuppressWarnings("deprecation")
public static void main(String[] argv) {
if (argv.length > 0 && argv[0].equals("no2d")) {
Transform.no2D = true;
}
JFrame
frame
new
JFrame("Cc
php
chuyn i");
frame.addWindowListener(new
WindowAdapter() {
public
void
windowClosing(WindowEvent e) {
System.exit(0);
}
http://tailieuhay.com
67
frame.getContentPane().add(BorderLayout.CENTER,
applet);
applet.init();
frame.setSize(550, 400);
frame.show();
}
@SuppressWarnings("serial")
class TransPanel extends JPanel {
int w, h;
Bufferedimage bi;
http://tailieuhay.com
68
shapes[1]
new
Rectangle(0,
0,
100,
100);
new
Ellipse2D.Double(0.0,
textTl
new
76),
new
textAt
new
AffineTransform();
textAt.translate(0,
(float)
textTl.getBounds().getHeight());
shapes[2] = textTl.getOutline(textAt);
}
http://tailieuhay.com
69
if (!Transform.no2D) {
Graphics2D g2 = (Graphics2D) g;
Dimension d = getSize();
w = d.width;
h = d.height;
String instruct = "Nh p mt hnh c
thisTl
new
10),
g2.getFontRenderContext());
float
width
(float)
(float)
thisTl.getBounds().getWidth();
float
height
thisTl.getBounds().getHeight();
http://tailieuhay.com
70
to
new
TextLayout(instruct,
(float)
thisTl.getBounds().getWidth();
thisTl.draw(g2, w / 2 - width / 2,
height + 17);
switch
(Transform.line.getSelectedindex()) {
case 0:
g2.setStroke(new
BasicStroke(3.0f));
break;
http://tailieuhay.com
71
switch
(Transform.paint.getSelectedindex()) {
case 0:
g2.setPaint(Color.blue);
break;
case 1:
g2.setPaint(new GradientPaint(0,
0, Color.lightGray, w - 250,
h, Color.blue, false));
break;
case 2:
Bufferedimage
buffi
new
Bufferedimage(15, 15,
http://tailieuhay.com
72
Bufferedimage.TYPE_iNT_RGB);
Graphics2D
buffig
buffi.createGraphics();
buffig.setColor(Color.blue);
buffig.fillRect(0, 0, 15, 15);
buffig.setColor(Color.lightGray);
buffig.translate((15 / 2) - (5 /
2), (15 / 2) - (5 / 2));
buffig.fillOval(0, 0, 7, 7);
Rectangle r = new Rectangle(0,
0, 25, 25);
g2.setPaint(new
TexturePaint(buffi, r));
break;
}
shape
shapes[Transform.primitive.getSelectedindex()];
Rectangle r = shape.getBounds();
saveXform
g2.getTransform();
AffineTransform
toCenterAt
new
AffineTransform();
http://tailieuhay.com
73
g2.transform(toCenterAt);
g2.setStroke(oldStroke);
g2.setPaint(oldPaint);
g2.setTransform(saveXform);
http://tailieuhay.com
74
http://tailieuhay.com
75
76
M t
nh ngha cc phng thc cho vic phc hI cc
Shape
phn t t mt ng dn.
Cung cp mt tp cc phng thc cho vic miu t
(java.awt)
Cc lp
Area
CubicCurve2D
Implements: Shape
CubicCurve2D.Float
and
CubicCurve2D.Double.
Dimension2D
http://tailieuhay.com
77
Ellipse2D
M rng: RectangularShape
Ellipse2D.Double
Ellipse2D.Float
Line2D
ng thng v cc ng bc hai v bc ba
Thc thi i tng Shape.
Line2D.Double
Line2D.Float
Point2D
v Line2D.Double.
Mt im miu t mt v tr trong khng gian ta
Point2D.Double
Point2D.Float
QuadCurve2D
Point2D.Double.
Thc thi i tng Shape.
QuadCurve2D.Doubl
QuadCurve2D.Float
xc nh cc ng bc hai vi chnh xc
float
Rectangle2D
http://tailieuhay.com
double:
QuadCurve2D.Float
QuadCurve2D.Double.
M rng: RectangularShape
78
Rectangle2D.Float
RectangularShape
Rectangle2D.Double.
Thc thi i tng Shape.
Cung cp s thao tc chung cho cc tc ng ln
cc i tng Shape m n c cc hnh ch nht
RoundRectangle2D
bin.
M rng: RectangularShape
RoundRectangle2D.Double.
http://tailieuhay.com
79
http://tailieuhay.com
80
th(contains)
Mt hnh ch nht c th nm hon ton bn trong mt
bao ng ca hnh th. (contains)
Mt hnh ch nht c th phn ct hnh th (intersects)
/*
* Composite.java
* 1.0
* 20/03/06
*/
http://tailieuhay.com
81
import javax.swing.*;
/*
* Chuong trinh nay la mot vi du ve cac luat ket
hop giua cac hinh.
*/
@SuppressWarnings("serial")
public class Composite extends JApplet implements
itemListener {
CompPanel comp;
int rule = 0;
layOut
new
GridBagLayout();
getContentPane().setLayout(layOut);
http://tailieuhay.com
82
new
GridBagConstraints();
l.weightx = 1.0;
l.fill = GridBagConstraints.BOTH;
l.gridwidth
GridBagConstraints.RELATiVE;
alphaLabel = new JLabel();
alphaLabel.setText("C ng
m u");
alphaLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(alphaLabel, l);
getContentPane().add(alphaLabel);
getContentPane().setLayout(layOut);
l.gridwidth
GridBagConstraints.REMAiNDER;
rulesLabel = new JLabel();
rulesLabel.setText("Cc lut kt hp.");
newFont = getFont().deriveFont(1);
rulesLabel.setFont(newFont);
rulesLabel.setHorizontalAlignment(JLabel.CENTER);
layOut.setConstraints(rulesLabel, l);
getContentPane().add(rulesLabel);
http://tailieuhay.com
83
new
GridBagConstraints();
a.gridwidth
GridBagConstraints.RELATiVE;
a.weightx = 1.0;
a.fill = GridBagConstraints.BOTH;
alphas = new JComboBox();
layOut.setConstraints(alphas, a);
alphas.additem("1.0");
alphas.additem("0.75");
alphas.additem("0.50");
alphas.additem("0.25");
alphas.additem("0.0");
alphas.additemListener(this);
getContentPane().add(alphas);
a.gridwidth
GridBagConstraints.REMAiNDER;
rules = new JComboBox();
layOut.setConstraints(rules, a);
rules.additem("SRC");
rules.additem("DST_iN");
rules.additem("DST_OUT");
rules.additem("DST_OVER");
rules.additem("SRC_iN");
rules.additem("SRC_OVER");
rules.additem("SRC_OUT");
rules.additem("CLEAR");
rules.additemListener(this);
http://tailieuhay.com
84
GridBagConstraints
fC
new
GridBagConstraints();
fC.fill = GridBagConstraints.BOTH;
fC.weightx = 1.0;
fC.weighty = 1.0;
fC.gridwidth
GridBagConstraints.REMAiNDER;
comp = new CompPanel();
layOut.setConstraints(comp, fC);
getContentPane().add(comp);
validate();
}
(e.getStateChange()
!=
itemEvent.SELECTED) {
return;
}
(String)
alphas.getSelecteditem();
} else {
rule = rules.getSelectedindex();
}
http://tailieuhay.com
85
WindowAdapter()
{
public
void
windowClosing(WindowEvent e) {
System.exit(0);
}
});
JApplet applet = new Composite();
f.getContentPane().add("Center",
applet);
applet.init();
f.pack();
f.setSize(new Dimension(300, 300));
f.show();
}
}
AlphaComposite
ac
AlphaComposite.getinstance(AlphaComposite.SRC);
http://tailieuhay.com
86
AlphaComposite.getinstance(getRule(rule), alpha);
repaint();
}
http://tailieuhay.com
87
Dimension d = getSize();
int w = d.width;
int h = d.height;
Bufferedimage
buffimg
new
Bufferedimage(w, h,
Bufferedimage.TYPE_iNT_ARGB);
Graphics2D
gbi
buffimg.createGraphics();
g2.setColor(Color.white);
g2.fillRect(0, 0, d.width, d.height);
http://tailieuhay.com
88
Rectangle2D.Double(rectx,
Ellipse2D.Double(rectx
http://tailieuhay.com
89
/*
* @(#)Pear.java
1.0
27/03/06
*/
http://tailieuhay.com
90
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import javax.swing.JApplet;
import javax.swing.JFrame;
/*
* Chuong trinh nay ve mot qua le,su dung phuong
thuc ket hop giua cac
vung.
*/
@SuppressWarnings("serial")
public class Pear extends JApplet {
http://tailieuhay.com
91
1,
eh
29,
15.0,
15.0);
leaf1 = new Area(leaf);
http://tailieuhay.com
92
3,
eh
47,
50.0,
50.0);
st2 = new Area(stem);
st1.subtract(st2);
g2.fill(st1);
g2.setColor(Color.yellow);
circle.setFrame(ew
25,
eh,
50.0,
50.0);
oval.setFrame(ew - 19, eh - 20, 40.0,
70.0);
circ = new Area(circle);
ov = new Area(oval);
circ.add(ov);
g2.fill(circ);
}
WindowAdapter()
{
public
void
windowClosing(WindowEvent e) {
System.exit(0);
}
http://tailieuhay.com
93
}
Kt qu ca chng trnh:
http://tailieuhay.com
94
Miu t
Miu t cc font kiu 1 vi nhiu ng.c thc thi
OpenType
http://tailieuhay.com
95
M t
Miu t mt th hin ca b mt font(font face)
(java.awt)
FontRenderContext
kiu font v cc ng nt ca n.
ng gi thng tin cn thit cho cc php o vn
GlyphJustificationInfo
GlyphMetrics
GlyphVector
GraphicAttribute
vn
bn.c
ShapGaphicAttribute
thc
thi
bi
v
v cc nh bn trong mt TextLayout.
Chia mt khi vn bn thnh nhiu dng trong
cc i tng TextLayout m n khit bn trong
mt dong.
http://tailieuhay.com
96
c s
tng TextLayout
nh ngha cc thuc tnh quan trng v cc gi
tr c s dng cho vic to bng vn bn(text
TextHitInfo
rendering).
Miu t thng tin hit test cho cc k t trong mt
TextLayout
i tng TextLayout
Thc thi:Cloneable
Cung cp mt s biu din ha c nh ca
cc d liu k t c nh kiu,bao gm c
cc vn bn hai chiu.
97
danh
sch
cc
logical
name,hy
gi
java.awt.Toolkit.getFontList.
Mt family name ca i tng Font l tn trong h font m n nh
ngha cch thit k vic in thng qua mt s b mt,chng hn nh kiu
ch Helvetica.Bn ly h tn font bng cch s dng phng thc
getFamily.
Mt font face name ca i tng Font dng m ch kch thc
tht ca font c ci t trong h thng. l tn m bn c th s dng
khi ch r mt kiu font trong Java 2 SDK.N cng thng c m ch
cho font name.Bn c th ly tn font bng cch gi phng thc
geFontName. xc nh kiu font no c s dng trong h thng,bn
c th gi phng thc GraphicsEnvironment.getAllFonts.
Bn c th truy xut cc thng tin v mt i tng Font bng vic
gi phng thc getAttributes. Cc thuc tnh ca Font bao gm tn,kch
c font,transform,c tnh font nh hnh dng font.
Mt i tng LineMetrics ng gi cc thng tin v cc s o ca
Font,nh ascent,descent v khong cch gia cc dng ch.
http://tailieuhay.com
98
4.3
http://tailieuhay.com
99
http://tailieuhay.com
100
http://tailieuhay.com
101
102
Hnh 4-5
Bidirectional Text
http://tailieuhay.com
103
http://tailieuhay.com
104
http://tailieuhay.com
105
Dual Carets
http://tailieuhay.com
106
http://tailieuhay.com
107
cung
cp
cc
phng thc
getNextRightHit
and
Hnh 4-9
http://tailieuhay.com
108
- vi visual
http://tailieuhay.com
109
Hnh 4-10
Hnh 4-11
http://tailieuhay.com
110
http://tailieuhay.com
111
http://tailieuhay.com
112
Hnh 4-12
http://tailieuhay.com
Angled Carets
113
vo
khong
trng
thm
vo,phng
thc
caretShapes
layout.getCaretShapes(hit);
g2.setColor(PRiMARY_CARET_COLOR);
g2.draw(caretShapes[0]);
if
(caretShapes[1]
!=
null){
g2.setColor(SECONDARY_CARET_COLOR);
g2.draw(caretShapes[1]);
}
4.4.3 Di chuyn du nhc.
Bn cng c th s dng lp TextLayout xc nh kt qu ca
vic thm vo cc khong trng khi ngi s dng n cc phm mi tn
tri hoc phi.Da vo i tng TextHitinfo,n cho ta bit v tr hin ti
ca khong trng thm vo,phng thc getNextRightHit tr v kiu i
tng TextHitinfo m n cho bit chnh xc v tr ca khong trng thm
http://tailieuhay.com
114
newinsertionOffset
layout.getNextRightHit(insertionOffset);
if
(newinsertionOffset
!=
null)
{
Shape[]
caretShapes
layout.getCaretShapes(newinsertionOffset);
//
draw
carets
...
insertionOffset
newinsertionOffset;
hit
layout.hitTestChar(x,
insertindex
hit.getinsertindex();
http://tailieuhay.com
y);
115
Shape
highlightRegion
layout.getLogicalHighlightShape(hit1,
hit2);
graphics.setColor(HiGHLiGHT_COLOR);
graphics.fill(highlightRegion);
graphics.drawString(layout,
0,
0);
http://tailieuhay.com
116
graphics.drawString(layout,
Rectangle2D
bounds
0,
0);
layout.getBounds();
graphics.drawRect(bounds.getX()-1,
bounds.getY()-1,
bounds.getWidth()+2,
bounds.getHeight()+2);
http://tailieuhay.com
117
/*
* FontSelection.java
* 1.0
* 12/03/06
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.itemEvent;
import java.awt.event.itemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
http://tailieuhay.com
118
/*
* Applet nay hien thi mot xau voi lua chon cua
nguoi su dung.
*/
public
class
FontSelection
extends
JApplet
implements itemListener {
/**
*
*/
private static final long serialVersionUiD =
5469031020823166920L;
FontPanel fontC;
int index = 0;
String fontchoice = "La chn Font";
http://tailieuhay.com
119
@SuppressWarnings("unchecked")
public void init() {
getContentPane().setLayout(new
BorderLayout());
topPanel.setLayout(new BorderLayout());
fontPanel.setLayout(new
GridLayout(2,
sizePanel.setLayout(new
GridLayout(2,
stylePanel.setLayout(new
GridLayout(2,
1));
1));
1));
sizeAndStylePanel.setLayout(new
BorderLayout());
topPanel.add(BorderLayout.WEST,
fontPanel);
http://tailieuhay.com
120
sizeAndStylePanel.add(BorderLayout.CENTER,
stylePanel);
topPanel.add(BorderLayout.CENTER,
sizeAndStylePanel);
getContentPane().add(BorderLayout.NORTH,
topPanel);
fontLabel.setHorizontalAlignment(JLabel.CENTER);
fontPanel.add(fontLabel);
sizeLabel.setHorizontalAlignment(JLabel.CENTER);
sizePanel.add(sizeLabel);
121
styleLabel.setHorizontalAlignment(JLabel.CENTER);
stylePanel.add(styleLabel);
GraphicsEnvironment
gEnv
GraphicsEnvironment
.getLocalGraphicsEnvironment();
String
envfonts[]
gEnv.getAvailableFontFamilyNames();
Vector vector = new Vector();
for (int i = 1; i < envfonts.length; i+
+) {
vector.addElement(envfonts[i]);
}
fonts = new JComboBox(vector);
fonts.setMaximumRowCount(9);
fonts.additemListener(this);
fontchoice = envfonts[0];
fontPanel.add(fonts);
sizes
new
JComboBox(new
Object[]
styles
new
JComboBox(new
Object[]
122
getContentPane().add(BorderLayout.CENTER,
fontC);
}
(e.getStateChange()
!=
itemEvent.SELECTED) {
return;
}
if (list == fonts) {
fontchoice
(String)
fonts.getSelecteditem();
} else if (list == styles) {
index = styles.getSelectedindex();
stChoice = index;
} else {
http://tailieuhay.com
123
(String)
sizes.getSelecteditem();
}
fontC.changeFont(fontchoice,
stChoice,
siChoice);
}
WindowAdapter()
{
public
void
windowClosing(WindowEvent e) {
System.exit(0);
}
});
JApplet
fontSelection
new
FontSelection();
f.getContentPane().add(fontSelection,
BorderLayout.CENTER);
fontSelection.init();
f.setSize(new Dimension(550, 250));
f.setVisible(true);
}
http://tailieuhay.com
124
public FontPanel() {
thisFont = new Font("Arial", Font.PLAiN,
10);
}
public
void
changeFont(String
f,
int
st,
String si) {
integer newSize = new integer(si);
int size = newSize.intValue();
thisFont = new Font(f, st, size);
repaint();
}
g2.setColor(Color.darkGray);
g2.setFont(thisFont);
http://tailieuhay.com
125
kiu ch.";
FontMetrics
metrics
g2.getFontMetrics();
int width = metrics.stringWidth(change);
int height = metrics.getHeight();
g2.drawString(change, w / 2 - width / 2,
h / 2 - height / 2);
}
}
Kt qu ca chng trnh:
http://tailieuhay.com
126
http://tailieuhay.com
127
Description
M t cc thao tc vo n ra n thc hin
trn i tng Bufferedimage. c ci t
bi
AffineTransformOp,
ColorConvertOp,
RasterOp
BandCombineOp,
WritableRenderedImag
Rasters
M rng Renderedimage
TileObserver
thi
chnh
sa
ca
mt
WritableRenderedimage thay i.
.
Clases
Bufferedimage
Description
M rng image ci t WriteableRenderedimage
Mt nh vi mt b m d liu c th truy cp.
http://tailieuhay.com
128
DataBuffer
DataBufferByte
liu
im. Mi mng c gi l bank
M rng DataBuffer. Mt b m d liu cha cc
byte d liu. ( dng trong Java Advanced
DataBufferint
imaging API)
M rng DataBuffer (Final))
Mt b m d liu cha d liu s nguyn (a
DataBufferShort
DataBufferUShort
liu v cc im bin ca
LookupTable
n tc ng n gi tr
ca im trong b lc ConvolveOP
M rng Object
Mt bng nh x cc gi tr t d liu im n
Raster
bng ti cc gi tr mu.
Mt mng cc im gc t bn c th nhn v
cc d liu im. Mt Raster cha mt DataBuffer
ShortLookupTable
v mt SampleModel.
M rng LookupTable
Mt bng tham chiu cha cc d liu s nguyn
WritableRaster
short
M rng Raster
Mt Raster c th chnh sa.
http://tailieuhay.com
129
Description
Ci t : BufferedimageOp, RasterOp
Mt lp nh ngha mt bin i affine thc
hin mt s nh x tuyn tnh t cc to 2D
trong mt nh ngun hoc Raster sang cc to
2D trong nh ch hoc Raster. Lp ny c th thc
hin c nh x song nh v cc php ton bin i
BandCombineOp
trong mt Raster.
BufferedimageFilter M rng imageFilter
Mt imageFilter cung cp mt cch n gin ca
vic sng mt BufferedimageOp(ton t mt
ngun
ColorConvertOp
/mt
ch
n)
lc
mt
ConvolveOp
im trong nh ngun.
Ci t BufferedimageOp, RasterOp
Dng mt Kernel thc hin ci thin nh ngun.
Mt s ci thin l mt s tao tc khng gian ni
cc im cn bin vo c nhn bi bi mt gi
tr Kernel to gi tr ca im ra. Kernel nh
ngha mt cch ton hc quan h gia cc im
trong quan h lng ging trung gian ca im vo
v im ra.
http://tailieuhay.com
130
Ci t BufferedimageOp, RasterOp
Thc hin thao tc tham chiu t ngun ti ch.
Vi cc Raster, cc thao tc tham chiu trn cc gi
tr mu, cc Bufferedimage, thao tc tham chiu
RescaleOp
Clases
BandedSampleModel
Description
M rng
ComponentSampleModel
(Final)
Cung cp truy cp d liu nh cha
ging nh cc mu cha nh nhng
di (bands) trong cc bank ring bit
ca DataBuffer. Mt im bao gm
ComponentSampleModel
mt mu t mi di (band)
M rng SampleModel
Cung cp truy cp ti d liu nh cha
vi mt mu ca mt im tp trung
trong mi phn t ring bit ca
DataBuffer. Cc loi chn im khc
MultiPixelPackedSampleModel
PixelinterleavedSampleModel
nhau c h tr
M rng SampleModel
M rng ComponentSampleModel
Cung cp truy nhp ti d liu nh
cha d liu mu cho mi im trong
http://tailieuhay.com
131
SampleModel
Clases
ColorModel
Description
Ci t lp trong sut nh ngha cc
phng thc cho vic chuyn i t cc gi
tr im nh ti cc thnh phn mu nh ,
ComponentColorModel
http://tailieuhay.com
132
ColorModel mc nh c tr v bi
ColorModel.getRGBdefault
DirectColorModel.
PackedColorModel
nh
mt
indexColorModel
Extends: ColorModel
M rng ColorModel.
Mt ColorModel tru tng biu din cc
gi tr im c cc thnh phn nhng trc
tip
trong
cc
bit
ca
DirectColorModel
mt
im.
rng
PackedColorModel h tr cc im cha
SampleModel
Clases
imagingOpException
Description
M rng RuntimException.
a ra nu mt trong cc phng thc
BufferedimageOp hoc RasterOp khng th
RasterFormatException
http://tailieuhay.com
x l nh.
M rng RuntimException.
133
5.2
Hnh 5-1
Bufferedimage v cc lp h tr.
134
135
http://tailieuhay.com
136
Using Bufferedimages
Lp Bufferedimage l lp chnh h tr mode to nh trung gian. N
public
Graphics2D
createDemoGraphics2D(Graphics
Graphics2D
g2
int
width
int
height
if
(offimg
width
g)
null;
getSize().width;
=
==
getSize().height;
null
||
offimg.getWidth()
!=
||
offimg.getHeight()
http://tailieuhay.com
!=
height)
{
137
(Bufferedimage)
createimage(width,
height);
}
if
(offimg
g2
!=
null)
offimg.createGraphics();
g2.setBackground(getBackground());
}
//
..
width,
clear
canvas
.. g2.clearRect(0,
0,
height);
return
}
Bn cng c th to mt Bufferedimage trng trong b nh dng
mt vi hm to c cung cp.
5.3.2 Drawing in an Offscreen Buffer
Lp Bufferedimage c th uc ng chun b cc phn t ho
khng hin th (offscreen )sau copy chng ra mn hnh. K thut ny
hu ch c bit khi mt graphic phc tp hoc dng lp li. V d, nu
bn mun hin th`hnh nh tinh vi trong vi ln, bn c th v n mt ln
trong b m offscreen v sau copy n ti cc v tr khc nhau trn ca
s. Bng vic v cc hnh mt ln v vic sao chp n bn c th hin th
ho nhanh hn.
Java.awt package c kh nng dng cc b m offsceam bi iu
ny bn v mt i tng nh cng cch m bn v ra ca s. Tt c cc
http://tailieuhay.com
138
139
http://tailieuhay.com
140
void
Graphics2D
update(Graphics
g2
g){
(Graphics2D)g;
getSize();
if(firstTime){
Dimension
dim
int
dim.width;
int
dim.height;
area
bi
big
=
=
new
Rectangle(dim);
(Bufferedimage)createimage(w,
=
h);
bi.createGraphics();
http://tailieuhay.com
141
h/2-25);
BasicStroke(8.0f));
false;
Clears
the
}
//
previously
rectangle
was
drawn. big.setColor(Color.white);
big.clearRect(0,
0,
//
fills
Draws
that
and
rectangle
area.width,
the
to
area.height);
newly
positioned
the
buffer.
big.setPaint(strokePolka);
big.draw(rect);
big.setPaint(fillPolka);
big.fill(rect);
//
Draws
the
buffered
screen. g2.drawimage(bi,
0,
image
0,
to
the
this);
}
5.3.3 Manipulating Bufferedimage Data Directly
Cng vi vic v nh trc tip trong Bufferedimage, bn c th truy
cp trc tip v x l d liu im nh trong 2 cch. Nhng cch ny hu
ch nu vn ang ci t giao din b lc BufferedimageOp nh c
m t trong chng x l v ci thin nh.
Bn cng c th dng phng thc Bufferedimage.setRGB t
trc tip gi tr ca mt im hoc mt mng cc im ti mt gi tr
RGB xc nh. Ch rng, khng c s lay ng khi bn modify cc
http://tailieuhay.com
142
public
void
paint(Graphics
if
(getSize().width
getSize().height
<=
g)
<=
||
0)
return;
Graphics2D
if
g2
(offimg
!=
(Graphics2D)
null
g2.drawimage(offimg,
&&
0,
g;
isShowing())
0,
this);
}
}
Chng trnh v d:
http://tailieuhay.com
143
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.image.*;
public class BufferedShapeMover extends Applet {
static protected Label label;
public void init() {
setLayout(new BorderLayout());
add(new BSMCanvas());
label = new Label("t hnh ch nht ny
xung quanh vng frame.");
add("South", label);
}
public static void main(String s[]) {
Frame
new
Frame("BufferedShapeMover");
f.addWindowListener(new
WindowAdapter()
{
public
void
windowClosing(WindowEvent e) {
System.exit(0);
}
});
http://tailieuhay.com
144
applet
new
BufferedShapeMover();
f.add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(550, 250));
f.show();
}
}
class
BSMCanvas
extends
Canvas
implements
MouseListener, MouseMotionListener {
Rectangle
rect
new
Rectangle(0,
0,
100,
50);
Bufferedimage bi;
Graphics2D big;
int last_x, last_y;
boolean firstTime = true;
TexturePaint fillPolka, strokePolka;
Rectangle area;
http://tailieuhay.com
145
new
Bufferedimage(5,
5,
Bufferedimage.TYPE_iNT_RGB);
big = bi.createGraphics();
big.setColor(Color.pink);
big.fillRect(0, 0, 7, 7);
big.setColor(Color.cyan);
big.fillOval(0, 0, 3, 3);
Rectangle r = new Rectangle(0, 0, 5, 5);
fillPolka = new TexturePaint(bi, r);
big.dispose();
bi
new
Bufferedimage(5,
5,
Bufferedimage.TYPE_iNT_RGB);
big = bi.createGraphics();
big.setColor(Color.cyan);
big.fillRect(0, 0, 7, 7);
big.setColor(Color.pink);
big.fillOval(0, 0, 3, 3);
r = new Rectangle(0, 0, 5, 5);
strokePolka = new TexturePaint(bi, r);
big.dispose();
}
http://tailieuhay.com
146
http://tailieuhay.com
147
e.getX(),
last_y + e.getY());
if (checkRect()) {
BufferedShapeMover.label.setText("Hnh
ch
nht v tr : "
http://tailieuhay.com
148
rect.getX()
"-
"
rect.getY());
} else {
BufferedShapeMover.label
.setText("ng c gng a
hnh ra ngoi frame.");
}
repaint();
}
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
if (firstTime) {
Dimension dim = getSize();
int w = dim.width;
int h = dim.height;
area = new Rectangle(dim);
bi = (Bufferedimage) createimage(w,
h);
big = bi.createGraphics();
rect.setLocation(w / 2 - 50, h / 2 25);
big.setStroke(new
BasicStroke(8.0f));
http://tailieuhay.com
149
0,
area.width,
area.height);
big.setPaint(strokePolka);
big.draw(rect);
big.setPaint(fillPolka);
big.fill(rect);
g2.drawimage(bi, 0, 0, this);
}
boolean checkRect() {
if (area == null) {
return false;
}
if
(area.contains(rect.x,
rect.y,
100,
50)) {
return true;
}
int new_x = rect.x;
int new_y = rect.y;
if ((rect.x + 100) > area.width) {
new_x = area.width - 99;
}
if (rect.x < 0) {
http://tailieuhay.com
150
http://tailieuhay.com
151
liu
nh
khng
th
hin
DataBuffer.
Phng
thc
http://tailieuhay.com
152
http://tailieuhay.com
153
http://tailieuhay.com
154
http://tailieuhay.com
155
ColorConvertOp,
ConvolveOp,
LookupOp,
http://tailieuhay.com
156
float[]
-1.0f,
0.0f,
elements
4.f,
-1.0f,
0.0f,
-1.0f,
0.0f,
-1.0f,
0.0f};
...
Bufferedimage
bimg
new
Bufferedimage(bw,bh,Bufferedimage.TYPE_iNT_RGB);
Kernel
kernel
new
Kernel(3,
3,
elements);
ConvolveOp
cop
new
ConvolveOp(kernel,
ConvolveOp.EDGE_NO_OP, null);
cop.filter(bi,bimg);
Hnh 5 -5 demo x l bng tham chiu. X l bng tham chiu c th
c dng thay cho cc thnh phn ring l ca mt im.
http://tailieuhay.com
157
Hnh 5-5
X l Lookup-Table
reverse[]
(int
j=0;
new
byte[256];
j<200;
j++){
reverse[j]=(byte)(256-j);
}
ByteLookupTable
blut=new
ByteLookupTable(0,
reverse);
LookupOp
lop
new
LookupOp(blut,
null);
lop.filter(bi,bimg);
Hnh 5-6 minh ho rescaling. Rescaling c th tng hoc gim cng
ca tt c cc im. Rescaling c th c dng tng di ng ca
cc nh t nhin khc, a ra chi tit trong cc vng t nhin hoc
phng.
http://tailieuhay.com
158
Hnh 5-6
Rescaling
rop
new
RescaleOp(1.5f,
1.0f,
null);
rop.filter(bi,bimg);
5.8.1 Using an image Processing Operation
Convolution l qu trnh bn di hu ht cc thot ton lc khng
gian. Convolution la qu trnh nh gi (weighting) hoc lm u
(averaging) gi tr ca mi im trong mt nh vi cc ga tr im ln
cn. iu ny cho php mi im ra c t bi ln cn trung gian
trong cch md c th c xc nh vi mt nhn (kernel)
Hnh 5 -7 minh ho Convolution
http://tailieuhay.com
159
weight
float[]
2D
1.0f/9.0f;
elements
new
float[9];
//
create
array
//
fill
the
elements for
(i
elements[i]
array
0;
with
i
<
nine
9;
equal
i++)
weight;
}
//
use
to
create
private
the
a
array
of
elements
as
argument
Kernel
Kernel
myKernel
new
Kernel(3,
3,
new
elements);
public
ConvolveOp
simpleBlur
ConvolveOp(myKernel);
//
sourceimage
of
Bufferedimage
and
destimage
simpleBlur.filter(sourceimage,
blur
the
are
instances
destimage)
//
image
160
http://tailieuhay.com
161
Hnh 5-8
elements
5.f,
0.0f,
-1.0f,
0.0f,
-1.0f,
-1.0f,
0.0f };
...
Kernel
kernel
ConvolveOp
cop
new
=
Kernel(3,3,elements);
new
ConvolveOp(kernel,
ConvolveOp.EDGE_NO_OP,
null);
cop.filter(bi,bimg);
http://tailieuhay.com
162
Chng 6
Mu sc
http://tailieuhay.com
163
Description
Identifies the color space of a Color object,
Image, BufferedImage, or GraphicsDevice.
Has methods to transform between RGB and
ICC_ColorSpace
ICC_Profile
ICC_ProfileGray
Format Specification.
Extends: ICC_Profile
ICC_ProfileRGB
http://tailieuhay.com
164
http://tailieuhay.com
165
http://tailieuhay.com
166
167
thch
hp
cho
vic
nh
ngha
mt
gi
sRGB(tham
kho
http://
www.
W3.
http://tailieuhay.com
168
http://tailieuhay.com
169
170
http://tailieuhay.com
171
Chng 7
In n
v stapling.
4. In vi tt c cc platform, c Windows v Solaris. iu ny bao
gm my in c gn trc tip vi my tnh cng nh vi
platform software cho php truy cp s dng cc giao thc in
qua mng.
Khng phi tt c cc tnh nng c b tr v c ci t trong
in n vi Java 2 SDK API. Nhng API s c m rng b tr cho
tt c cc thuc tnh ny cc bn release trong tng lai.
7.1 Cc giao din v cc lp
http://tailieuhay.com
172
Description
The Printable interface is implemented by each page
painter, the application class(es) called by the
printing system to render a page. The system calls the
page painters print method to request that a page be
Pageable
rendered.
The Pageable interface is implemented by a
document that is to be printed by the printing system.
Through the Pageable methods, the system can
determine the number of pages in the document, the
format to use for each page, and the page painter to
PrinterGraphics
Printable
Class
Book
Description
Implements: Pageable
Represents a document in which pages can have
different page
formats and page painters. This class uses the
Pageable
PageFormat
http://tailieuhay.com
PageFormat.
Describes the physical characteristics of a piece of
PrinterJob
paper.
The principal class that controls printing. The
application calls PrinterJob methods to set up a job,
display a print dialog to the user (optional), and to
print the pages in the job.
Cc nh ngha v in
Java Printing API da trn m hnh in callback trong h thng in,
khng phi ng dng s iu khin khi cc trang c in. ng dng cung
cp thng tin v ti liu c in v h thng in s yu cu ng dng y
ti cc trang in khi n cn chng.
H thng in c th yu cu rng mt trang in ring bit c a ra
hn mt ln hoc yu cu cc trang c a ra ngoi theo th t. ng
dng phi cho php to ra hnh nh ng ca trang, khng ph thuc
trang no h thng in yu cu. Trong kha cnh , h thng in ging nh
window toolkit, c th yu cu cc thnh phn v li bt c lc no
trong th t no.
M hnh in callback mm do hn cc m hnh ng dng iu khin in
truyn thng v b tr cho vic in trn di rng hn cc h thng v cc
my in.
http://tailieuhay.com
174
http://tailieuhay.com
175
http://tailieuhay.com
176
177
http://tailieuhay.com
178
http://tailieuhay.com
179
mt
tng
PrinterJob
mi
bi
vic
gi
PrinterJob.getPrintJob
Xc nh PageFormat dng cho vic in. Mt PageFormat mc
nh c th ly v bi gi hm defaultPage. hoc bn c th gi
mt hp thoi cho php ngi dng xc nh nh dng .
Xc nh cc c im ca cng vic in cho PrinterJob. Cho
http://tailieuhay.com
180
http://tailieuhay.com
181
y mi trang ra in.
2. To mt PrinterJob.
3. Gi setPrintable thng bo cho PrinterJob cch thc in ti liu.
java.awt.*;
public
class
import
java.awt.print.*;
SimplePrint
implements
Printable
http://tailieuhay.com
182
static
Font
fnt
new
Font("Helvetica",Font.PLAiN,24);
public
static
void
main(String[]
args)
{
//
Get
PrinterJob
//
PrinterJob
job
Specify
of
PrinterJob.getPrinterJob();
the
Printable
SimplePrint
is
an
instance
job.setPrintable(new
SimplePrint());
//
Put
up
the
dialog
box
if
(job.printDialog())
{
//
the
job
cancel
printing
try
job.print();
catch
(Exception
handle
/*
if
the
user
didn't
e)
exception
*/
}
System.exit(0);
}
public
int
int
print(Graphics
g,
PageFormat
pf,
pageindex)
throws
PrinterException
http://tailieuhay.com
183
pageindex
numbers
to
if
(pageindex
to
corresponds
to
page
5.
>=
5)
return
Printable.NO_SUCH_PAGE;
g.setFont(fnt);
g.setColor(Color.green);
g.drawString("Page
"
(pageindex+1),
100,
100);
return
Printable.PAGE_EXiSTS;
}
}
java.awt.*;
public
class
import
java.awt.print.*;
SimplePrint2D
implements
Printable
{
private
static
Font
fnt
new
Font("Helvetica",Font.PLAiN,24);
http://tailieuhay.com
184
Paint
pnt
100f,
Color.red,
136f,
100f,
public
new
Color.green,
static
void
GradientPaint(100f,
true);
main(String[]
args)
{
//
Get
PrinterJob
//
of
PrinterJob
job
Specify
the
PrinterJob.getPrinterJob();
Printable
is
an
instance
SimplePrint2D
job.setPrintable(new
up
the
SimplePrint2D());
//
Put
dialog
if
(job.printDialog())
box
{
//
the
job
cancel
printing
try
job.print();
catch
*/
(Exception
e)
if
the
user
didn't
}
{
/*
handle
exception
}
System.exit(0);
}
public
int
int
print(Graphics
g,
PageFormat
pf,
pageindex)
throws
PrinterException
{
//
pageindex
numbers
http://tailieuhay.com
to
to
corresponds
to
page
5.
185
(pageindex
>=
5)
return
Printable.NO_SUCH_PAGE;
Graphics2D
//
Use
the
g2
=
font
(Graphics2D)
defined
g;
above
g2.setFont(fnt);
//
Use
the
gradient
color
defined
above
g2.setPaint(pnt);
g2.drawString("Page
"
(pageindex+1),
100f,
100f);
return
Printable.PAGE_EXiSTS;
}
}
l i
s cho hm main.
Lp
java.awt.*;
http://tailieuhay.com
186
java.awt.print.*;
import
java.io.*;
public
class
PrintListing
{
public
static
void
main(String[]
args)
{
//
Get
PrinterJob
PrinterJob
job
//
user
Ask
PrinterJob.getPrinterJob();
for
page
format
(e.g.,
portrait/landscape)
PageFormat
pf
job.pageDialog(job.defaultPage());
//
//
Specify
the
Printable
PrintListingPainter;
is
an
also
instance
provide
of
given
PageFormat
job.setPrintable(new
PrintListingPainter(args[0]),
//
pf);
copy
job.setCopies(1);
//
Put
up
the
dialog
if
(job.printDialog())
box
{
//
the
job
cancel
printing
try
job.print();
catch
*/
(Exception
e)
if
the
user
didn't
}
{
/*
handle
exception
http://tailieuhay.com
187
PrintListingPainter
implements
Printable
{
private
RandomAccessFile
private
String
private
Font
Font.PLAiN,
fileName;
fnt
new
Font("Helvetica",
10);
private
int
private
long
private
boolean
public
raf;
rememberedPageindex
rememberedFilePointer
-1;
rememberedEOF
PrintListingPainter(String
-1;
false;
file)
{
fileName
file;
try{
//
Open
raf
file
new
RandomAccessFile(file,
"r");
}
catch
(Exception
e)
rememberedEOF
true;
}
}
public
int
int
print(Graphics
g,
PageFormat
pf,
pageindex)
throws
PrinterException
http://tailieuhay.com
188
For
catching
if
(pageindex
iOException
!=
rememberedPageindex)
{
//
First
time
we've
rememberedPageindex
//
if
visited
this
page
encountered
pageindex;
EOF
on
previous
page,
done
if
(rememberedEOF)
return
Printable.NO_SUCH_PAGE;
//
Save
current
position
rememberedFilePointer
in
input
file
raf.getFilePointer();
}
else
raf.seek(rememberedFilePointer);
g.setColor(Color.black);
g.setFont(fnt);
int
(int)
pf.getimageableX()
10;
int
(int)
pf.getimageableY()
12;
//
Title
line
g.drawString("File:
"
Generate
imageable
y
fileName
",
page:
(pageindex+1),
//
"
+=
while
x,
as
y);
many
lines
as
will
fit
in
area
36;
(y
12
<
pf.getimageableY()
+pf.getimageableHeight())
{
http://tailieuhay.com
189
line
(line
==
raf.readLine();
null)
{
rememberedEOF
true;
break;
}
g.drawString(line,
y
+=
x,
y);
12;
}
return
Printable.PAGE_EXiSTS;
}
catch
(Exception
e)
return
Printable.NO_SUCH_PAGE;}
}
}
Giao din ca chng trnh:
http://tailieuhay.com
190
http://tailieuhay.com
191
http://tailieuhay.com
192
java.awt.*;
import
java.awt.print.*;
public
class
SimplePrintBook
implements
Printable
{
private
static
Font
fnt
new
Font("Helvetica",Font.PLAiN,24);
public
static
void
main(String[]
args)
{
//
Get
PrinterJob
PrinterJob
//
Set
Book
job
book
up
bk
new
PrinterJob.getPrinterJob();
Book();
bk.append(new
SimplePrintBook(),
job.defaultPage(),
//
Pass
the
5);
book
to
the
PrinterJob
job.setPageable(bk);
//
Put
up
the
dialog
if
(job.printDialog())
box
{
//
the
job
cancel
printing
try
job.print();
catch
*/
(Exception
e)
if
the
user
didn't
}
{
/*
handle
exception
}
System.exit(0);
}
http://tailieuhay.com
193
public
int
int
print(Graphics
g,
PageFormat
pf,
pageindex)
throws
PrinterException
{
g.setFont(fnt);
g.setColor(Color.green);
g.drawString("Page
"
(pageindex+1),
100,
100);
return
Printable.PAGE_EXiSTS;
}
}
Giao din ca chng trnh:
194
java.awt.*;
import
java.awt.print.*;
public
class
PrintBook
{
public
static
void
main(String[]
args)
{
//
Get
PrinterJob
PrinterJob
job
//
Create
PageFormat
PrinterJob.getPrinterJob();
landscape
pfl
page
format
job.defaultPage();
pfl.setOrientation(PageFormat.LANDSCAPE);
//
Set
Book
up
bk
book
new
bk.append(new
Book();
PaintCover(),
pfl);
bk.append(new
PaintContent(),
job.defaultPage(),
//
Pass
the
2);
book
to
the
PrinterJob
job.setPageable(bk);
//
Put
up
the
dialog
if
(job.printDialog())
box
{
//
the
job
cancel
printing
try
job.print();
catch
*/
(Exception
e)
if
the
user
didn't
}
{
/*
handle
exception
}
System.exit(0);
http://tailieuhay.com
195
PaintCover
implements
Printable
{
Font
fnt
new
Font("Helvetica-Bold",
Font.PLAiN,
72);
public
print(Graphics
int
int
g,
PageFormat
pf,
pageindex)
throws
PrinterException
{
g.setFont(fnt);
g.setColor(Color.black);
int
yc
(int)
(pf.getimageableY()
pf.getimageableHeight()/2);
g.drawString("Widgets,
return
inc.",
72,
yc+36);
Printable.PAGE_EXiSTS;
}
}
class
PaintContent
implements
Printable
{
public
int
int
print(Graphics
g,
PageFormat
pf,
pageindex)
throws
PrinterException
{
Graphics2D
http://tailieuhay.com
g2
(Graphics2D)
g;
196
useRed
int
xo
(int)
pf.getimageableX();
int
yo
(int)
pf.getimageableY();
//
Fill
page
with
alternating
for
0;
red
circles
green
(int
&
for
0;
pf.getimageableWidth();
(int
pf.getimageableHeight();
or
+=
x+28
<
y+28
<
36)
0;
squares,
+=
36)
{
if
(useRed
else
0)
g.setColor(Color.red);
g.setColor(Color.green);
useRed
if
==
(pageindex
yo+y+4,
else
28,
useRed;
%
==
0)
g.drawRect(xo+x+4,
28);
g.drawOval(xo+x+4,
yo+y+4,
28,
28);
}
return
Printable.PAGE_EXiSTS;
}
Giao din cua chng trnh:
http://tailieuhay.com
197
V d in mt mt chng trnh.
import java.awt.geom.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.print.PrinterJob;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
public
class
ShapesPrint
extends
JPanel
http://tailieuhay.com
198
static
BasicStroke
stroke
new
BasicStroke(2.0f);
final
static
BasicStroke
wideStroke
new
BasicStroke(8.0f);
final static float dash1[] = { 10.0f };
final
static
BasicStroke
dashed
new
BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOiN_MiTER, 10.0f, dash1, 0.0f);
final
static
JButton
button
new
JButton("in");
public ShapesPrint() {
setBackground(bg);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
http://tailieuhay.com
199
printJob
PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog()) {
try {
printJob.print();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
drawShapes(g2);
}
public void drawShapes(Graphics2D g2) {
Dimension d = getSize();
int gridWidth = 400 / 6;
int gridHeight = 300 / 2;
int rowspacing = 5;
int columnspacing = 7;
int
rectWidth
gridWidth
rectHeight
gridHeight
columnspacing;
int
rowspacing;
http://tailieuhay.com
200
Line2D.Double(x,
Rectangle2D.Double(x,
y,
rectWidth, rectHeight));
x += gridWidth;
g2.setStroke(dashed);
g2
.draw(new
RoundRectangle2D.Double(x,
y,
rectWidth,
rectHeight,
10, 10));
x += gridWidth;
g2.setStroke(wideStroke);
g2.draw(new
Arc2D.Double(x,
y,
Ellipse2D.Double(x,
y,
rectWidth, rectHeight));
x += gridWidth;
http://tailieuhay.com
201
polygon
new
GeneralPath(GeneralPath.WiND_EVEN_ODD,
x1Points.length);
polygon.moveTo(x1Points[0],
y1Points[0]);
for
(int
index
1;
index
<
x1Points.length; index++) {
polygon.lineTo(x1Points[index],
y1Points[index]);
}
;
polygon.closePath();
g2.draw(polygon);
x = 85;
y += gridHeight;
int x2Points[] = { x, x + rectWidth, x,
x + rectWidth };
int y2Points[] = { y, y + rectHeight, y
+ rectHeight, y };
GeneralPath
polyline
new
GeneralPath(GeneralPath.WiND_EVEN_ODD,
x2Points.length);
polyline.moveTo(x2Points[0],
y2Points[0]);
http://tailieuhay.com
202
(int
index
1;
index
<
x2Points.length; index++) {
polyline.lineTo(x2Points[index],
y2Points[index]);
}
;
g2.draw(polyline);
x += gridWidth;
g2.setPaint(red);
g2.fill(new
Rectangle2D.Double(x,
y,
rectWidth, rectHeight));
g2.setPaint(fg);
x += gridWidth;
GradientPaint
redtowhite
new
y,
rectWidth,
rectHeight,
10, 10));
g2.setPaint(fg);
x += gridWidth;
g2.setPaint(red);
g2.fill(new
Arc2D.Double(x,
y,
http://tailieuhay.com
203
new
GradientPaint(x,
y,
Ellipse2D.Double(x,
y,
rectWidth, rectHeight));
g2.setPaint(fg);
x += gridWidth;
int x3Points[] = { x, x + rectWidth, x,
x + rectWidth };
int y3Points[] = { y, y + rectHeight, y
+ rectHeight, y };
GeneralPath
filledPolygon
new
GeneralPath(GeneralPath.WiND_EVEN_ODD,
x3Points.length);
filledPolygon.moveTo(x3Points[0],
y3Points[0]);
for
(int
index
1;
index
<
x3Points.length; index++) {
filledPolygon.lineTo(x3Points[index],
y3Points[index]);
}
;
filledPolygon.closePath();
g2.setPaint(red);
g2.fill(filledPolygon);
g2.setPaint(fg);
g2.draw(filledPolygon);
http://tailieuhay.com
204
void
windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowClosed(WindowEvent
e) {
System.exit(0);
}
};
JFrame f = new JFrame();
f.addWindowListener(l);
JPanel panel = new JPanel();
panel.add(button);
http://tailieuhay.com
205
http://tailieuhay.com
206
Phn 2
Lp trnh ha vi Java 3D
http://tailieuhay.com
207
CHNG 1
NHP MN LP TRNH TRN JAVA 3D
http://tailieuhay.com
208
209
210
211
http://tailieuhay.com
212
http://tailieuhay.com
213
http://tailieuhay.com
214
215
http://tailieuhay.com
216
217
http://tailieuhay.com
218
219
ViewingPlatform,
lp
ny
phng
thc
220
http://tailieuhay.com
221
222
http://tailieuhay.com
223
SimpleUniverse
is
Convenience
Utility class
http://tailieuhay.com
224
simpleU
new
SimpleUniverse(canvas3D);
// This will move the ViewPlatform back
a bit so the
// objects in the scene can be viewed.
simpleU.getViewingPlatform().setNominalViewingTr
ansform();
simpleU.addBranchGraph(scene);
} // end of HelloJava3Da (constructor)
Ta thy bc 3 ca cng thc ny l to th nhnh ni dung. Mt
th nhnh ni dung c to trong on m 1-2. l th nhnh ni
dung n gin nht c th. N cha mt i tng ha tnh l hnh
lp phng mu. Hnh ny c t v tr ban u trong h thng th
gii o. Vi v tr v hng nhn ny, hnh lp phng ny xut hin nh
hnh ch nht khi c dng ln.
public BranchGroup createSceneGraph() {
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
objRoot.addChild(new ColorCube(0.4));
return objRoot;
http://tailieuhay.com
225
//
end
of
CreateSceneGraph
method
of
HelloJava3Da
thm
java.lang.Runnable,
java.applet.AppletStub,
java.applet.AppletContext.
Hm
MainFrame(java.applet.Applet applet, int width, int height)
To to i tng Mainframe cho php applet chy nh ng dng
c lp.
Tham s: Applet Hm to ca mt lp tha k t applet.
MainFrame cung cp AWT frame
public static void main(String[] args) {
Frame
frame
new
MainFrame(new
http://tailieuhay.com
226
http://tailieuhay.com
227
simpleU
new
SimpleUniverse(canvas3D);
// This will move the ViewPlatform back a bit so the
// objects in the scene can be viewed.
http://tailieuhay.com
228
simpleU.getViewingPlatform().setNominalViewingTransform();
simpleU.addBranchGraph(scene);
} // end of HelloJava3Da (constructor)
public BranchGroup createSceneGraph() {
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
objRoot.addChild(new ColorCube(0.4));
return objRoot;
} // end of CreateSceneGraph method of HelloJava3Da
// The following allows this to be run as an application
// as well as an applet
public static void main(String[] args) {
Frame frame = new MainFrame(new HelloJava3Da(), 256,
256);
} // end of main (method of HelloJava3Da)
} // end of class HelloJava3Da
Kt qu ca chng trnh chy l:
http://tailieuhay.com
229
BranchGroup constructor
BranchGroup ()
Instance ca BranchGroup c coi l gc ca mt nhnh th,
mi i tng BranchGroup ch l i tng c th chn vo tp cc i
tng ca Locales.
http://tailieuhay.com
230
Lp Transform3D
i tng Transform3D i in cho vic bin hnh ca hnh hc
3D nh dch v quay. Nhng i tng ny thng ch s dng to
mt i tng TransformGroup. u tin i Transform3D c
khi to, c kh nng lin kt vi cc i tng Transform3D khc.
Sau TransformGroup c khi to s dng Transform3D va
to.
Transform3D Default Constructor
Mi i tng tng quan khi thay i hnh dng thng qua mt ma
trn 4x4 vi cc im thc. i tng Transform3D khng c s
dng trong th khung cnh. N ch c dng ch ra s bin hnh
ca mt i tng TransformGroup.
Transform3D()
To i tng Transform3D m i din cho ma trn ban u
(khng c bin i)
Mt i tng Transform3D c th i din cho tnh tin, quay,
bin hnh theo quy m,hoc l kt hp cc phng php trn li. Khi c
hin tng quay, gc c th hin di dng radians. Mt vng quay
http://tailieuhay.com
231
Lp TransformGroup
y l lp con ca lp Group, mi instance ca TransformGroup
c s dng to th khung cnh v c mt tp cc i tng nt
con. i tng TransformGroup gi gi tr bin hnh. Vic bin hnh
thng c to trn i tng Transform3D vn khng phi l mt
i tng ca th khung cnh.
http://tailieuhay.com
232
Lp Vertor3f
L lp ton hc trong gi javax.vecmath nh ra mt vertor s
dng 3 im s thc. Cc i tng vertor thng c s dng ch
ra php bin hnh trong hnh hc. i tng Vertor3f khng c s
dng trc tip trong cu trc ca th khung cnh. Chng thng c
s dng ch ra cc c nh bin i.
Vector3f Constructors
Vector3f()
To v thit lp cc gi tr Vertor3f cho (0,0,0)
Vector3f(float x, float y, float z)
To v thit lp cc gi tr Vertor3f cho (x,y,z)
http://tailieuhay.com
233
http://tailieuhay.com
234
rotate
object
has
composited
transformation matrix
Transform3D rotate = new Transform3D();
Transform3D tempRotate = new Transform3D();
rotate.rotX(Math.PI/4.0d);
tempRotate.rotY(Math.PI/5.0d);
rotate.mul(tempRotate);
TransformGroup
objRotate
new
TransformGroup(rotate);
objRoot.addChild(objRotate);
objRotate.addChild(new ColorCube(0.4));
// Let Java 3D perform optimizations on this
scene graph.
objRoot.compile();
return objRoot;
}
Nh vy bn th nhnh ni dung c cc i tng nh hnh di,
ch l i tng BranchGroup bao gi cng l con ca mt Locale.
http://tailieuhay.com
235
Kt qu:
http://tailieuhay.com
236
http://tailieuhay.com
237
1.8.2 Kh nng
Mt khi th nhnh c lm cho sng v dch, h thng dng hnh
ca Java 3D chuyn th nhnh sang mt m t bn trong hiu qu hn,
qua cng tng cao hiu nng dng hnh.
Vic bin i qua m t bn trong c nhng tc ng khc nhau. Mt
trong s l c nh gi tr bin hnh v cc i tng trong th
khung cnh. Tr phi c ch ra chi tit ca chng trnh, th s khng c
kh nng thay i gi tr ca cc i tng th khung cnh sau khi
chng sng.
C nhng trng hp mt chng trnh vn cn kh nng thayi gi
tr ca chng trong mt i tng th khung cnh sau khi n sng.
V d nh vic thay i gi tr ca mt i tng TransformGroup to
hot ha. Mt danh sch cc tham s c th truy cp c v khi
ngi ta gi l nng lc (capability) ca mt i tng.
Mi i tng SceneGraphObject c mt tp cc bit nng lc. Gi
tr ca cc bit ny xc nh kh nng c th tn ti cho i tng sau khi
http://tailieuhay.com
238
tng
TransformGroup
cng
nh
vy.
tng
TransformGroup.
TransformGroup Capabilities
kh nng di y l mt trong nhng kh nng c nh ngha bi
TransformGroup. TransformGroup tha k rt nhiu bit kh nng ca
lp tin bi ca n l Group v Node. Cc kh nng nh set,reset hay
retrieve c ng ngha SceneGraphObject.
ALLOW_TRANSFORM_READ
Ch ra cc nt cho php truy cp ti thng tin bin hnh ca i tng
ca n.
ALLOW_TRANSFORM_WRITE
Cho php ghi ti thng tin bin hnh ca i tng ca n.
http://tailieuhay.com
239
http://tailieuhay.com
240
(RotationInterpolator),
kch
c(ScaleInterpolator),
mu
241
RotationInterpolator Constructor
RotationInterpolator(Alpha alpha, TransformGroup target)
Hm khi to ny s dng cc gi tr mc nh cho mt vi tham s
ca hnh vi mc nh khi to mt php quay y trn trc y,
bng i tng TransformGroup c ch ra bng hnh vi mc nh.
Tham s:
alpha thi gian hm thay i tham chiu
target i tng TransformGroup cn thay i
5 Alpha l mt lp trong Java 3D to ra cc hm bin i thi gian.
1.9.2 Cc hm bin i v thi gian: nh x mt hnh vi vi thi gian
Vic nh x mt i tng vi thi gian thng qua mt i tng Alpha.
Lp Alpha
Lp ny c s dng to hm bin i theo thi gian. Lp ny
cung cp cc gi tr gia 0 v 1,. Gi tr ny ph thuc vo thi im v
thng s ca i tng Alpha. i tng Alpha thng c s dng
vi cc i tng hnh vi sn c thc hin cc thay i hot ha ca
cc i tng quan st.
http://tailieuhay.com
242
cc
hnh
vi
thit
lp
da
trn
phng
thc
setSchedulingBounds ca lp Behavior.
C rt nhiu cch nh ngha vng danh mc ny nhng cch n gin
nht l to i tng BoundSphere . Cc ty chn khc nh bounding
box, hoc bouding polytope.
Behavior setSchedulingBounds method
void setSchedulingBounds(Bounds region)
http://tailieuhay.com
243
Lp BoundingSphere
Vic nh ngha mt vng cu phi i i vi vic ch ra im trung
tm v bn knh ca n. Cch thng lm l tm ca hnh cu v tr
trung tm l (0,0,0). Bn knh sau c la chn sao cho hnh cu
cha i tng quan st, bao gm tt c cc v tr m i tng c th
.
Bounding Sphere Constructors
BoundingSphere()
To mt hnh cu bao m tm v tr (0,0,0) vi bn knh bng 1
BoundingSphere(Point3d center, double radius)
2 tham s ln lt l
center ta ca tm trong khng gian
radius bn knh ca hnh cu
1.9.4 V d v hnh vi: HelloJava3Dc
on m hnh 1-7 a ra mt v d hon thin v vic s dng lp
thm vo to animation. Animation c to trong on m ny l
hnh lp phng quay lin tc trong thi gian 4 giy.
Bc u tin ca cng thc l to i tng TransformGroup
sa i ti thi im chy. i tng TransformGroup ca mt hnh vi
sn c phi c kh nng ghi. i tng TransformGroup tn l objSpin
c to dng 7. Kh nng ca n c thit lp dng th 8.
http://tailieuhay.com
244
to
tng
thm
vo.
tng
quay
objRoot
new
BranchGroup();
// Create the transform group node and
initialize it to the
// identity. Add it to the root of the
subgraph.
TransformGroup
objSpin
new
TransformGroup();
http://tailieuhay.com
245
bounds
new
BoundingSphere();
rotator.setSchedulingBounds(bounds);
http://tailieuhay.com
246
Kt qu
http://tailieuhay.com
247
rotate
object
has
composited
transformation matrix
Transform3D rotate = new Transform3D();
Transform3D tempRotate = new Transform3D();
rotate.rotX(Math.PI/4.0d);
tempRotate.rotY(Math.PI/5.0d);
rotate.mul(tempRotate);
TransformGroup
objRotate
new
TransformGroup(rotate);
//
Create
the
transform
group
node
and
initialize it to the
//
identity.
Enable
the
TRANSFORM_WRITE
capability so that
//
our
runtime.
behavior
code
can
modify
it
at
Add it to the
248
objSpin
new
TransformGroup();
objSpin.setCapability(TransformGroup.ALLOW_TRANS
FORM_WRITE);
objRoot.addChild(objRotate);
objRotate.addChild(objSpin);
// Create a simple shape leaf node, add it
to the scene graph.
// ColorCube is a Convenience Utility class
objSpin.addChild(new ColorCube(0.4));
// Create a new Behavior object that will
perform the desired
//
operation
on
the
specified
transform
(float)
Math.PI*2.0f);
http://tailieuhay.com
249
bounds
new
BoundingSphere();
rotator.setSchedulingBounds(bounds);
objSpin.addChild(rotator);
return objRoot;
} // end of CreateSceneGraph method of
HelloJava3Dd
Kt qu
http://tailieuhay.com
250
http://tailieuhay.com
251
CHNG 2
To cc hnh
2.1 H ta th gii o
Trong chng 1 ta bit vi mi instance ca mt lp
VirtualUniverse c chc nng nh mt gc ca th khung cnh trong
tt c chng trnh Java 3D. T kha virtual universe l ch mt khng
gian o 3 chiu trong c cc i tng 3D. Mi i tng Locale trong
mt mi trng o thit lp mt th gii o Cartesian. i tng ny
tng ng vi mt con tr tham chiu cho mt i tng quan st
trong mt mi trng o. Vi mt i tng Locale trong
SimpleUniverse c mt h ta duy nht.
H ta ca mi trng o Java 3D l thun phi tc l trc X
hng dng bn tay phi, trc Y hng dng ch ln trn, trc Z hng
dng ch vo ngi nhn vi n v l mt. Hnh 2-1 di y ch ra
hng nhn trong SimpleUniverse.
http://tailieuhay.com
252
http://tailieuhay.com
253
http://tailieuhay.com
254
http://tailieuhay.com
255
http://tailieuhay.com
256
http://tailieuhay.com
257
2.3.1 Box
Lp gc Box (hnh hp) to i tng quan st hnh hp 3D. Chiu
di chiu rng chiu cao mc nh l 2 met, vi tm gc. Chiu di
http://tailieuhay.com
258
rng
Primitive,
mt
lp
khc
trong
gi
com.sun.j3d.utils.Geometry
Box()
Thit lp mt hnh hp vi mc nh chiu cao chiu di chiu rng l 2
met, tm gc.
Box(float xdim, float ydim, float zdim, Appearance Appearance)
Thit lp hnh hp vi hng, b ngoi, v tm gc.
http://tailieuhay.com
259
http://tailieuhay.com
260
Sphere Methods
Package: com.sun.j3d.utils.Geometry
Shape3D getShape()
Ly i tng Shape3D cha dng hnh hc v b mt.
Shape3D getShape(int id)
Phng thc ny cng c s dng vi cc lp c bn pha trn. Tuy
nhin 1 Sphere ch c mt i tng Shape3D nn id =1.
void setAppearance(Appearance Appearance)
Lp b mt cho hnh cu.
http://tailieuhay.com
261
2.3.6 ColorCube
Lp ColorCube c trnh by y th hin s tng phn vi cc
lp hnh c bn nh Box, Cone, Cylinder v Sphere. Lp ny m rng
theo hng tha k khc, n l lp con ca Shape3D. Cy tha k c
ch ra trong hnh 2-5.
262
263
http://tailieuhay.com
264
create
Shape3D
with
geometry
and
appearance
//
the
geometry
is
created
in
method
yoyoGeometry
// the appearance is created in method
yoyoAppearance
//
public ConeYoyo() {
yoyoBG = new BranchGroup();
Appearance app = new Appearance();
//
rotate
object
has
composited
transformation matrix
Transform3D
rotate
new
Transform3D();
Transform3D
translate
new
Transform3D();
http://tailieuhay.com
265
translate.set(new
Vector3f(0.1f,
0.0f, 0.0f));
TransformGroup
yoyoTGT1
new
new
TransformGroup(translate);
yoyoBG.addChild(yoyoTGT1);
rotate.rotZ(Math.PI / 2.0d);
TransformGroup
yoyoTGR1
TransformGroup(rotate);
Cone cone1 = new Cone(0.6f, 0.2f);
cone1.setAppearance(app);
yoyoTGR1.addChild(cone1);
yoyoTGT1.addChild(yoyoTGR1);
translate.set(new
Vector3f(-0.1f,
0.0f, 0.0f));
TransformGroup
yoyoTGT2
new
TransformGroup(translate);
yoyoBG.addChild(yoyoTGT2);
rotate.rotZ(-Math.PI / 2.0d);
TransformGroup
yoyoTGR2
new
TransformGroup(rotate);
Cone cone2 = new Cone(0.6f, 0.2f);
cone2.setAppearance(app);
yoyoTGR2.addChild(cone2);
yoyoTGT2.addChild(yoyoTGR2);
http://tailieuhay.com
266
267
2.4 Cc lp ton hc
to i tng quan st, cn c lp hnh hc v cc lp con ca n.
Rt nhiu lp con ca lp hnh hcmo t da trn cc hnh c bn vc t,
nh im ng thng v a gic. Cc lp con ca lp hnh hc s c
m t trong phn 2-5 nhng trc chng ta quan tm n cc lp ton
http://tailieuhay.com
268
http://tailieuhay.com
269
270
http://tailieuhay.com
271
272
= new
Color3f(1.0f,0.0f,0.0f);
public static final Color3f green
= new
Color3f(0.0f,1.0f,0.0f);
public static final Color3f blue
= new
Color3f(0.0f,0.0f,1.0f);
public static final Color3f yellow
http://tailieuhay.com
= new
273
= new
Color3f(0.0f,1.0f,1.0f);
public static final Color3f magenta = new
Color3f(1.0f,0.0f,1.0f);
public static final Color3f white
= new
Color3f(1.0f,1.0f,1.0f);
public static final Color3f black
= new
Color3f(0.0f,0.0f,0.0f);
}
http://tailieuhay.com
274
http://tailieuhay.com
275
http://tailieuhay.com
276
http://tailieuhay.com
277
http://tailieuhay.com
278
http://tailieuhay.com
279
280
http://tailieuhay.com
281
/////////////////////////////////////
/////
//
// create axis subgraph
//
public Axis() {
axisBG = new BranchGroup();
// create line for X axis
LineArray
axisXLines
new
LineArray(2, LineArray.COORDINATES);
axisBG.addChild(new
Shape3D(axisXLines));
axisXLines.setCoordinate(0,
new
new
red
Color3f
green
Color3f
blue
new
Color3f(1.0f,
new
Color3f(0.0f,
new
Color3f(0.0f,
0.0f, 0.0f);
1.0f, 0.0f);
0.0f, 1.0f);
http://tailieuhay.com
282
axisYLines
new
LineArray(2, LineArray.COORDINATES
| LineArray.COLOR_3);
axisBG.addChild(new
Shape3D(axisYLines));
axisYLines.setCoordinate(0,
new
new
axisZLines
new
LineArray(10, LineArray.COORDINATES
| LineArray.COLOR_3);
axisBG.addChild(new
Shape3D(axisZLines));
axisZLines.setCoordinate(0, z1);
http://tailieuhay.com
283
new
new
new
new
http://tailieuhay.com
284
http://tailieuhay.com
285
http://tailieuhay.com
286
bn
ghp
GeometryStripArray
to
ng
lp
cha
mt
ca
tha
k.
LineStripArray,
php
mt
tng
th
duy
tr
nhiu
mnh.
http://tailieuhay.com
287
vtxCount,
int
vertexFormat,
int
int
vertexFormat,
int
stripVertexCounts[])
TriangleFanArray(int
vtxCount,
stripVertexCounts[])
Ch rng Java 3D khng h tr cc hnh c bn y vi nhiu hn 4
mt. Ngi lp trnh phi c trch nhim trong vic s dng k thut tch
tch hnh phc tp ra thnh nhiu cc i tng ca Java 3D nh mng
tam gic hoc hnh qut.
Triangulator Class
Package: com.sun.j3d.utils.Geometry
S dng chuyn cc a gic hnh hc khng c dng tam gic v cc
tam gic c th dng hnh bng Java 3D. Cc a gic phi l li,
cng nm trn mt mt phng cc cnh khng giao nhau.
Triangulator Constructor Summary
Triangulator()
To mt i tng tam gic.
Triangulator Method Summary
void triangulate(GeometryInfo ginfo)
http://tailieuhay.com
288
http://tailieuhay.com
289
290
http://tailieuhay.com
291
292
http://tailieuhay.com
293
http://tailieuhay.com
294
Hm
to
cho
IndexedGeometryArray,
vertexCount,
int
vertexFormat,
int
indexCount)
IndexedPointArray(int vertexCount, int vertexFormat, int indexCount)
IndexedLineArray(int vertexCount, int vertexFormat, int indexCount)
IndexedTriangleArray(int
vertexCount,
int
vertexFormat,
int
indexCount)
IndexedQuadArray(int vertexCount, int vertexFormat, int indexCount)
http://tailieuhay.com
295
vc,
int
vf,
int
ic,
int
stripVertexCounts[])
IndexedLineStripArray(int vc, int vf, int ic, int stripVertexCounts[])
IndexedTriangleStripArray(int vc, int vf, int ic, int stripVertexCounts[])
IndexedTriangleFanArray(int vc, int vf, int ic, int stripVertexCounts[])
Cc phng thc ca chng cho i dy:
IndexedGeometryArray Methods (partial list)
void setCoordinateIndex(int index, int coordinateIndex)
To cc ch mc ta tng ng vi cc nh ti v tr ch mc cho i
tng
void setCoordinateIndices(int index, int coordinateIndices[])
To cc ch mc cc ta tng ng vi cc nh ti v tr ch mc cho
i tng
void setColorIndex(int index, int colorIndex)
Lp ch mc mu tng ng vi nh ti v tr ch mc cho vi i
tng.
void setColorIndices(int index, int colorIndices[])
Lp cc ch mc mu tng ng vi cc nh ti v tr ch mc cho
vi i tng.
void setNormalIndex(int index, int normalIndex)
Lp ch mc bnh thng tng ng vi nh ti ch mc nh trc cho
i tng.
void setNormalIndices(int index, int normalIndices[])
Lp cc ch mc bnh thng tng ng vi cc nh ti ch mc nh
trc cho i tng.
http://tailieuhay.com
296
http://tailieuhay.com
297
ColoringAttributes
dng
phng
thc
Appearance.setColoringAttributes().
http://tailieuhay.com
298
http://tailieuhay.com
299
Vic chia s ny gip cho vic dng hnh nhanh hn, hiu qu cng
cao.
Tuy nhin cn ch rng mt node khng c c nhiu hn mt cha t
NodeComponent c th chia s hay tham chiu n bi nhiu i
tng khc.
http://tailieuhay.com
300
PointAttributes Methods
void setPointSize(float pointSize)
M t kch thc pixel ca cc im
void setPointAntialiasingEnable(boolean state)
Thit lp hoc b thit lp chng rng ca. Thng lm nu pointSize
>= 1 pixel.
LineAttributes
i tng ny thay i cch dng cc ng c bn theo 3 cch. Mc
nh ng c v l nt lin, vi rng 1pixle khng chng rng ca.
Bn c th thay i iu ny bng cch s dng cc phng thc
setLinePattern(), setLineWidth(), v setLineAntialiasingEnable().
Mu ng thng do ngi dng t nh ngha
Mt mu thng dc nh ngha bng mt mt n mu v mt thnh
phn quy m.
Mt gi tr 16 bit nh ngha mt mt n mu. Mi bit trong 16 bit gi
tr nh ngha khi no 1 pixel trong mu c bt hay tt (1/0). Sau khi c
16 mu u c s dng, th mu c lp li. Bit 0 tng ng vi pixel
u tin trong mu.
V d mt mt n ca 0x00ff (0b0000000011111111) nh ngha 8 pixel
m sau l 8 pixel ng.
Nh rng,bit phng i b nht c s dng u tin khi v, nn
mu bit c c t phi sang tri. Mt n mu gi tr 0x0101 nh ngha
mt mu lp ca mt pixel m v 7pixel tt. Mu ny c lp li nhiu
ln ty theo yu cu, mu khi ng li trc mi ng mi ca mt
mnh.
Cc mu c th m rng n 240 pixel s dng nhn t quy m. V d
nh quy m ca 3 x vi mt mt n mu 0x001f tng ng vi sn
http://tailieuhay.com
301
LineAttributes Methods
void setLineWidth(float lineWidth)
M t rng pixel cho ng thng
void setLinePattern(int linePattern)
linePattern l mt trong s cc hng sau:
PATTERN_SOLID (the default),
PATTERN_DASH, PATTERN_DOT, PATTERN_DASH_DOT, or
PATTERN_USER_DEFINED.
M t lm sao mt pixel ca mt ng c in vo.
void setLineAntialiasingEnable(boolean state)
B hay c chng rng ca vi ng thng
void setPatternMask(int mask) <new in 1.2>
Lp mt mt n mu vi mt gi tr c bit
void setPatternScaleFactor(int scaleFactor) <new in 1.2>
Sets the line pattern scale factor to the specified value.
http://tailieuhay.com
302
http://tailieuhay.com
303
polygonMode,
int
cullFace,
float
polygonOffset)
To i tng thnh phn vi gi tr cho trc ca gic li
PolygonAttributes(int
polygonMode,
int
cullFace,
float
polygonOffset,
boolean backFaceNormalFlip)
To i tng thnh phn ging nh cc hm to pha trc nhng cng
cho php ch ra mt pha trc v pha sau ca a gic nh th no
PolygonAttributes(int
polygonOffset,
polygonMode,
boolean
int
cullFace,
backFaceNormalFlip,
float
float
PolygonAttributes Methods
void setCullFace(int cullFace)
cullFace l CULL_FRONT, CULL_BACK, or CULL_NONE. Cull
(khng dng) trc mt v mt sau ca cc a gic hoc khng tch a
gic no.
void setPolygonMode(int polygonMode)
polygonMode l: POLYGON_POINT, POLYGON_LINE, or
http://tailieuhay.com
304
red,
float
green,
float
blue,
int
shadeModel)
shadeModel l mt trong SHADE_GOURAUD, SHADE_FLAT,
FASTEST, or NICEST.
http://tailieuhay.com
305
mt
trong
cc
hng:
SHADE_GOURAUD,
SHADE_FLAT, FASTEST,
or NICEST.
TransparencyAttributes
Thuc tnh ny qun l trong sut ca bt c hnh c bn no.
setTransparency() nh ngha gi tr trong sut (bng 1 l trong sut hon
ton, bng 0.0 l khng trong sut)
TransparencyAttributes Constructors
TransparencyAttributes()
To i tng thnh phn vi trong sut lp ch NONE.
TransparencyAttributes(int tMode, float tVal)
Trong tMode l mt trong nhng BLENDED, SCREEN_DOOR,
FASTEST, NICEST, hoc NONE, v tVal nh ngha tnh m ca i
tng (0.0 khng trong sut v 1.0, trong sut hon ton).
TransparencyAttributes(int
tMode,
float
tVal,
int
srcBlendFunction,
int dstBlendFunction) <new in 1.2>
http://tailieuhay.com
306
TransparencyAttributes Methods
void setTransparency(float tVal)
tVal nh ngha tnh m ca i tng (0.0 khng trong sut v 1.0,
trong sut hon ton).
void setTransparencyMode(int tMode)
tMode (one of BLENDED, SCREEN_DOOR, FASTEST, NICEST, or
NONE) ch ra nu
c hot ng lm trong sut
void setDstBlendFunction(int blendFunction) <new in 1.2>
Lp a ch chc nng pha trn c s dng trn trong sut v
chng rng ca.
void setSrcBlendFunction(int blendFunction) <new in 1.2>
Lp ti nguyen hm trng s dng trn trong sut v chng rng
ca.
RenderingAttributes
RenderingAttributes iu khin 2 hot ng dng hnh trn tng
pixel: kim nh su m, v kim tra alpha.
Hot ng qut (Geometry) xc nh xem vic dng hnh pixel nh
hng n mn nh th no. Mc nh l b chn Geometry thng c
s dng trong hu ht cc trng hp
su m l tp hp cc gi tr su ca nhng pixel c dng. N
c dng xc nh pixel c nhn thy hay b khut chng c th
c dng. su m s dng khc khi dng i m v trong sut. Kt
qu l i tng trong sut khng cp nhp gi tr su m khng bnh
thng. C th v hiu ha hoc dng tnh nng ny i vi mt i
http://tailieuhay.com
307
depthBufferEnable,
float
alphaTestValue,
boolean
int
alphaTestFunction)
Trong depthBufferEnable bt tt so snh su m (kim tra
su),
depthBufferWriteEnable bt v tt ghi vo depth buffer,
alphaTestValue c s dng kim tra. i vi cc ngun alpha i
vo , and alphaTestFunction l mt trong nhng ALWAYS, NEVER,
EQUAL, NOT_EQUAL, LESS, LESS_OR_EQUAL, GREATER, hoc
GREATER_OR_EQUAL, ch r loi alpha test no c kch hot. To
mt i tng thnh phn nh ngha vic dng trn pixel cho so sanh
su m v kim tra alpha.
RenderingAttributes(boolean
depthBufferWriteEnable,
depthBufferEnable,
float
alphaTestValue,
boolean
int
alphaTestFunction,
boolean visible, boolean ignoreVertexColors,
boolean GeometryOpEnable, int GeometryOp) <new in 1.2>
To mt i tng RenderingAttributes vi gi tr cho trc.
RenderingAttributes Methods
void setDepthBufferEnable(boolean state)
http://tailieuhay.com
308
309
Parameter
Default Value
ColoringAttributes
color
white (1, 1, 1)
shade model
SHADE_GOURAUD
line width
1.0
line pattern
PATTERN_SOLID
false
point size
1.0
false
cull face
CULL_BACK
backFaceNormalFlip
false
polygon mode
POLYGON_FILL
polygonOffset
0.0
polygonOffsetFactor
0.0
depthBufferEnable
true
depthBufferWriteEnable
true
alphaTestFunction
ALWAYS
alphaTestValue
0.0
visible
true
ignoreVertexColors
false
LineAttributes
PointAttributes
PolygonAttributes
RenderingAttributes
http://tailieuhay.com
310
TextureAttributes
GeometryOpEnable
false
GeometryOp
ROP_COPY
textureMode
REPLACE
textureBlendColor
black (0, 0, 0, 0)
transform
identity
perspectiveCorrectionMode NICEST
textureColorTable
TransparencyAttributes transparencyMode
null
NONE
transparencyValue
0.0
srcBlendFunction
SRC_BLEND_ALPHA
dstBlendFunction
BLEND_ONE_MINUS_ALPHA
http://tailieuhay.com
311
http://tailieuhay.com
312
/////////////////////////////////////
/////
//
// create twist subgraph
//
public Twist() {
this.setGeometry(createGeometry());
this.setAppearance(createAppearance());
} // end of twist constructor
Geometry createGeometry() {
TriangleStripArray twistStrip;
Color3f
blue
new
Color3f(0.0f,
0.0f, 1.0f);
// create triangle strip for twist
int N = 80;
int stripCounts[] = { N };
twistStrip = new TriangleStripArray(
N,
TriangleStripArray.COORDINATES
TriangleStripArray.COLOR_3,
stripCounts);
double a;
http://tailieuhay.com
313
new
Math.cos(a),
0.3
0.2
Math.cos(a),
Math.cos(a)
0.2
Math.cos(a)));
twistStrip.setColor(v, blue);
twistStrip.setColor(v
1,
blue);
}
return twistStrip;
}
// create Appearance for Twist Strip
//
//
this
method
creates
the
default
http://tailieuhay.com
314
twistAppear
new
Appearance();
PolygonAttributes
polyAttrib
new
PolygonAttributes();
//
polyAttrib.setCullFace(PolygonAttributes.CULL_NON
E);
twistAppear.setPolygonAttributes(polyAttrib);
return twistAppear;
}
} // end of class Twist
// //////////////////////////////////////////
/////
//
// create scene graph branch group
//
public BranchGroup createSceneGraph() {
http://tailieuhay.com
315
contentRoot
new
BranchGroup();
// Create the transform group node and
initialize it to the
// identity. Add it to the root of the
subgraph.
TransformGroup
objSpin
new
TransformGroup();
objSpin.setCapability(TransformGroup.ALLOW_TRANSF
ORM_WRITE);
contentRoot.addChild(objSpin);
Shape3D twist = new Twist();
objSpin.addChild(twist);
//
Duplicate
the
twist
strip
geometry
Add
the
POLYGON_FILLED
and
POLYGON_LINE strips
// in the scene graph at the same point.
// This will show the triangles of the
original Mobius strip that
// are clipped. The PolygonOffset is set
to prevent stitching.
http://tailieuhay.com
316
polyAttrib
new
PolygonAttributes();
polyAttrib.setCullFace(PolygonAttributes.CULL_NON
E);
polyAttrib.setPolygonMode(PolygonAttributes.POLYG
ON_LINE);
polyAttrib.setPolygonOffset(0.001f);
Appearance
polyAppear
new
Appearance();
polyAppear.setPolygonAttributes(polyAttrib);
objSpin.addChild(new
Shape3D(twist.getGeometry(), polyAppear));
Alpha
rotationAlpha
new
Alpha(-1,
16000);
RotationInterpolator
rotator
new
RotationInterpolator(rotationAlpha,
objSpin);
// a bounding sphere specifies a region
a behavior is active
//
create
sphere
centered
at
the
http://tailieuhay.com
317
bounds
new
BoundingSphere();
rotator.setSchedulingBounds(bounds);
objSpin.addChild(rotator);
// make background white
Background
background
new
//
end
of
CreateSceneGraph
method
of
TwistStripApp
// Create a simple scene and attach it to the
virtual universe
public TwistStripApp() {
setLayout(new BorderLayout());
Canvas3D canvas3D = new Canvas3D(null);
add("Center", canvas3D);
BranchGroup scene = createSceneGraph();
http://tailieuhay.com
318
SimpleUniverse
is
Convenience
Utility class
SimpleUniverse
simpleU
new
SimpleUniverse(canvas3D);
// This will move the ViewPlatform back
a bit so the
// objects in the scene can be viewed.
simpleU.getViewingPlatform().setNominalViewingTra
nsform();
simpleU.addBranchGraph(scene);
} // end of TwistStripApp constructor
// The following method allows this to be run
as an application
public static void main(String[] args) {
System.out.println("TwistStripApp - Java
3D API version 1.1");
System.out.print("See
\"Getting
Started
program
http://tailieuhay.com
319
this
program
two
wireframe
and
wire
frame
is
frame
new
MainFrame(new
http://tailieuhay.com
320
http://tailieuhay.com
321
http://tailieuhay.com
322
http://tailieuhay.com
323
http://tailieuhay.com
324
http://tailieuhay.com
325
326
http://tailieuhay.com
327
BoundingLeafa Class
Cc phi tham s ca hm to cho BoundingLeafa to mt n v
hnh cu bao.
BoundingLeafa Constructor Summary
The BoundingLeafa node defines a bounding region object that can be
referenced by other nodes to define a region of influence, an activation
region, or a scheduling region.
Nt BoundingLeafa dng nh ngha mt i tng vng bao c th
c tham chiu n bng cc nt khc nahu nh ngha mt vng
nh hng, mt vng kch hot hoc mt vng danh mc.
BoundingLeafa()
To mt nt BoundingLeafa vi mt i tng n v hnh cu
BoundingLeafa(Bounds region)
To mt nt BoundingLeafa vi vng nh trc.
BoundingLeafa Method Summary
Bounds getRegion()
Nht vng BoundingLeafa.
void setRegion(Bounds region)
Sets this BoundingLeafa node's bounding region.
Lp vng bao ca nt BoundingLeafa.
2.7.3 Scope
Nh gii thiu pha trn, nh ngha mt scope (tm quan st) l
mt cch gii hn ng dng hay nh hng ca mt nt. Nt nh
ngha mt phm vi quan st c th nh hng ti i tng ca ca th
con c gc ti i tng Group. Khi khng c mt phm vi quan st cho
http://tailieuhay.com
328
http://tailieuhay.com
329
330
GeometryArray:
[Indexed]{TriangleArray,
TriangleStripArray, TriangleFanArray,
QuadArray}
http://tailieuhay.com
331
http://tailieuhay.com
332
2.8.2 GeometryArray
Trong vic xy dng hnh cc bc l to mt i tng hnh hc, ri
ng k gi tr cho n nh ngha d liu hnh hc (to , mu ...) .
Vi phin bn 1.2 cho php li gi BY_REFERENCE thay th cho vic
sao chp d liu hnh hc. Vic ny khi phin bn c l i tng sao
chp GeometryArray c khi to c mt mng private lu gi ton b
d liu ny bn trong i tng GeometryArray. Sau khi d liu hnh
hc c ng k vi GeometryArray n c sao chp vo mng ny.
Khi i tng GeometryArray BY_REFERENCE c to ngi dng
to mt mng hnh hc v qun l mng ny vi d liu hnh hc. V v
th khng c mng bn trong i tng hnh hc.
Vy khi no cn s dng BY_REFERENCE, c 2 l do s dng n l:
1. Nu d liu hnh hc l ng
2. Nu d liu hnh hc cn s dng nhiu b nh
L do ln nht chn phng php ny l d liu c th thay i
thm ch i tng ang sng hoc c dch. Cch thay i hnh chnh
l thay i d liu ca n, cch khc l phn chia mng s dng bi i
tng hnh hc.
Nhng gi v cnh bo khi s dng BY_REFERENCE
Nu s dng BY_REFERENCE, s dng phng thc set*RefFloat l tt
hn c. V d, s dng setCoordRefFloat()thay v setCoordRef3f()s
dng mng s thc cho php truy cp trc tip hn l s dng mt mng
cc i tng. Mt mng cc i tng trong Java 3D lun lun lu tr
cc tham chiu hn l gi tr thc v ch cc mng c kiu d liu nh
thc mi lu d liu.
http://tailieuhay.com
333
http://tailieuhay.com
334
contentRoot
new
BranchGroup();
// Create the transform group node and
initialize it to the
// identity. Add it to the root of the
subgraph.
TransformGroup
objSpin
new
TransformGroup();
objSpin.setCapability(TransformGroup.ALLOW_TRANSF
ORM_WRITE);
contentRoot.addChild(objSpin);
Shape3D twist = new Twist();
objSpin.addChild(twist);
//
Duplicate
the
twist
strip
geometry
Add
the
POLYGON_FILLED
and
POLYGON_LINE strips
// in the scene graph at the same point.
// This will show the triangles of the
original Mobius strip that
// are clipped. The PolygonOffset is set
to prevent stitching.
http://tailieuhay.com
335
polyAttrib
new
PolygonAttributes();
polyAttrib.setCullFace(PolygonAttributes.CULL_NON
E);
polyAttrib.setPolygonMode(PolygonAttributes.POLYG
ON_LINE);
polyAttrib.setPolygonOffset(0.001f);
Appearance
polyAppear
new
Appearance();
polyAppear.setPolygonAttributes(polyAttrib);
objSpin.addChild(new
Shape3D(twist.getGeometry(), polyAppear));
Alpha
rotationAlpha
new
Alpha(-1,
16000);
RotationInterpolator
rotator
new
RotationInterpolator(rotationAlpha,
objSpin);
// a bounding sphere specifies a region
a behavior is active
//
create
sphere
centered
at
the
http://tailieuhay.com
336
bounds
new
BoundingSphere();
rotator.setSchedulingBounds(bounds);
objSpin.addChild(rotator);
// make background white
Background
background
new
//
end
of
CreateSceneGraph
method
of
TwistStripApp
GeometryArray
Lp GeometryArray l lp c s ca nhiu lp hnh hc khc. V th
n nh ngha rt nhiu phng thc cho vic qun l d liu. s dng
tham chiu hnh hc,lp bit BY_REFERENCE trong trng nh dng
nh trong hm to ca i tng GeometryArray.
GeometryArray Methods for Referencing Geometry Data (partial
list)
This collection of methods set the references to Geometry data in user
arrays. In each case, the method will throw an exception if the data
http://tailieuhay.com
337
http://tailieuhay.com
338
http://tailieuhay.com
339
GeometryArray Capabilites
BY_REFERENCE <new in 1.2>
Specifies the position, color, normal, and texture coordinate data for this
object are accessed by reference
INTERLEAVED <new in 1.2>
Specifies that the position, color, normal, and texture coordinate data for
this GeometryArray are
accessed via a single interleaved, floating-point array reference. This is
only used in by-reference
Geometry mode.
ALLOW_COUNT_READ | WRITE <new in 1.2>
allow write access to the count or initial index information for this
object
ALLOW_REF_DATA_READ <new in 1.2>
allow read access to the Geometry data reference information; only
used in by-reference Geometry mode
ALLOW_REF_DATA_WRITE <new in 1.2>
allow write access to the Geometry data reference information for this
object. It also enables writing the referenced data itself, via the
GeometryUpdater interface. This is only used in by-reference
Geometry mode.
http://tailieuhay.com
340
http://tailieuhay.com
341
theo
AlternateAppearance
vo
mnh.
th
ng
khung
qun
cnh,
lp
thm
c
http://tailieuhay.com
342
http://tailieuhay.com
343
2.9 Clipping Ct xn
Ch ca Clipping khng thc s l vic to hnh nhng mt trong
nhng nhn t nh hng n hnh nh trong nh th no. V d khi mt
hnh m rng n vng bin nn n b ct i v th mt s hnh khng
xem c. Ct xn l mt ch phc tp, phn ny a ra cc vn c
bn nht trong vic ct hnh .
http://tailieuhay.com
344
345
http://tailieuhay.com
346
http://tailieuhay.com
347
http://tailieuhay.com
348
http://tailieuhay.com
349
http://tailieuhay.com
350
CHNG 3
TO NI DUNG
http://tailieuhay.com
351
3.1.1 GeometryInfo
Thng thng v mt hnh mt i tng hnh hc bt k, chng ta
phi t lm hon ton v vic code s rt vt v v nhm chn. S
dng lp GeometryInfo cng vic s tr nen d dng v thun tin
hn. Khi bt u v mt i tng hnh hc, chng ta s xc nh mt
a gic bt k ph hp vi di tng . a gic ny c th l a gic
lm, khng phng i tng GeometryInfo v cc lp khc s
chuyn cc a gic ny thnh cc tam gic nh hn, t Java3D c
th render (t_cht) .
TRIANGLE_ARRAY,
352
gi
new
GeometryInfo(GeometryInfo.POLYGON_ARRAY);
gi.setCoordinates(coordinateData);
gi.setStripCounts(stripCounts);
Triangulator tr = new Triangulator();
tr.triangulate(gi);
NormalGenerator ng = new NormalGenerator();
ng.generateNormals(gi);
Stripifier st = new Stripifier();
st.stripify(gi);
Shape3D part = new Shape3D();
part.setAppearance(appearance);
part.setGeometry(gi.getGeometryArray());
http://tailieuhay.com
353
com.sun.j3d.util.geometry.
http://tailieuhay.com
354
Hm to GeometryInfo
Gi: com.sun.j3d.utils.geometry
Lp cha: java..lang.Object
S dng: Chng ta mun chuyn cc i tng hnh hc cho i tng
GeometryInfo c th dng cc lp tin ch khc. Khi chng ta
chuyn i tng hnh hc cn th hin cho i tng GeometryInfo,
cc lp tin ch s s dng cc d liu trong i tng GeometryInfo
thc hin cc yu cu ca chng ta.
GeometryInfo(int primitive)
Gi tr ca primitive:
POLYGON_ARRAY
chiu(a din)
QUAD_ARRAY
: T din
TRIANGLE_ARRAY
: Tam gic
TRIANGLE_FAN_ARRAY
http://tailieuhay.com
355
http://tailieuhay.com
356
http://tailieuhay.com
357
POLYGON_ARRAY
sang
kiu
nguyn
thu
kiu
TRIANGLE_ARRY.
Hm to lp Stripifier nhm to ra mt i tng stripification
Stripifier Constructor Summary
Gi: com.sun.j3d.utils.geometry
Lp cha: java.lang.Object
Lp Stripfier c tin ch i kiu d liu nguyn thu ca mt i tng
GeometryInfo sang kiu Triangle Strips. cho kt qu tt Normal
Generation phi c thc hintrc khi qu trnh tch nh i tng
hnh hc.
Stripifier()
Hm to
Png thc ca lp Stripifier
void stripify(GeometryInfo gi)
http://tailieuhay.com
358
http://tailieuhay.com
359
http://tailieuhay.com
360
Cc loader ph bin
Trong Java3D chng ta c th tm thy rt nhiu lp Loader. Ta c
bng danh sach c th di y.
File
M t
3DS
COB
DEM
3D-Studio
Caligari trueSpace
Digital Elevation Map
AutoCAD Drawing Interchange
DXF
IOB
File
Imagine
LWS
NFF
OBJ
Wavefront
PDB
PLAY
PLAY
SLD
Solid World
VRT
Superscape VRT
http://tailieuhay.com
361
3.3.3
Visual Toolkit
Virtual
Reality
Modeling
language
http://tailieuhay.com
362
http://tailieuhay.com
363
http://tailieuhay.com
364
http://tailieuhay.com
365
Vit mt loader
http://tailieuhay.com
366
http://tailieuhay.com
367
Scene
textures )
Chuyn danh sch cc i
tong scene graph vo tong
File
khung cnh ho
Lin quan n cc file hay
cc URL cn m
Tokenizer
y l tng thp nht ca loader trong vic x l cc file ho.
Tn ny c nhim v chia nh ni dung cu file thnh phn nh
hn, gi l cc token. Ly v d mt token c th l mt s, mt
t, hay mt k t n.
i tng
Tng object c nhim v to ra cc i tng ha t cc
token c to ra theo ni dung ca file. Mt vi i tng c
th l i tng nh, a gic, nh sng, kt cu hay bt c i
tng khung cnh no trong Java3D. Nhng object ny l cc
thnh phn ca mt khung cnh
Scene
L tp hp cc i tng hnh hc.Thng thng tng scene
trong Java3D n gin. Tr trung hp ngoi l khi n lp
loader c nhim v load mt tp i din cho mt khung cnh
ha. V d nh file theo nh dng Open Inventor v OOGL
List.
File
http://tailieuhay.com
368
http://tailieuhay.com
369
Thc thi
tokenizer
QuadFileParser
Object
SimpleQuadObject
scene
QuadFileParser
SimpleQuadScene tha k
file
lp SimpleQuadObject
SimpleQuadFileLoader
tha
cha
lp
lp Loader
SimpleQuadLoad cha lp
SimpleQuadFileLoader
Trong cc phn tip theo chng ta s xem xt k hn cc lp ny,
thnh phn v hot ng ca n tng mt ng dn loader.
Tng Tokenizer(Qun l cc phn t)
Bc u tin xy dng mt loader l xy dng tokenizer. iu
ny c thc hin bng cch chng ta tha k lp tin ch
StreamTokenizer. Lp ny c vo lung cc k t v chuyn i
n thnh tp cc phn t. Trong v d ny, chng ta xy dng lp
QuadFileParser th k lp StreamTokenizer.
Cc phng thc trong lp QuadFileParser
http://tailieuhay.com
370
Nhim v/hot ng
Void setup()
boolean getToken()
hm ny c gi trong hm to
Phng thc ly ra token tip theo,
phng
thc
dng
nextToken()ca
Void printToken()
StreamTokenizer
In gi tr ca
hm
lp
cc
token
ra
li
Hm to gi phng thc setup v
r r)
http://tailieuhay.com
371
372
Nhim v
Boolean
c nh, mi nh bao gm
readVertex(QuadFileParser st)
Boolean
mt
c cc t din bng cch
readQuad(QuadFileParser st)
c cc nh t file QUAD
http://tailieuhay.com
373
readQuadFile(QuadFileParserst)
cc th trong file, xc nh
tp cc nh v c ra c t
din(t gic)
static
final
int
COORDINATE
GeometryArray.COORDINATES;
// lists of points are read from the .quad file into this //array. . .
protected ArrayList coordList; // Holds Point3f
/**
* readVertex reads one vertex's coordinate data
*/
boolean readVertex(QuadFileParser st)
{
http://tailieuhay.com
374
375
Nhim v
Nhn d liu t mt ArrayList do
tng di a ln, to ra cc i
tng hnh hc tng ng v a
http://tailieuhay.com
376
Point3f[]
thc makeScene() to ra cc i
tng hnh hc
1.Khi to a mt i tng
QuadFileParser
2.Gi QuadFileLoad(scene)
3.Gi makeScene()
http://tailieuhay.com
377
378
http://tailieuhay.com
379
Text2D
C hai cch thc hin vic them ch vo trong khung hnh
Java3D. Cch th nht l s dng lp Text2D, cch th hai l s
dng Text3D. S khc nhau ch, lp Text2D thc hin cc dng
ch trong khng gian 2 chiu cn Text3D thc hin trong khng
gian 3 chiu.
i tng Text2D l cc a gic vung trong cc ch c coi
nh l phn b mt. i tuwng Text3D l nhng i tng hnh
hc trong khng gian 3 chiu.
L mt lp con ca lp Shpae3D, th hin ca lp Text2D c th l
con ca i tng group. thm vo dng ch 2D trong Java3D
chng ta cn to ra i tng Text2D sau thm n vo khng
gian ho.
i tng Text2D c thc hin s dng mt a gic v mt
texture.
http://tailieuhay.com
380
3.5.2 Lp Text2D
Lp Text2D l lp tin ch th k t lp Shape3D.
http://tailieuhay.com
381
Hm to lp Text2D.
Text2D Constructor Summary
Gi: com.sun.j3d.utils.geometry
Lp Text2D to ra mt khung ch nht c nh x n phn ni dung
text, hin th ni dung text c gi bi ngui dng. Kch thc ca
khung ch nht c xc nh ph thuc vo font c s dng(tham s
ca hm to). Kt qu ca i tng Shape3D trong sut ngoi tr hnh
ch nht cha ni dung text c t ti v tr (0,0,0) ko di theo chiu
dng trc x, trc y
Text2D(java.lang.String
text,
Color3f
color,
java.lang.String
fontName,
int fontSize, int fontStyle)
Trong hm to Text2D ta c th thay i t l kch thoc ca i
tuwng dng ch hin ra so vi kch thc im c nh.
Text2D Method Summary
void setRectangleScaleFactor(float newScaleFactor)
http://tailieuhay.com
382
http://tailieuhay.com
383
http://tailieuhay.com
384
http://tailieuhay.com
385
http://tailieuhay.com
386
http://tailieuhay.com
387
http://tailieuhay.com
388
http://tailieuhay.com
389
bng
gi
tr
cu
tham
vo.
double
http://tailieuhay.com
390
http://tailieuhay.com
391
Nn khng gian ha
Mt cch mc nh, mu nn ca khng gian ha l mu en sm.
Tuy nhin Java3D cung cp cho chng ta kh nng thay i nn ca
khng gian ha, ta c th la chn mu sc, nh, cc i tng hnh
hc hay kt hp cc thnh phn ny li to thnh nn ca khng
gian ha.
Cc bc to ra nn ca khng gian ha:
Khi to mt i tng background mi ch nh mu sc hoc
mt hnh nh no .
Thm vo mt i tng hnh hc (ty chn)
Cung cp mt Application Boundary hoc mt BoundingLeaf
Thm i tng background vo khng gian ha
Mt v d background
Nh ta trnh by phn trc. Mt di tung background c th l
mt mu c th, mt hnh nh hay thm ch mt i tng hnh hc.
http://tailieuhay.com
392
BoundingSphere(new
Point3d(), 100.0));
objRoot.addChild(backg);
Phng thc createBackGraph() bao gm vic to ra i tng hnh
hc lm nn. Phng thc ny tr v i tng BranchGroup. Ta c
th xem mt v d hon chinh BackgroundApp.java trong th mc
examples/easyContent.
Lp Background
http://tailieuhay.com
393
394
http://tailieuhay.com
395
http://tailieuhay.com
396
CHNG 4
TNG TC
Xy dng mt lp Behaviour
http://tailieuhay.com
397
Tc nhn TransformGroup
Geometry
Ngi
ng dng c ng
Tng tc
dng
S
chm
th
va i
quan
http://tailieuhay.com
SceneGraph Vie w
c th
dng Di
chuyn
tng
trc i
tng i
tng Th
thay
i trc
quan xut
hin hin
398
trong chm
thay i
cc va chm
trong va
chm
Thi
gian
Khung
Hot hnh
Bng
nhn
Hot hnh
Hot hnh
Tn cc chi ng
tit
(LOD)
c th
Hot
hnh
dng ng
dng c
th
http://tailieuhay.com
399
Behaviour.
http://tailieuhay.com
400
S cc lp con ca lp Behaviour
4.2.1 Vit mt lp Behaviour
Trong phn ny chng ta s tm hiu cch vit mt lp
Behaviour.Mechanics ca Behaviours
Mt lp Behaviour thc thi qu trnh khi to v phng thc
processStimulus ca lp c s tru tng Behaviour. Ngoi ra mt lp
Behaviour t xy dng cng c t nht mt hm to v c cc phng
thc khc ca ring n.
Cc Behaviour thng qua cc i tng ho, s hnh ng trong
mt th khung cnh nhm tc ng n hnh vi. i tng Behaviour
cn mt tham chiu n i tng c s thay i, n c kh nng to
ra nhng hnh vi thay i.
Trong hm to, c th thit lp tham chiu n i tng trong s
thay i. Nu khng, tng mt phng thc khc cu lp Behaviour t
xy dng phi cha nhng thng tin ny, qu trnh tham chiu phi c
thc hin ti thi im th khung cnh c to ra.
http://tailieuhay.com
401
402
WakeuponCondition
http://tailieuhay.com
403
Transform3D
rotation
new
Transform3D();
private double angle = 0.0;
// create SimpleBehavior - set TG object
of change
SimpleBehavior(TransformGroup
targetTG)
{
this.targetTG = targetTG;
}
// initialize the Behavior
// set initial wakeup condition
// called when behavior becomes live
public void initialize() {
// set initial wakeup condition
this.wakeupOn(new
WakeupOnAWTEvent(KeyEvent.KEY_PRESSED));
}
http://tailieuhay.com
404
void
processStimulus(Enumeration
criteria) {
// do what is necessary in response
to stimulus
angle += 0.1;
rotation.rotY(angle);
targetTG.setTransform(rotation);
this.wakeupOn(new
WakeupOnAWTEvent(KeyEvent.KEY_PRESSED));
}
}
}// end of class SimpleBehavior
Lp SimpleBehaviourApp ch thc hin nhng chc nng chnh cn
thit ca mt Behaviour n gin. Chungs ta c th pht trin thm cc
chc nng phong ph hn, v d ta c th xet gc quay ca trc quay c
th c thay i bi cc phng thc ca lp.
Mt im pht trin nng cp l khc phc hin tng trn ca gc
nghing.
Nhng sai lm trong vic vit mt lp Behaviour
http://tailieuhay.com
405
http://tailieuhay.com
406
objRotate
new
TransformGroup();
objRotate.setCapability(TransformGroup.ALLOW_TRA
NSFORM_WRITE);
objRoot.addChild(objRotate);
objRotate.addChild(new ColorCube(0.4));
SimpleBehavior myRotationBehavior = new
SimpleBehavior(objRotate);
myRotationBehavior.setSchedulingBounds(new
BoundingSphere());
objRoot.addChild(myRotationBehavior);
// Let Java 3D perform optimizations on
this scene graph.
http://tailieuhay.com
407
408
http://tailieuhay.com
409
http://tailieuhay.com
410
thc
khc.
trong
nhng
iu
kin
wakeup
411
412
http://tailieuhay.com
413
http://tailieuhay.com
414
http://tailieuhay.com
415
region.
WakeupOnActivation
is
paired
with
416
KeyEvent.KEY_RELEASED,
MouseEvent.MOUSE_CLICKED,
MouseEvent.MOUSE_PRESSED, MouseEvent.MOUSE_RELEASED,
MouseEvent.MOUSE_MOVED,
MouseEvent.MOUSE_DRAGGED, or one of many other event values.
WakeupOnAWTEvent(long eventMask)
Khi to mt i tng WakeupOnAWTEvent s dng ORed
EVENT_MASK,v AWT EVENT_MASK vi cc gi tr:
:
KEY_EVENT_MASK,
MOUSE_EVENT_MASK,
http://tailieuhay.com
417
Do
WakeupCondition
th
cha
nhiu
tng
http://tailieuhay.com
418
WakeupCriterion
pairPostCondition;
private WakeupCriterion wakeupNextFrame;
http://tailieuhay.com
419
private
WakeupCriterion
AWTEventCondition;
private
Transform3D
t3D
new
rotMat
new
Transform3D();
private
Matrix3d
Matrix3d();
private double doorAngle;
OpenBehavior(TransformGroup targetTG) {
this.targetTG = targetTG;
AWTEventCondition
new
WakeupOnAWTEvent(KeyEvent.KEY_PRESSED);
wakeupNextFrame
new
WakeupOnElapsedFrames(0);
}
public
void
setBehaviorObjectPartner(Behavior behaviorObject)
{
pairPostCondition
new
WakeupOnBehaviorPost(behaviorObject, 1);
}
public void initialize() {
this.wakeupOn(AWTEventCondition);
http://tailieuhay.com
420
void
processStimulus(Enumeration
criteria) {
if
(criteria.nextElement().equals(pairPostCondition)
) {
System.out.println("ready
to
open door");
this.wakeupOn(AWTEventCondition);
doorAngle = 0.0f;
} else { // could be KeyPress or
nextFrame, in either case: open
if (doorAngle < 1.6) {
doorAngle += 0.1;
if (doorAngle > 1.6)
doorAngle = 1.6;
//
get
rotation
and
scale
portion of transform
targetTG.getTransform(t3D);
t3D.getRotationScale(rotMat);
//
set
y-axis
rotation
to
doorAngle
// (clobber any previous yrotation, x and z scale)
http://tailieuhay.com
421
Math.cos(doorAngle);
rotMat.m22 = rotMat.m00;
rotMat.m02
Math.sin(doorAngle);
rotMat.m20 = -rotMat.m02;
t3D.setRotation(rotMat);
targetTG.setTransform(t3D);
this.wakeupOn(wakeupNextFrame);
}
else
//
finished
opening
is
open");
this.wakeupOn(pairPostCondition);
postId(1);
}
}
}
} // end of class OpenBehavior
Code 4-4: S dng lp OpenBehaviour v CloseBehaviour
i tng ca hai lp ny s thay phin nhau phn hi vi tc nhn
phm bm.i tng open behavior s tr li li kch hot phm bm u
tin ng thi n nh du cho i tng close Behaviour bit v thit
lp iu kin trigger ca n c th oc i tng close Behaviour
nhn bit.i tng open behavior m ca tr li li tc nhn phm
http://tailieuhay.com
422
http://tailieuhay.com
423
USE_BOUNDS
WakeupOnCollisionEntry(SceneGraphPath
WakeupOnCollisionExit
WakeupOnCollisionExit Constructor Summary
Tha k WakeupCriterion
Lp xc nh khi mt i tng xc nh kt thc va chm vi cc i
tng khc trong th khung cnh
WakeupOnCollisionExit(Bounds armingBounds)
Hm to vi tham s Bound
WakeupOnCollisionExit(Node armingNode)
Hm to vi tham s armingNode
WakeupOnCollisionExit(Node armingNode, int speedHint)
http://tailieuhay.com
424
armingPath,
int
speedHint)
Hm to vi tham s armingPath, speedHint
WakeupOnCollisionMovement
WakeupOnCollisionMovement Constructor Summary
Th k: WakeupCriterion
Lp xc nh khi i tng xc nh di chuyn trong va chm vi mt
i tng khc trong khng gian o
WakeupOnCollisionMovement(Bounds armingBounds)
Hm to WakeupOnCollisionMovement
WakeupOnCollisionMovement(Node armingNode)
http://tailieuhay.com
425
WakeupOnDeactivation
WakeupOnDeactivation Constructor Summary
Tha k: WakeupCriterion
http://tailieuhay.com
426
http://tailieuhay.com
427
th
nhn
bit
bi
lp
WakeupOnSensorEntry
WakeupOnSensorExit.
http://tailieuhay.com
428
http://tailieuhay.com
429
WakeupOnTransformChange
WakeupOnTransformChange rt hiu qu trong vic nhn bit thay
i v tr hay hng ca cc i tng trc quan trong th khung cnh.
Lp ny s dng phng thc postId to ra cc Behaviour hp tc.
iu ny c bit hiu qu khi chng ta mun hp tc vi mt Behaviour
c xy dng trc .
WakeupOnTransformChange Constructor Summary
Tha k: WakeupCriterion
Lp xc nh mt wakeup khi mt i tng transform trong mt nhm
TransformGroup xc nh thay i.
WakeupOnTransformChange(TransformGroup node)
Hm to i tng WakeupOnTransformChange.
http://tailieuhay.com
430
http://tailieuhay.com
431
t mt tp
http://tailieuhay.com
432
http://tailieuhay.com
433
4.4.1 Mt v d n gin
V
KeyNavigatorApp
sau
nm
trong
th
mc
examples/Interaction
Trong chng trnh ny chng ta c th thy c cc bc thc hin bao
gm c vic s dng lp KeyNavigatorBehavior ging nh vic s dng
cc lp Behaviour khc.
1. To ra i tng KeyNavigatorBehaviour
,thit lp transform
group
2. Thm i tng KeyNavigatorBehavior vo th khung cnh
http://tailieuhay.com
434
KeyNavigatorBehavior
public
BranchGroup
createSceneGraph(SimpleUniverse su) {
// Create the root of the branch graph
TransformGroup vpTrans = null;
BranchGroup
objRoot
new
BranchGroup();
objRoot.addChild(createLand());
// create other scene graph content
vpTrans
su.getViewingPlatform().getViewPlatformTransform
();
translate.set( 0.0f, 0.3f, 0.0f); // 3
meter elevation
T3D.setTranslation(translate);
//
set
as translation
vpTrans.setTransform(T3D); // used for
initial position
KeyNavigatorBehavior
keyNavBeh
new
KeyNavigatorBehavior(vpTrans);
keyNavBeh.setSchedulingBounds(new
BoundingSphere(new Point3d(),1000.0));
objRoot.addChild(keyNavBeh);
// Let Java 3D perform optimizations on
this scene graph.
objRoot.compile();
return objRoot;
http://tailieuhay.com
435
vo
cc
nhnh
PlatformGeometry,
view
khc
ca
ViewerAvatar, hoc
SimpleUniverse,
thm
mt
nh
tng
SimpleUniverse
is
Convenience
Utility class
SimpleUniverse
simpleU
new
SimpleUniverse(canvas3D);
BranchGroup
scene
createSceneGraph(simpleU);
http://tailieuhay.com
436
Lp tic ch tng tc bn phm thc thi hai lp. Trong thi gian chy
chng trnh c hai i tng. i tng u tin l i tng
KeyNavigatorBehavior, i tng th hai l KeyNavigator. Lp th hai
khng cn thit phi trnh by trong ti liu ny. i tng
KeyNavigatorBehavior thc hin hu ht tt c cc hm chc nng
truyn thng ca mt lp Behaviour, ngoi vic n gi n i tng
KeyNavigator
thc
hin
phng
thc
perform
the
http://tailieuhay.com
437
(com.sun.j3d.utils.behaviors.mouse) cha
http://tailieuhay.com
438
MouseRotateApp
renders
single,
objRotate
new
TransformGroup();
http://tailieuhay.com
439
objRotate.setCapability(TransformGroup.ALLOW_TRAN
SFORM_WRITE);
objRotate.setCapability(TransformGroup.ALLOW_TRAN
SFORM_READ);
objRoot.addChild(objRotate);
objRotate.addChild(new ColorCube(0.4));
objRoot.addChild(new Axis());
MouseRotate
myMouseRotate
new
MouseRotate();
myMouseRotate.setTransformGroup(objRotate);
myMouseRotate.setSchedulingBounds(new
BoundingSphere());
objRoot.addChild(myMouseRotate);
// Let Java 3D perform optimizations on
this scene graph.
objRoot.compile();
return objRoot;
}
//
end
of
CreateSceneGraph
method
of
MouseRotateApp
http://tailieuhay.com
440
SimpleUniverse
is
Convenience
Utility class
SimpleUniverse
simpleU
new
SimpleUniverse(canvas3D);
// This will move the ViewPlatform back
a bit so the
// objects in the scene can be viewed.
simpleU.getViewingPlatform().setNominalViewingTra
nsform();
simpleU.addBranchGraph(scene);
} // end of MouseRotateApp (constructor)
// The following allows this to be run as an
application
// as well as an applet
http://tailieuhay.com
441
\n-
moving
the
mouse
to
make
the
cube
rotate.");
System.out
.println("This
is
simple
frame
new
MainFrame(new
http://tailieuhay.com
442
http://tailieuhay.com
443
void
setTransformGroup(TransformGroup
TransformGroup)
Thit lp TransformGroup ch cho Behaviour
void wakeup()
Gi n phng thc wakeup.
MouseCallback Interface
http://tailieuhay.com
444
thay
Behaviour u phi thc thi giao din ny. Chng ta cng c th vit
phng thc transformChanged ca mt trong s cc lp kia xc nh
phng thc c gi khi i tng transform thay i
Cc phng thc Interface MouseBehaviorCallback
Gi: com.sun.j3d.utils.behaviors.mouse
void transformChanged(int type, Transform3D transform)
Lp thc thi giao din ny c dng k vi mt trong s cc
MouseBehaviors s c gi mi khi Behaviour cp nht transform.
Gi
tr
ca
type:
MouseCallback.ROTATE,
4.5.3 Cc lp MouseBehaviour
Mouse Rotate
Mt th khung cnh c cha mt i tng MouseRotate cho php
ngui dng quay i tng truqj quan. Chng ta s xem chi tit trong cc
v d MouseRotateApp,
MouseRotate2App, v MouseBehaviorApp.
Hm to MouseRotate Constructor
Gi: com.sun.j3d.utils.behaviors.mouse
Tha k : MouseBehavior
http://tailieuhay.com
445
http://tailieuhay.com
446
http://tailieuhay.com
447
http://tailieuhay.com
448
MouseBehavior.INVERT_INPUTS i tng
public
BranchGroup
createSceneGraph(SimpleUniverse su) {
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
TransformGroup vpTrans = null;
BoundingSphere mouseBounds = null;
vpTrans
su.getViewingPlatform().getViewPlatformTransform
();
objRoot.addChild(new ColorCube(0.4));
objRoot.addChild(new Axis());
http://tailieuhay.com
449
myMouseRotate
new
MouseRotate(MouseBehavior.INVERT_INPUT);
myMouseRotate.setTransformGroup(vpTrans)
;
myMouseRotate.setSchedulingBounds(mouseB
ounds);
objRoot.addChild(myMouseRotate);
MouseTranslate myMouseTranslate = new
MouseTranslate(MouseBehavior.INVERT_INPUT);
myMouseTranslate.setTransformGroup(vpTra
ns);
myMouseTranslate.setSchedulingBounds(mou
seBounds);
objRoot.addChild(myMouseTranslate);
MouseZoom
myMouseZoom
new
MouseZoom(MouseBehavior.INVERT_INPUT);
myMouseZoom.setTransformGroup(vpTrans);
myMouseZoom.setSchedulingBounds(mouseBou
nds);
objRoot.addChild(myMouseZoom);
// Let Java 3D perform optimizations on this
scene graph.
objRoot.compile();
http://tailieuhay.com
450
return objRoot;
}
//
end
of
CreateSceneGraph
method
of
MouseNavigatorApp
Kt qu cho ta l:
http://tailieuhay.com
451
http://tailieuhay.com
452
im
khc
ca
lp
Node
kh
nng
http://tailieuhay.com
453
http://tailieuhay.com
454
phn
ny
PickRotateBehavior,
chng
ta
gii
thiu
PickTranslateBehavior,
cc
lp
tin
ch
PickZoomBehavior.
Trong phn tip theo 4.6.2 chng ta gii thiu cc lp hay s dng trong
vic to ra cc lp picking mi.
Do mi i tng picking behavior object c kh nng thc hin vi
bt k i tng th khung cnh, v vy ch cn mt i tng picking
behavior cung cp kh nng picking on code di y m t cng
vic cn thit s dng cc lp picking behavior trong mt chng trnh
Java 3D
http://tailieuhay.com
455
456
transform
new
Transform3D();
BoundingSphere
behaveBounds
new
BoundingSphere();
//
create
ColorCube
and
PickRotateBehavior objects
transform.setTranslation(new Vector3f(0.6f, 0.0f, -0.6f));
objRotate
new
TransformGroup(transform);
objRotate.setCapability(TransformGroup.AL
LOW_TRANSFORM_WRITE);
objRotate.setCapability(TransformGroup.AL
LOW_TRANSFORM_READ);
objRotate.setCapability(TransformGroup.EN
ABLE_PICK_REPORTING);
objRoot.addChild(objRotate);
objRotate.addChild(new ColorCube(0.4));
pickRotate
PickRotateBehavior(objRoot,
new
canvas,
behaveBounds);
http://tailieuhay.com
457
new
TransformGroup(transform);
objRotate.setCapability(TransformGroup.AL
LOW_TRANSFORM_WRITE);
objRotate.setCapability(TransformGroup.AL
LOW_TRANSFORM_READ);
objRotate.setCapability(TransformGroup.EN
ABLE_PICK_REPORTING);
objRoot.addChild(objRotate);
objRotate.addChild(new ColorCube(0.4));
// Let Java 3D perform optimizations on this
scene graph.
objRoot.compile();
return objRoot;
}
//
end
of
CreateSceneGraph
method
of
MousePickApp
http://tailieuhay.com
458
459
S ph h PickShape
PickShape
Lp con: PickBounds, PickRay, PickSegment, PickPoint, and PickCone
PickBounds
i tng PickBounds th hin mt khung cho pick testing.
http://tailieuhay.com
460
http://tailieuhay.com
461
http://tailieuhay.com
462
463
origin,
Point3d
end,
double
http://tailieuhay.com
464
http://tailieuhay.com
465
http://tailieuhay.com
466
467
4.6.3 Cc lp picking
Nhng lp picking ni chung c dng hiu qu trong vic to ra
cc picking behavior . Cc lp : PickMouseBehavior, PickObject,v
PickCallback.
PickMouseBehavior Class
Lp c s cung cp cc phng thc picking behavior.Lp ny cn
rt hiu qu trong vic xy dung cc picking class sau ny bng vic
tha k n.
PickMouseBehavior Method Summary
http://tailieuhay.com
468
PickObject Class
Lp PickObject cung cp cc phng thc xc nh i tng no
oc chn bi hnh ng pick ca ngi dng.
PickObject Constructor Summary
Gi: com.sun.j3d.utils.behaviors.picking
Tha k : java.lang.Object
PickObject(Canvas3D c, BranchGroup root)
Hm to PickObject.
http://tailieuhay.com
469
xc
nh
gi
tr
ca
kiu
node:
PickObject.BRANCH_GROUP,
PickObject.GROUP,
PickObject.LINK,
PickObject.MORPH,
PickObject.PRIMITIVE,
PickObject.SHAPE3D,
PickObject.SWITCH,
PickObject.TRANSFORM_GROUP.
Node pickNode(SceneGraphPath sgPath, int node_types, int
occurrence)
PickingCallback Interface
Giao din PickingCallback cung cp mt khng lm vic tha k
mt lp picking c trc.
Interface PickingCallback Method Summary
http://tailieuhay.com
470
http://tailieuhay.com
471
segmentAndLine(PickSegment
segment,
Point3d[]
segmentAndQuad(PickSegment
segment,
Point3d[]
segmentAndTriangle(PickSegment
segment,
Point3d[]
coordinates,
int index, double[] dist)
http://tailieuhay.com
472
PickMode
PickObject.USE_BOUNDS
hay
lp
gi
tr
pickMode:
nhn
mt
trong
cc
gi
tr
PickObject.USE_BOUNDS hay
PickObject.USE_GEOMETRY.
void setupCallback(PickingCallback callback)
void transformChanged(int type, Transform3D transform)
void updateScene(int xpos, int ypos)
PickTranslateBehavior
Lp PickTranslateBehavior cho php ngi dung tng tc pick v
translate
tng
trc
quan.
Mt
th
hin
ca
lp
http://tailieuhay.com
473
root,
Canvas3D
canvas,
Bounds bounds)
Khi to hnh vi pick/translate ch s kin t chut trong th khung
cnh
PickTranslateBehavior(BranchGroup
root,
Canvas3D
canvas,
Bounds bounds,
int pickMode)
http://tailieuhay.com
474
http://tailieuhay.com
475
thm cc hot nh
n gin
S dng cc lp LOD
476
http://tailieuhay.com
477
478
bi tham s
http://tailieuhay.com
479
http://tailieuhay.com
480
v i tng ch
4. thm cc gii hn cho i tng Interpolator
5. thm i tng Interpolator vo th khung cnh
http://tailieuhay.com
481
khc
482
objSpin
new
TransformGroup();
objSpin.setCapability(TransformGroup.ALL
OW_TRANSFORM_WRITE);
// create Alpha that continuously
rotates with a period of 1 minute
Alpha alpha = new Alpha (-1, 60000);
// create rotation about y-axis
RotationInterpolator
rotInt
new
background
new
Background();
background.setColor(1.0f, 1.0f, 1.0f);
background.setApplicationBounds(new
BoundingSphere());
http://tailieuhay.com
483
http://tailieuhay.com
484
http://tailieuhay.com
485
Time ~ 1.2s
Time ~ 0.8s
Time ~ 1.6s
486
http://tailieuhay.com
487
lp
http://tailieuhay.com
gi
tr
xc
nh
cho
thuc
tnh
488
lp
gi
tr
xc
nh
cho
thuc
tnh
mode
th
INCREASING_ENABLE
hoc
489
l mt i tng hnh vi
http://tailieuhay.com
490
chc nng
thay i
kiu i tng ch
mu Material
Trang
5-12
khuych tn ca
PathInterpolator
PositionInterpolator
mt i tng
lp tru tng TransformGroup
thay i v tr TransformGroup
5-20
5-14
RotationInterpolator
ca i tng
thay i chuyn TransformGroup
5-15
http://tailieuhay.com
491
quay
(hng) ca i
ScaleInterpolator
tng
thay i kch c TransformGroup
ca i tng
SwitchValueInterpolator la chn mt Switch
5-16
5-17
thay i (switch)
trong mt b cc
i tng
TransparencyInterpolator thay i mc TransparencyAttributes 5-19
trong sut ca
i tng
Bng 5-1. Tm tt cc lp Interpolator c bn
Ch : PathInterpolator l mt lp tru tng, nn khng c i
tng ch. Tuy nhin, bt c lp no tha k lp ny u c i tng
ch thuc kiu Transformation.
hiu thm hiu ng ca cc Interpolator
ny, hy xem v d
ScaleInterpolator,
ColorInterpolator,
http://tailieuhay.com
492
http://tailieuhay.com
493
//
InterpolatorApp renders an
new
QuadArray(16,
GeometryArray.COORDINATES
|
GeometryArray.NORMALS);
else
carGeom
new
QuadArray(16,
GeometryArray.COORDINATES);
carGeom.setCoordinate(
0,
new
1,
new
2,
new
http://tailieuhay.com
494
3,
new
4,
new
5,
new
6,
new
7,
new
8,
new
9,
new
new
new
new
new
new
new
http://tailieuhay.com
495
carAppear
new
Appearance();
carAppear.setColoringAttributes(color
Attrib);
car.setAppearance(carAppear);
}
car.setGeometry(carGeom);
return car;
}
public BranchGroup createSceneGraph() {
// Create the root of the branch graph
BranchGroup objRoot = new BranchGroup();
Transform3D t3d = new Transform3D();
http://tailieuhay.com
496
bounds
new
BoundingSphere();
// create target TransformGroup with
Capabilities
TransformGroup
objMove
new
TransformGroup();
objMove.setCapability(TransformGroup.ALLO
W_TRANSFORM_WRITE);
// create target TransformGroup with
Capabilities
TransformGroup
objRotate
new
TransformGroup();
objRotate.setCapability(TransformGroup.AL
LOW_TRANSFORM_WRITE);
// create target TransformGroup with
Capabilities
TransformGroup
objScale
new
TransformGroup();
objScale.setCapability(TransformGroup.ALL
OW_TRANSFORM_WRITE);
//
create
target
Material
with
Capabilities
Material objColor = new Material();
objColor.setCapability(Material.ALLOW_COM
PONENT_WRITE);
http://tailieuhay.com
497
posInt
new
http://tailieuhay.com
498
rotInt
new
new
new
scaInt
colInt
http://tailieuhay.com
499
objMovePos
new
TransformGroup(t3d);
objRoot.addChild(objMovePos);
objMovePos.addChild(objMove);
objMove.addChild(createCar(0.4f, 0.4f,
false, true));
objRoot.addChild(posInt);
t3d.setTranslation(new Vector3f(0.0f,
0.5f, 0.0f));
TransformGroup
objRotPos
new
TransformGroup(t3d);
objRoot.addChild(objRotPos);
objRotPos.addChild(objRotate);
objRotate.addChild(createCar(0.4f, 0.4f,
false, true));
objRoot.addChild(rotInt);
t3d.setTranslation(new Vector3f(0.0f,
0.2f, 0.0f));
TransformGroup
objScalePos
new
TransformGroup(t3d);
objRoot.addChild(objScalePos);
objScalePos.addChild(objScale);
objScale.addChild(createCar(0.4f, 0.4f,
false, true));
objRoot.addChild(scaInt);
http://tailieuhay.com
500
t3d.setTranslation(new Vector3f(0.0f,
-0.2f, 0.0f));
TransformGroup
objColorPos
new
TransformGroup(t3d);
objRoot.addChild(objColorPos);
Shape3D colorCar = createCar(0.4f, 0.4f,
true, false);
Appearance
materialAppear
new
Appearance();
materialAppear.setMaterial(objColor);
colorCar.setAppearance(materialAppear);
objColorPos.addChild(colorCar);
objRoot.addChild(colInt);
t3d.setTranslation(new Vector3f(0.0f,
-0.5f, 0.0f));
TransformGroup
objTranspPos
new
TransformGroup(t3d);
objRoot.addChild(objTranspPos);
Shape3D transpCar = createCar(0.4f, 0.4f,
false, true);
Appearance
transpAppear
transpCar.getAppearance();
transpAppear.setTransparencyAttributes(ob
jTransp);
objTranspPos.addChild(transpCar);
objRoot.addChild(traInt);
http://tailieuhay.com
501
objSwitchPos
new
TransformGroup(t3d);
objRoot.addChild(objSwitchPos);
objSwitch.addChild(createCar(0.4f, 0.4f,
false, true));;
objSwitch.addChild(new ColorCube(0.1f));
objSwitchPos.addChild(objSwitch);
objRoot.addChild(swiInt);
swiInt.setLastChildIndex(2);// since
switch made after interpolator
DirectionalLight
lightD1
new
DirectionalLight();
// lightD1.setDirection(new Vector3f(-0.7f,0.7f,0.0f));
lightD1.setInfluencingBounds(bounds);
objRoot.addChild(lightD1);
Background background = new Background();
background.setColor(1.0f, 1.0f, 1.0f);
background.setApplicationBounds(new
BoundingSphere());
objRoot.addChild(background);
// Let Java 3D perform optimizations on this
scene graph.
objRoot.compile();
http://tailieuhay.com
502
return objRoot;
}
//
end
of
CreateSceneGraph
method
of
InterpolatorApp
// Create a simple scene and attach it to the
virtual universe
public InterpolatorApp() {
setLayout(new BorderLayout());
Canvas3D canvas3D = new Canvas3D(null);
add("Center", canvas3D);
BranchGroup scene = createSceneGraph();
// SimpleUniverse is a Convenience
Utility class
SimpleUniverse
simpleU
new
SimpleUniverse(canvas3D);
// This will move the ViewPlatform back a bit
so the
// objects in the scene can be viewed.
simpleU.getViewingPlatform().setNominalVi
ewingTransform();
simpleU.addBranchGraph(scene);
} // end of InterpolatorApp (constructor)
http://tailieuhay.com
503
application
//
as well as an applet
frame
new
MainFrame(new
504
http://tailieuhay.com
505
http://tailieuhay.com
506
507
508
http://tailieuhay.com
509
http://tailieuhay.com
510
http://tailieuhay.com
511
CHILD_MASK
http://tailieuhay.com
512
513
http://tailieuhay.com
514
3. to cc mng im mt v cc gi tr khc
4. to i tng ni suy ng tham chiu n i tng Alpha, i
trnh
RotPosPathApp.java
dng
tng
515
target
new
new
TransformGroup();
Transform3D
axisOfRotPos
Transform3D();
float[] knots = {0.0f, 0.1f, 0.2f, 0.3f,
0.4f, 0.6f, 0.8f, 0.9f, 1.0f};
Quat4f[] quats = new Quat4f[9];
Point3f[] positions = new Point3f[9];
target.setCapability(TransformGroup.ALLOW
_TRANSFORM_WRITE);
AxisAngle4f
axis
new
AxisAngle4f(1.0f,0.0f,0.0f,0.0f);
axisOfRotPos.set(axis);
quats[0] = new Quat4f(0.0f, 1.0f, 1.0f,
0.0f);
quats[1] = new Quat4f(1.0f, 0.0f, 0.0f,
0.0f);
quats[2] = new Quat4f(0.0f, 1.0f, 0.0f,
0.0f);
http://tailieuhay.com
516
0.0f,
0.0f,
1.0f, -1.0f,
-1.0f);
-2.0f);
positions[2]= new Point3f( -1.0f,
1.0f,
0.0f,
-3.0f);
2.0f,
-4.0f);
positions[4]= new Point3f( -2.0f, -1.0f,
-5.0f);
positions[5]= new Point3f(
3.0f,
1.0f,
0.0f,
-6.0f);
-7.0f);
positions[7]= new Point3f(
2.0f, -1.0f,
-4.0f);
positions[8]= positions[0];
http://tailieuhay.com
517
objRoot.addChild(target);
objRoot.addChild(rotPosPath);
target.addChild(new ColorCube(0.4));
Background background = new Background();
background.setColor(1.0f, 1.0f, 1.0f);
background.setApplicationBounds(new
BoundingSphere());
objRoot.addChild(background);
PointArray point_geom = new PointArray(9,
GeometryArray.COORDINATES);
point_geom.setCoordinates(0, positions);
Appearance
points_appear
new
Appearance();
ColoringAttributes points_coloring = new
ColoringAttributes();
points_coloring.setColor(1.0f, 0.0f,
0.0f);
http://tailieuhay.com
518
//
end
of
CreateSceneGraph
method
of
RotPosPathApp
on m trn c trch khng ton vn t phng thc
createSceneGraph trong chng trnh RotPosPathApp.java bn c c
hnh dung s qua v cch s dng mt i tng ni suy ng:
RotPosPathInterpolator. Cc bc thc hin c nh s t 1-6 tng
ng vi cc bc trong cng thc.
Hnh 5-13 l mt cnh trong chng trnh RotPosPathApp, vi cc
im mu biu din v tr ca 9 im mt. im u tin c dng 2
ln, nn trong hnh, chng ta ch thy c 8 im.
http://tailieuhay.com
519
http://tailieuhay.com
520
PathInterpolator
PathInterpolator l mt lp tru tng cung cp giao din v chc
nng c bn cho cc lp con ca n. Cc i tng PathInterpolator lu
tr cc gi tr im mt v tnh ton ch mc ca cc gi tr ny s
dng
da
trn
gi
tr
Alpha
thi
gian
hin
thi
http://tailieuhay.com
521
http://tailieuhay.com
522
http://tailieuhay.com
523
524
TransformGroup
3. thm danh gii lm vic cho i tng Billboard
4. lp ghp th
Hnh 5-15. Cng thc s dng i tng Billboard to hot nh
Cc li thng gp khi s dng Billboard
Mc d vic s dng i tng Billboard khng h phc tp, nhng
cng c hai li lp trnh thng gp sau. Li th nht xy ra do i tng
ch TransformGroup thit lp li hon ton gi tr ca n mi khi c
cp nht. Do , i tng TransformGroup ny khng th s dng
nh v i tng trc quan. Nu dng i tng ch nh v, hiu ng
Billboard vn hot ng, tuy nhin, trong ln cp nht quay u tin,
thng tin v tr ca i tng ch s b mt v i tng trc quan s
c hin th ti v tr ban u.
Nu
tng
ch
khng
thit
lp
thuc
tnh
525
BranchGroup
createSceneGraph(SimpleUniverse su) {
// Create the root of the branch graph
TransformGroup vpTrans = null;
BranchGroup objRoot = new BranchGroup();
Vector3f translate = new Vector3f();
http://tailieuhay.com
526
bSphere
new
BoundingSphere();
objRoot.addChild(createLand());
SharedGroup share = new SharedGroup();
share.addChild(createTree());
float[][]
position
0.0f,
0.0f,
13.0f,
0.0f,
-30.0f
},
-13.0f,
0.0f,
23.0f
},
http://tailieuhay.com
527
TGR.setCapability(TransformGroup.ALLOW_TRANSFORM_
WRITE);
billboard = new Billboard(TGR);
billboard.setSchedulingBounds(bSphere);
//
billboard.setAlignmentMode(Billboard.ROTATE_ABOUT
_POINT);
objRoot.addChild(TGT);
objRoot.addChild(billboard);
TGT.addChild(TGR);
TGR.addChild(new Link(share));
}
vpTrans
su.getViewingPlatform().getViewPlatformTransform(
);
translate.set(0.0f, 0.3f, 0.0f);
T3D.setTranslation(translate);
vpTrans.setTransform(T3D);
KeyNavigatorBehavior
keyNavBeh
new
KeyNavigatorBehavior(vpTrans);
keyNavBeh
.setSchedulingBounds(new
BoundingSphere(new Point3d(), 1000.0));
objRoot.addChild(keyNavBeh);
Background
background
new
Background();
http://tailieuhay.com
528
//
end
BillboardAppon
of
m
CreateSceneGraph
trn
trch
method
of
phng
thc
trong
BillboardApp.java
Hnh 5-17 hin th mt cnh sinh bi chng trnh v d BillboardApp.
http://tailieuhay.com
529
BillboardApp.java cung cp
http://tailieuhay.com
530
()
vi tham s mc nh: mode =
trc xc nh
ROTATE_ABOUT_POINT - Ch nh quay xung quanh mt im
xc nh v ch nh rng trc Y ca i tng con phi ph hp vi trc
Y ca i tng c quan st
void setRotationPoint(Point3f point)
Thit lp tm quay
void setRotationPoint(float x, float y, float z)
Thit lp tm quay
http://tailieuhay.com
531
http://tailieuhay.com
532
http://tailieuhay.com
533
http://tailieuhay.com
534
535
536
cc
tng
Switch
ch
vi
kh
nng
ALLOW_SWITCH_WRITE
2. to danh sch mng cc ngng khong cch cho i tng
DistanceLOD
3. to i tng DistanceLOD s dng mng cc ngng khong
cch
4. thit lp i tng Switch ch cho i tng DistanceLOD
http://tailieuhay.com
537
http://tailieuhay.com
538
bounds
new
BoundingSphere();
// create target TransformGroup with
Capabilities
TransformGroup
objMove
new
TransformGroup();
objMove.setCapability(TransformGroup.ALLO
W_TRANSFORM_WRITE);
// create Alpha
Alpha alpha = new Alpha (-1,
Alpha.INCREASING_ENABLE
+ Alpha.DECREASING_ENABLE,
0, 0, 5000, 1000, 1000,
5000, 1000, 1000);
// specify the axis of translation
AxisAngle4f
axisOfTra
new
AxisAngle4f(0.0f,1.0f,0.0f,(float)Math.PI/-2.0f);
Transform3D axisT3D = new Transform3D();
axisT3D.set(axisOfTra);
// create position interpolator
http://tailieuhay.com
539
sphereAppearA
new
ColoringAttributes sphereCAa =
new
Appearance();
ColoringAttributes();
sphereCAa.setColor(0.1f, 0.8f, 0.1f);
sphereAppearA.setColoringAttributes(spher
eCAa);
Appearance
sphereAppearB
new
ColoringAttributes sphereCAb =
new
Appearance();
ColoringAttributes();
sphereCAb.setColor(0.8f, 0.1f, 0.1f);
sphereAppearB.setColoringAttributes(spher
eCAb);
http://tailieuhay.com
540
dLOD
new
http://tailieuhay.com
541
// target
// add
position interpolator
objMove.addChild(dLOD);
// make
tga
new
TransformGroup(t3d);
objRoot.addChild(tga);
tga.addChild(new Sphere(.40f, 0,
4,
sphereAppearB));
// show a level 0 object at a distance
for comparison
t3d.set(new
Vector3f(-5.0f,
0.0f,
-35.0f));
TransformGroup
tgb
new
tgb.addChild(new Sphere(.40f, 0,
25,
TransformGroup(t3d);
objRoot.addChild(tgb);
sphereAppearA));
http://tailieuhay.com
542
//
end
of
CreateSceneGraph
method
of
DistanceLODApp
Hnh 5-19 biu din biu th khung cnh c to ra trong v d
trn. Ch rng, i tng Switch ch va l con ca i tng
TransformGroup va c tham chiu n bi i tng DistanceLOD.
C hai quan h ny u cn c xc lp.
http://tailieuhay.com
543
http://tailieuhay.com
544
da
nu d <= distances[0]
http://tailieuhay.com
545
http://tailieuhay.com
546
http://tailieuhay.com
547
mt
tng
Morph
vi
kh
nng
ALLOW_WEIGHTS_WRITE
3. lp ghp th khung cnh, bao gm c vic thm cc con cho i
tng ch Switch
Hnh 5-21. Cng thc s dng i tng Morph
Nh trnh by, s dng i tng Morph khng kh, tuy nhin,
cc bc ny ng cho c hot nh v tng tc. Hot nh v tng tc
c cung cp thng qua mt i tng hnh vi. Do , s dng i
tng Morph thng c ngha l vit mt lp hnh vi. Cch vit lp
hnh vi c trnh by trong phn 4.2.1, nn y khng ni chi tit.
Tt nhin, Morph hon ton c th s dng m khng cn i tng
hnh vi, nhng n s khng th to ra c hot nh.
V d s dng Morph
Chng trnh Morph ny s dng mt i tng hnh vi ty chnh
sinh hot nh. Bc u tin trong qu trnh pht trin s l xy dng
lp hnh vi ny.
http://tailieuhay.com
548
http://tailieuhay.com
549
alphaValue
4f
alpha.value() - 0.00001f;
int alphaIndex = (int) alphaValue;
weights[alphaIndex] = (double)
alphaValue - (double)alphaIndex;
if(alphaIndex < 3)
weights[alphaIndex + 1] = 1.0 weights[alphaIndex];
else
weights[0]
1.0
weights[alphaIndex];
targetMorph.setWeights(weights);
// set next wakeup condition
this.wakeupOn(trigger);
}
} // end of class MorphBehavior
http://tailieuhay.com
550
http://tailieuhay.com
551
translate
new
TransformGroup(t3d);
// create GeometryArray[] (array of
GeometryArray objects)
GeometryArray[]
geomArray
new
GeometryArray[4];
geomArray[0] = createGeomArray0();
geomArray[1] = createGeomArray1();
geomArray[2] = createGeomArray2();
geomArray[3] = createGeomArray3();
// create morph object
Morph morphObj = new Morph(geomArray);
morphObj.setCapability(Morph.ALLOW_WEIGH
TS_WRITE);
// create alpha object
Alpha alpha = new Alpha(-1, 1, 0, 0,
2000, 100, 0, 0, 0, 0);
// create morph driving behavior
MorphBehavior
morphBehav
new
MorphBehavior(morphObj, alpha);
http://tailieuhay.com
552
background
new
Background();
background.setColor(1f, 1f, 1f);
background.setApplicationBounds(new
BoundingSphere());
objRoot.addChild(background);
// Let Java 3D perform optimizations on this
scene graph.
objRoot.compile();
return objRoot;
} // end of CreateSceneGraph method of
MorphApp
Mt ch th v rt ra t v d trn l nhiu hot nh khc nhau c
th c to ra, s dng chnh cc khung hnh chnh c xy dng
trn, vi cc lp hnh vi khc nhau. Hnh 5-23 biu din mt cnh sinh ra
bi Morph3DApp. Trong chng trnh ny, 3 lp hnh vi khc nhau to
hot nh da trn mt s hoc tt c i tng GeometryArray ca
MorphApp. Chng c gi ln lt (t tri qua phi) l In Place,
Tango, v Broken.
http://tailieuhay.com
553
554
http://tailieuhay.com
555
http://tailieuhay.com
556
http://tailieuhay.com
557
. Trng
http://tailieuhay.com
558
, N l s lng cc
. S lng cc nh l N*2, bi mi
u tin thit
th 2
nh.
http://tailieuhay.com
559
GeometryUpdater
geometryUpdater
new WaterUpdater();
Geometry createWaterGeometry() {
int N = 1400; // number of 'drops'
waterLines
new
LineArray(N
2,
LineArray.COORDINATES
| LineArray.BY_REFERENCE);
waterLines.setCapability(GeometryArray.ALLOW_REF_
DATA_WRITE);
waterLines.setCapability(GeometryArray.ALLOW_REF_
DATA_READ);
http://tailieuhay.com
560
waterLines.setCapability(GeometryArray.ALLOW_COUN
T_READ);
float[] coordinates = new float[N * 3 *
2];
int p;
for (p = 0; p < N; p += 2) { // for each
particle
coordinates[p * 3 + 0] = 0.0f;
coordinates[p
1]
4]
baseElevation;
coordinates[p * 3 + 2] = 0.0f;
coordinates[p * 3 + 3] = 0.0f;
coordinates[p
baseElevation;
coordinates[p * 3 + 5] = 0.0f;
}
waterLines.setCoordRefFloat(coordinates);
//
the
following
statements
would
be
redundant
// waterLines.setInitialCoordIndex(0);
// waterLines.setValidVertexCount(N*2);
return waterLines;
}
http://tailieuhay.com
561
abstract
class
UpdateWaterBehavior
extends
Behavior {
WakeupOnElapsedFrames w = null;
public UpdateWaterBehavior() {
w = new WakeupOnElapsedFrames(0);
}
public void initialize() {
wakeupOn(w);
}
public
void
processStimulus(Enumeration
critiria) {
waterLines.updateData(geometryUpdater);
wakeupOn(w);
} // end processStimulus
} // end class UpdateWaterBehavior
public
class
WaterUpdater
implements
GeometryUpdater {
Random random;
public WaterUpdater() {
http://tailieuhay.com
562
void
updateData(Geometry
geometry) {
GeometryArray
geometryArray
(GeometryArray) geometry;
float[]
coords
geometryArray.getCoordRefFloat();
int
geometryArray.getValidVertexCount();
int i;
for (i = 0; i < N; i += 2) { // for
each particle
if
(coords[i
1]
>
0]
+=
1]
+=
coords[i * 3 + 1] - coords[i * 3 + 4]
- 0.01f; // y1
coords[i
2]
+=
3]
http://tailieuhay.com
563
4]
5]
(coords[i
1]
<
baseElevation) { // if particle
// below base
coords[i
0]
coords[i
1]
coords[i
2]
coords[i
3]
coords[i
4]
coords[i
5]
0.0f; // x1
baseElevation; // y1
0.0f; // z1
0.0f; // x2
baseElevation; // y2
0.0f; // z2
}
} else { // an inactive particle
if
(random.nextFloat()
>
0]
http://tailieuhay.com
564
1]
2]
0.14f * random.nextFloat()
+
baseElevation; // y1
coords[i
dn
nhn
Phng
thc
UpdateWaterBehavior, bt u t dng m
initialize()
ca
lp
, thit lp iu kin nh
, nh
http://tailieuhay.com
565
class
UpdateWaterBehavior
extends
Behavior {
WakeupOnElapsedFrames w = null;
public UpdateWaterBehavior() {
w = new WakeupOnElapsedFrames(0);
}
public void initialize() {
wakeupOn(w);
}
public
void
processStimulus(Enumeration
critiria) {
waterLines.updateData(geometryUpdater);
wakeupOn(w);
} // end processStimulus
} // end class UpdateWaterBehavior
on m sau nh ngha lp GeometryUpdater. GeometryUpdater
dch chuyn cc phn t nc bng cch thay i d liu ta ca
chng.
Lp GeometryUpdater trong ng dng ny c mt hm khi to v
mt phng thc. Trong hm khi to, nhn
, mt i tng Random
http://tailieuhay.com
566
nh c ly ra. Dng
. Vi mi phn t
567
. Trong v d ny,
class
WaterUpdater
implements
GeometryUpdater {
Random random;
public WaterUpdater() {
random = new Random();
}
public
void
updateData(Geometry
geometry) {
GeometryArray
geometryArray
coords
(GeometryArray) geometry;
float[]
geometryArray.getCoordRefFloat();
int
geometryArray.getValidVertexCount();
int i;
for (i = 0; i < N; i += 2) { // for
each particle
if
(coords[i
1]
>
http://tailieuhay.com
568
// particles
coords[i
0]
+=
1]
+=
coords[i * 3 + 1] - coords[i * 3 + 4]
- 0.01f; // y1
coords[i
2]
+=
3]
1]
coords[i
3
*
+
3
4]
+
4]
=
+
0.01f) / 2;// y2
coords[i
5]
(coords[i
1]
<
coords[i
0]
coords[i
1]
coords[i
2]
baseElevation) { // if particle
// below base
0.0f; // x1
baseElevation; // y1
0.0f; // z1
http://tailieuhay.com
569
3]
coords[i
4]
coords[i
5]
0.0f; // x2
baseElevation; // y2
0.0f; // z2
}
}
else
//
an
inactive
particle
if
(random.nextFloat()
>
0]
1]
2]
0.14f * random.nextFloat()
+
baseElevation; // y1
coords[i
cch
thm
tng
LineAttributes
vi
http://tailieuhay.com
570
http://tailieuhay.com
571
http://tailieuhay.com
572