DirectX9 3D quick start 6

xiaoxiao2021-03-05  23

DirectX9 3D quick start 6

By SSSA2000

4/25/2005

Telling a lot, the most basic part is not told. Texture is a very important part of DirectX. For the sake of simplicity, we still use SDK Tutorial5 as an example.

Texture is like a wallpaper, which is used to attach the surface of the object. Of course, if it is large enough, it can cover the surface of the entire object, or use the appropriate method to allow textures to be used as your desired effect.

Take a look at the comparison of textures: device.setTexture

Public void settexture (int Stage, // Texture mixed phase serial number, starting the texture object to be set);

Public Void SetTexturestageState (int Stage, // Texture Mixed Phamentation Texturestagestates State, // TextureStageStates Enumeration member int value // Value of the corresponding phase status);

The SetTextureStageState function is applied to handle different texture coordinates, color operations, alpha operations, and concave-convex mapping / environment mapping, but these operations are only valid for the multi-texture unit of DX9's fixed function, and they cannot be used with pixels Shader.

Public void setsamplerstate (int Stage, // Texture Mixed Phament No. SamplerStageStates State, // SamplerStageStates Enumeration member int value // Value of the status of the sampler);

I know that these codes are very easy, we need to build Vertex, here we need to have a little change, do not involve the texture in the previous Vertex, so we chose the CustomvertEx inside the texture Type, now we have to use customTomvertEx.positionnormaltext, you can see from the name, including the normal X, Y, Z, and Texture coordinate TU and TV.

Of course, if you use CustomvertEX.PositionTexTexture, it does not include normal information.

Next, we need to specify information for each Vertex. Let's first interrupted the texture coordinates. In order to access each of the textures in the texture by specifying the texture coordinates, DX uses a generalized addressing scheme, texture address The coordinates in the [0.0, 1.0] interval consist, so we don't have to care about the actual size of the texture, for example,

0.0F

,

0.0F

)

1.0f

,

0.0F

)

1.0F

,

1.0f

)

0.0F

,

1.0f

) Post a texture to a rectangle, if

0.0F

,

0.0F

), (0.

5F

,

0.0F

), (0.5,

1.0f

)

0.0F

,

1.0F

) The left half of the texture.

We can read the picture as a texture through the TextureLoader.FromFile method.

The code here is very simple, there is a detailed note, I don't talk much,

/ / -------------------------------------------------------------------------------------------- -----------------------------

// File: Texture.cs

//

// Desc: Better Than Just Lights and Materials, 3D Objects Look Much More

// convincening when texture-mapped. TEXTURES Can Be Thought of as a Sort // of Wallpaper, That Is ShrinkWrapped to Fit A Texture. Textures Are

// Typically Loaded from Image Files, and D3DX Provides a Utility To

// function to do this for us. Like a Vertex Buffer, Textures Have

// Lock () and unlock () Functions to access (read or write) the Image

// Data. Textures Have a Width, Height, Miplevel, And Pixel Format. The

//Miplevel is for "mipmapped" textures, an advanced performance-

// Enhancing Feature Which Uses Lower Resolutions of The Texture for

// Objects in the distance where detail is less noticeable. The Pixel

// Format Determines How The Colors Are Stored in A TEXEL. The MOST

// Common Formats Are The 16-bit r

5G

6B5 Format (5 Bits of Red, 6-bits of

// Green and 5 bits of blue) and the 32-bit a8r

8G

8b8 Format (8 BITS EACH

// of alpha, red, green, and blue).

//

// Textures Are Associated with Geometry THROUGH TEXTURE COORDINATES.

// Each Vertex Has One or More Sets of Texture Coordinates, Which Are

// Named Tu and TV and Range from 0.0 to 1.0. Texture Coordinates Can Be

// Supplied by the geometry, or can be automaticly generated using

// Direct3D Texture Coordinate Generation (Which is an advanced feature).

//

// Copyright (c) Microsoft Corporation. All Rights Reserved.

/ / -------------------------------------------------------------------------------------------- -----------------------------

Using system;

Using system.drawing;

Using system.windows.forms;

Using Microsoft.directX;

Using Microsoft.directx.direct3d;

USING DIRECT3D = Microsoft.directx.direct3d;

Namespace Texturetututorial

{

Public Class Textures: form {

// Our Global Variables for this Project

Device device = NULL; // ur rendering Device

VertexBuffer VertexBuffer = NULL;

TEXTURE TEXTURE = NULL;

PresentParameters Presentparams = New Presentparameters ();

Bool pause = false;

Public textures ()

{

// set the initial size of ot form

THIS.CLIENTSIZE = New System.drawing.size (400, 300);

// and ITS CAPTION

THIS.TEXT = "Direct3D Tutorial 5 - Textures";

}

Public Bool Initializegraphics ()

{

Try

{

Presentparams.windowed = true; // we don't want to run fullullscreen

Presentparams.swapeffect = swapeffect.discard; // discard the frames

Presentparams.enableautodepthstencil = true; // Turn ON A Depth Stencil

Presentparams.autodepthstencilFormat = depthformat.d16; // and the stencil format

Device = New Device (0, DeviceType.hardware, this, createflags.softwarevertexprocessing, presentparams); // Create a Device

Device.DeviceReset = New System.EventHandler (this.onResetDevice);

This.oncreateDevice (Device, NULL);

This.onResetDevice (Device, NULL);

Pause = false;

Return True;

}

Catch (DirectxException)

{

// catch Any Errors and Return A Failure

Return False;

}

}

Public Void OncreateDevice (Object Sender, Eventargs E)

{

Device dev = (device) sender;

// now crete the VB

VertexBuffer = New VertexBuffer (TypeOf (CustomvertEx.positionNormaltext, 100, Dev, Usage.writeonly, CustomvertEx.PositionNormaltexTured.Format, pool.default);

VertexBuffer.created = New System.EventHandler (this.oncreatevertexbuffer);

This.oncreateVertexBuffer (VertexBuffer, NULL);

}

Public void OnResetDevice (Object Sender, Eventargs E)

{

Device dev = (device) sender;

// Turn Off Culling, So We See The Front and Back of The Triangledev.renderstate.cullMode = Cull.none;

// Turn Off D3D Lighting

Dev.renderstate.lighting = false;

// Turn on the zbuffer

Dev.renderstate.zbufferenable = true;

// now create Our Texture

Texture = TextureLoader.FromFile (dev, application.startuppath @ "/../../ banana.bmp");

}

Public void oncreatevertexbuffer (Object Sender, Eventargs E)

{

VertexBuffer VB = (VertexBuffer) Sender;

// Create a Vertex Buffer (100 Customervertex)

Customvertex.positionNormaltexTured [] VERTS = (CustomvertEx.positionNormaltexTured []) VB.Lock (0, 0); // Lock The Buffer (Which Will Return Our Structs)

For (int i = 0; i <50; i )

{

// Fill Up Our Structs

Float Theta = (FLOAT) (2 * math.pi * i) / 49;

VERTS [2 * i] .Position = new vector3 ((float) Math.sin (Theta), -1, (float) Math.cos (Theta));

VERTS [2 * i] .NORMAL = New Vector3 (FLOAT) Math.sin (Theta), 0, (FLOAT) Math.cos (Theta));

VERTS [2 * I] .TU = ((float) i) / (50-1);

VERTS [2 * I] .tv =

1.0F

;

VERTS [2 * i 1] .position = new vector3 ((float) Math.sin (Theta), 1, (float) Math.cos (Theta));

VERTS [2 * i 1] .NORMAL = New Vector3 (FLOAT) Math.sin (Theta), 0, (FLOAT) Math.cos (Theta));

VERTS [2 * i 1] .tu = ((float) i) / (50-1);

VERTS [2 * i 1] .tv =

0.0F

;

}

// unlock (and copy) The data

vb.unlock ();

}

Private void setupmatrices ()

{

// for Our World Matrix, We Well Just Rotate The Object About The Y-AXIS.

Device.Transform.World = Matrix.RotationAxis (New Vector3 ((Float) Math.cos (Environment.TickCount /

250.0f

), 1, (float) math.sin (Environment.Tickcount /

250.0f

)), Environment.Tickcount /

1000.0F

);

// SET UP OUR View Matrix. A View Matrix Can Be Defined Given An Eye Point, // A Point To Lookat, And A Direction For Which Way IS Up. Here, We set the

// Eye Five Units Back Along The Z-Axis and Up Three Units, Look At The

// ORIGIN, AND Define "UP" to be in the y-direction.

Device.Transform.View = Matrix.lookatlh (New Vector3

0.0F

,

3.0F

,

-5.0F

), new vector3 (

0.0F

,

0.0F

,

0.0F

), new vector3 (

0.0F

,

1.0F

,

0.0F

));

// for the Projection Matrix, We set up a persftive transform (Which

// Transforms Geometry from 3D View Space To 2D ViewPort Space, with

// a atpective divide making Objects smaller in the distance). To build

// a Perpsective Transform, We need the Field of View (1/4 pi is common),

// The Aspect Ratio, And The Near And Far Clipping Planes (Which Define At

// What Distances Geometry Should Be No longer be rendered.

Device.Transform.Projection = Matrix.PerspectiveFovlh (FLOAT) Math.pi /

4.0F

,

1.0F

,

1.0F

,

100.0F

);

}

Private void render ()

{

IF (PAUSE)

Return;

// Clear the Backbuffer to a blue color

Device.clear (Clearflags.target | Clearflags.zbuffer, System.drawing.color.blue,

1.0F

, 0);

// Begin the Scene

DEVICE.BEGINSCENE ();

// setup the World, View, and Projection Maatrices

Setupmaatrice ();

// setup our texture. Using Textures Introduces The Texture Stage State,

// Which Govern How Textures Get Blended Together (in the case of multiple

// textures) And Lighting Information. in this case, we are modulating

// (Blending) Our texture with the diffuse color of the vertices.

Device.Settexture (0, Texture);

Device.texturestate [0] .COLOROPERATION = TEXTUREOPERATION.MODULATE;

Device.texturestate [0] .COLORARGUMENT1 = Textureargument.textureColor; device.texturestate [0] .COLORARGUMENT2 = Textureargument.diffuse;

Device.texturestate [0] .alphaopert = TextureOperation.disable;

Device.setStreamSource (0, VertexBuffer, 0);

Device.VertexFormat = CustomvertEx.positionNormalTexTured.Format;

Device.drawPrimitives (PrimitiType.trianglestrip, 0, (4 * 25) -2);

// end the scene

Device.endscene ();

// Update the screen

Device.Present ();

}

Protected Override Void Onpaint (System.Windows.Forms.Painteventargs E)

{

THIS.Render (); // render on painting

}

Protected Override Void OnKeyPress (System.Windows.Forms.KeyPressEventArgs E)

{

IF ((int) e.keychar == (int) system.windows.forms.keys.escape)

this.dispose (); // esc Was Pressed

}

Protected Override Void OnResize (System.EventArgs E)

{

Pause = ((this.windowState == formwindowstate.minimized) ||! this.visible);

}

///

/// The main entry point for the application.

///

Static void

Main

()

{

Using (Textures FRM = New Textures ())

{

IF (! frm.initializegraphics ()) // Initialize Direct3D

{

Messagebox.show ("Could Not Initialize Direct3d. This Tutorial Will EXIT.");

Return;

}

Frm.show ();

// While The Form Is Still Valid, Render and Process Messages

While (frm.created)

{

frm.render ();

Application.doevents ();

}

}

}

}

}

There is also a simple way to handle textures, in fact, it is similar, it seems simple:

TEX

= New Texture (DEVICE, New Bitmap (this.gettype (), "puck.bmp"), usage.dynamic, pool.default;

Then use a sentence when drawing

Device.Settexture (0,

TEX

);

You can set the texture to the object, but if you want to perform a slightly complex texture operation, this method is not used.

There are still many things about texture, such as texture, texture, texture filtration, anti-aliasing, alpha mix, and multiple textures, etc., here is just nine bull, but these will slowly introduce it later. By SSSA2000

转载请注明原文地址:https://www.9cbs.com/read-32115.html

New Post(0)