14 / 14 / 8
Регистрация: 31.05.2012
Сообщений: 210
Записей в блоге: 2
1

DirectX: нарисовать несколько объектов

31.05.2012, 22:20. Показов 5935. Ответов 11
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Как мне тут несколько объектов нарисовать кроме чайника? подскажите куда компать
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        static void Main()
        {
            Form1 form = new Form1();
            form.Text = "test";
            form.Width = 400;
            form.Height = 300;
            form.InitD3D();
            form.Show();
            while (form.Created)
            {
                form.Render();
                Application.DoEvents();
            }
        }
 
        Device device;
        Mesh teapot;
 
        public void InitD3D()
        {
            PresentParameters parameters = new PresentParameters();
            parameters.Windowed = true;
            parameters.SwapEffect = SwapEffect.Discard;
 
            device = new Device(0, DeviceType.Hardware, this,
              CreateFlags.SoftwareVertexProcessing, parameters);
            teapot = Mesh.Teapot(device);
        }
 
        public void Render()
        {
            device.Clear(ClearFlags.Target,
              System.Drawing.Color.Blue, 1.0f, 0);
            device.BeginScene();
            try
            {
                device.RenderState.Lighting = true;
                device.Lights[0].Type = LightType.Directional;
                device.Lights[0].Direction = new Vector3(7, -2, 1);
                device.Lights[0].Diffuse = System.Drawing.Color.Yellow;
                device.Lights[0].Enabled = true;
 
                Material material = new Material();
                material.Ambient = System.Drawing.Color.White;
                material.Diffuse = System.Drawing.Color.White;
                material.Specular = System.Drawing.Color.White;
                device.Material = material;
 
                Matrix matrix = new Matrix();
                matrix.Scale(0.7f, 0.7f, 0.7f);
                matrix *= Matrix.RotationY(
                  System.Environment.TickCount / 300.0f);
                float move = (float)Math.Sin(
                  System.Environment.TickCount / 2000.0f) * 4 + 6;
                matrix.M43 = move;
                Text = move.ToString("##.##");
                device.RenderState.Clipping = false;
                device.Transform.World = matrix;
                device.Transform.Projection = Matrix.PerspectiveFovLH(
                  (float)Math.PI / 10, 1.0f, 0.1f, 20.0f);
                device.RenderState.CullMode = Cull.Clockwise;
                teapot.DrawSubset(0);
            }
            finally
            {
                device.EndScene();
            }
            device.Present();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
 
        }
    } 
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
31.05.2012, 22:20
Ответы с готовыми решениями:

OpenGL и DirectX: нарисовать эллипсойд и проекцию его на плоскость
Мне надо нарисовать эллипсойд( трехмерныймерный эллипс) и проекцию его на плоскость. С помощью...

Вращение объектов вокруг своей оси в DirectX
Всех приветствую. Собственно проблема заключается вот в чем. Нужно провернуть объект,...

Нарисовать треугольник, линию с определенным цветом Directx 8.1
Появилась надобность нарисовать линию или треугольник. В интернете все перерыл, не могу найти...

Как с помощью DirectX нарисовать текст на окне
Как с помощью DirectX нарисовать текст на окне. т.е как создать фонт D3DXCreateFontIndirectA а...

11
Эксперт С++
3571 / 2826 / 450
Регистрация: 03.05.2011
Сообщений: 5,193
Записей в блоге: 22
01.06.2012, 01:23 2
например так (результат с прикрепленных)
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
 
namespace example
{
    public partial class Form1 : Form
    {
        Device device;
        Mesh mesh1, mesh2, mesh3, mesh4, mesh5, mesh6;
 
        public float angle { get; set; }
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
 
            var presentParameters = new PresentParameters()
            {
                Windowed = true,
                SwapEffect = SwapEffect.Discard,
                AutoDepthStencilFormat = DepthFormat.D16,
                EnableAutoDepthStencil = true
            };
 
            device = new Device(0, DeviceType.Hardware, Handle, 
                CreateFlags.HardwareVertexProcessing, presentParameters);
 
            mesh1 = Mesh.Box(device, 2.0f, 2.0f, 2.0f); // куб
            mesh2 = Mesh.Cylinder(device, 2.0f, 2.0f, 2.0f, 36, 36); // цилиндр
            mesh3 = Mesh.Polygon(device, 2.0f, 8); // полигон, 8 - число сторон полигона
            mesh4 = Mesh.Sphere(device, 2.0f, 36, 36); // сфера
            mesh5 = Mesh.Torus(device, 0.5f, 2.0f, 36, 80); // тор ("бублик")
            mesh6 = Mesh.Teapot(device); // заварочный чайник
        }
 
        private void SetupCamera()
        {
            device.Transform.Projection = Matrix.PerspectiveFovLH(
                (float)Math.PI / 4, this.Width / this.Height, 1.0f, 100.0f);
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0, 0, 20.0f), new Vector3(), new Vector3(0, 1, 0));
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle / (float)Math.PI);
            angle += 0.03f;
            device.RenderState.Ambient = Color.DarkBlue;
            device.Lights[0].Type = LightType.Directional;
            device.Lights[0].Diffuse = Color.DarkBlue;
            device.Lights[0].Direction = new Vector3(0, -1, -1);
            device.Lights[0].Enabled = true;
            Material boxMaterial = new Material();
            boxMaterial.Ambient = Color.White;
            boxMaterial.Diffuse = Color.White;
            device.Material = boxMaterial;
        }
 
        protected override void OnPaint(PaintEventArgs e)
        {
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            SetupCamera();
            device.BeginScene();
            device.RenderState.CullMode = Cull.None;
            mesh1.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI / 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(5.0f, 0.0f, 0.0f);
            mesh2.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 4.0f, angle /
                (float)Math.PI / 2.0f) * Matrix.Translation(-5.0f, 0.0f, 0.0f);
            mesh3.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI / 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(5.0f, 5.0f, 0.0f);
            mesh4.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(-5.0f, 5.0f, 0.0f);
            mesh5.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI / 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(-5.0f, -5.0f, 0.0f);
            mesh6.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(5.0f, -5.0f, 0.0f);
            mesh1.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI / 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(0.0f, 5.0f, 0.0f);
            mesh3.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(0.0f, -5.0f, 0.0f);
            mesh5.DrawSubset(0);
            device.EndScene();
            device.Present();
            Invalidate();
        }
    }
}
Миниатюры
DirectX: нарисовать несколько объектов  
1
14 / 14 / 8
Регистрация: 31.05.2012
Сообщений: 210
Записей в блоге: 2
01.06.2012, 08:38  [ТС] 3
Спасибо.. только там пару ошибок было.. не компилировал гад.. вот видоизменил( работает )

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Mesh mesh1, mesh2, mesh3, mesh4, mesh5, mesh6;
        public float angle { get; set; }
        static void Main()
        {
            Form1 form = new Form1();
            form.Text = "test";
            form.Width = 400;
            form.Height = 300;
            form.InitD3D();
            form.Show();
            while (form.Created)
            {
                form.Render();
                Application.DoEvents();
            }
        }
 
        Device device;
        Mesh teapot;
 
        public void InitD3D()
        {
            PresentParameters parameters = new PresentParameters();
            parameters.Windowed = true;
            parameters.SwapEffect = SwapEffect.Discard;
 
            device = new Device(0, DeviceType.Hardware, this,
              CreateFlags.SoftwareVertexProcessing, parameters);
            mesh1 = Mesh.Box(device, 2.0f, 2.0f, 2.0f); // куб
            mesh2 = Mesh.Cylinder(device, 2.0f, 2.0f, 2.0f, 36, 36); // цилиндр
            mesh3 = Mesh.Polygon(device, 2.0f, 8); // полигон, 8 - число сторон полигона
            mesh4 = Mesh.Sphere(device, 2.0f, 36, 36); // сфера
            mesh5 = Mesh.Torus(device, 0.5f, 2.0f, 36, 80); // тор ("бублик")
            mesh6 = Mesh.Teapot(device); // заварочный чайник
            teapot = Mesh.Teapot(device);
        }
 
        public void Render()
        {
            device.Transform.Projection = Matrix.PerspectiveFovLH(
               (float)Math.PI / 4, this.Width / this.Height, 1.0f, 100.0f);
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0, 0, 20.0f), new Vector3(), new Vector3(0, 1, 0));
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle / (float)Math.PI);
            angle += 0.03f;
            device.RenderState.Ambient = Color.DarkBlue;
            device.Lights[0].Type = LightType.Directional;
            device.Lights[0].Diffuse = Color.DarkBlue;
            device.Lights[0].Direction = new Vector3(0, -1, -1);
            device.Lights[0].Enabled = true;
            Material boxMaterial = new Material();
            boxMaterial.Ambient = Color.White;
            boxMaterial.Diffuse = Color.White;
            device.Material = boxMaterial;
            device.BeginScene();
            device.RenderState.CullMode = Cull.None;
            mesh1.DrawSubset(0);
 
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI / 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(5.0f, 0.0f, 0.0f);
            mesh2.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 4.0f, angle /
                (float)Math.PI / 2.0f) * Matrix.Translation(-5.0f, 0.0f, 0.0f);
            mesh3.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI / 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(5.0f, 5.0f, 0.0f);
            mesh4.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(-5.0f, 5.0f, 0.0f);
            mesh5.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI / 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(-5.0f, -5.0f, 0.0f);
            mesh6.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(5.0f, -5.0f, 0.0f);
            mesh1.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI / 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(0.0f, 5.0f, 0.0f);
            mesh3.DrawSubset(0);
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle /
                (float)Math.PI * 4.0f) * Matrix.Translation(0.0f, -5.0f, 0.0f);
            mesh5.DrawSubset(0);
            device.EndScene();
            device.Present();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            
        }
    } 
}
Добавлено через 2 минуты
вот только объекты криво получаются т.е хз как объяснить хвосты получаются у них при вращении. и тупо хрень получается после второго оборота...
я убрал эту строку
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
т.к при компилировании(компилирует) пишит ошибка в приложении...

Добавлено через 1 минуту
а все.. вот так сделал:
device.Clear(ClearFlags.Target, System.Drawing.Color.Black, 1.0f, 0);
Добавлено через 6 минут
А как мне свой объект нарисовать ? кроме доступных из Mesh.Х
в Си знаю что так:
C++
1
2
3
4
5
6
D3DMATRIX transform = { 
        0.0f,      0.0f,        0.0f,        0.0f,
        0.0f,       0.0f,       0.0f,        0.0f,
        0.0f,       0.0f,        0.0f,       0.0f,
        0.0f,       0.0f,        1.0f,        1.0f
      };
а в C# хз как))
0
Эксперт С++
3571 / 2826 / 450
Регистрация: 03.05.2011
Сообщений: 5,193
Записей в блоге: 22
01.06.2012, 11:28 4
1. никакой ошибки в моём коде нет, если компилировать весь мой код с точностью до запятой.
2. ZBuffer у вас не работает, потому что нужно указать параметр
C#
1
2
AutoDepthStencilFormat = DepthFormat.D16,
EnableAutoDepthStencil = true
и стиль
C#
1
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
3. зачем вы определяете 2 раз один и тот же объект - чайник?
4. проще всего будет нарисовать объект в редакторе (например в Blender или DeleD 3D) и экспортировать его в x-файл (данные редакторы позволяют это делать, на youtube есть видео как и что). И дальше уже подключать х-файл (1 скриншот)
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
 
namespace example
{
    public partial class Form1 : Form
    {
        Device device;
        Mesh mesh;
        private Material[] meshMaterials;
        private Texture[] meshTextures;
 
        public float angle { get; set; }
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
 
            var presentParameters = new PresentParameters()
            {
                Windowed = true,
                SwapEffect = SwapEffect.Discard,
                AutoDepthStencilFormat = DepthFormat.D16,
                EnableAutoDepthStencil = true
            };
 
            device = new Device(0, DeviceType.Hardware, Handle, 
                CreateFlags.HardwareVertexProcessing, presentParameters);
 
            LoadMesh(@"..\..\tiny.x");
        }
 
        private void LoadMesh(string file)
        {
            ExtendedMaterial[] mtrl;
            mesh = Mesh.FromFile(file, MeshFlags.Managed, device, out mtrl);
            if ((mtrl != null) && (mtrl.Length > 0))
            {
                meshMaterials = new Material[mtrl.Length];
                meshTextures = new Texture[mtrl.Length];
                for (int i = 0; i < mtrl.Length; i++)
                {
                    meshMaterials[i] = mtrl[i].Material3D;
                    if ((mtrl[i].TextureFilename != null) && 
                        (mtrl[i].TextureFilename != string.Empty))
                    {
                        meshTextures[i] = TextureLoader.FromFile(
                            device, @"..\..\" + mtrl[i].TextureFilename);
                    }
                }
            }
        }
 
        private void SetupCamera()
        {
            device.Transform.Projection = Matrix.PerspectiveFovLH(
                (float)Math.PI / 4, this.Width / this.Height, 1.0f, 10000.0f);
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0, 0, 580.0f), new Vector3(), new Vector3(0, 1, 0));
            device.Lights[0].Type = LightType.Directional;
            device.Lights[0].Diffuse = Color.White;
            device.Lights[0].Direction = new Vector3(0, -1, -1);
            device.Lights[0].Enabled = true;
 
        }
 
        protected override void OnPaint(PaintEventArgs e)
        {
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.CornflowerBlue, 1.0f, 0);
            SetupCamera();
            device.BeginScene();
            DrawMesh(angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle / 
                (float)Math.PI / 4.0f, 0.0f, 0.0f, 0.0f);
            device.EndScene();
            device.Present();
            Invalidate();
        }
 
        private void DrawMesh(float yaw, float pitch, float roll, float x, float y, float z)
        {
            angle += 0.01f;
 
            device.Transform.World = Matrix.RotationYawPitchRoll(
                yaw, pitch, roll) * Matrix.Translation(x, y, z);
            for (int i = 0; i < meshMaterials.Length; i++)
            {
                device.Material = meshMaterials[i];
                device.SetTexture(0, meshTextures[i]);
                mesh.DrawSubset(i);
            }
        }
    }
}
т.е. здесь каркасом служит х-файл и на этот каркас наложена текстура.

либо можете создать массив из точек и не использовать х-файл (2 скриншот)
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
 
namespace example
{
    public partial class Form1 : Form
    {
        Device device;
        Texture texture;
 
        public float angle { get; set; }
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
 
            var presentParameters = new PresentParameters()
            {
                Windowed = true,
                SwapEffect = SwapEffect.Discard
            };
 
            device = new Device(0, DeviceType.Hardware, Handle, 
                CreateFlags.SoftwareVertexProcessing, presentParameters);
        }
 
        private void SetupCamera()
        {
            device.Transform.Projection = Matrix.PerspectiveFovLH(
                (float)Math.PI / 4, Width / Height, 1.0f, 100.0f);
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0, 0, 8.0f), new Vector3(), new Vector3(0, 1, 0));
            device.RenderState.Lighting = false;
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle / (float)Math.PI);
            angle += 0.1f;
        }
 
        protected override void OnPaint(PaintEventArgs e)
        {
            device.Clear(ClearFlags.Target, Color.CornflowerBlue, 1.0f, 0);
            SetupCamera();
            CustomVertex.PositionTextured[] verts = new CustomVertex.PositionTextured[36];
            // Front face
            verts[0] = new CustomVertex.PositionTextured(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f);
            verts[1] = new CustomVertex.PositionTextured(-1.0f, -1.0f, 1.0f, 0.0f, 1.0f);
            verts[2] = new CustomVertex.PositionTextured(1.0f, 1.0f, 1.0f, 1.0f, 0.0f);
            verts[3] = new CustomVertex.PositionTextured(-1.0f, -1.0f, 1.0f, 0.0f, 1.0f);
            verts[4] = new CustomVertex.PositionTextured(1.0f, -1.0f, 1.0f, 1.0f, 1.0f);
            verts[5] = new CustomVertex.PositionTextured(1.0f, 1.0f, 1.0f, 1.0f, 0.0f);
            // Back face (remember this is facing *away* from the camera, so vertices should be clockwise order)
            verts[6] = new CustomVertex.PositionTextured(-1.0f, 1.0f, -1.0f, 0.0f, 0.0f);
            verts[7] = new CustomVertex.PositionTextured(1.0f, 1.0f, -1.0f, 1.0f, 0.0f);
            verts[8] = new CustomVertex.PositionTextured(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f);
            verts[9] = new CustomVertex.PositionTextured(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f);
            verts[10] = new CustomVertex.PositionTextured(1.0f, 1.0f, -1.0f, 1.0f, 0.0f);
            verts[11] = new CustomVertex.PositionTextured(1.0f, -1.0f, -1.0f, 1.0f, 1.0f);
            // Top face
            verts[12] = new CustomVertex.PositionTextured(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f);
            verts[13] = new CustomVertex.PositionTextured(1.0f, 1.0f, -1.0f, 1.0f, 1.0f);
            verts[14] = new CustomVertex.PositionTextured(-1.0f, 1.0f, -1.0f, 0.0f, 1.0f);
            verts[15] = new CustomVertex.PositionTextured(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f);
            verts[16] = new CustomVertex.PositionTextured(1.0f, 1.0f, 1.0f, 1.0f, 0.0f);
            verts[17] = new CustomVertex.PositionTextured(1.0f, 1.0f, -1.0f, 1.0f, 1.0f);
            // Bottom face (remember this is facing *away* from the camera, so vertices should be clockwise order)
            verts[18] = new CustomVertex.PositionTextured(-1.0f, -1.0f, 1.0f, 0.0f, 0.0f);
            verts[19] = new CustomVertex.PositionTextured(-1.0f, -1.0f, -1.0f, 0.0f, 1.0f);
            verts[20] = new CustomVertex.PositionTextured(1.0f, -1.0f, -1.0f, 1.0f, 1.0f);
            verts[21] = new CustomVertex.PositionTextured(-1.0f, -1.0f, 1.0f, 0.0f, 0.0f);
            verts[22] = new CustomVertex.PositionTextured(1.0f, -1.0f, -1.0f, 1.0f, 1.0f);
            verts[23] = new CustomVertex.PositionTextured(1.0f, -1.0f, 1.0f, 1.0f, 0.0f);
            // Left face
            verts[24] = new CustomVertex.PositionTextured(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f);
            verts[25] = new CustomVertex.PositionTextured(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f);
            verts[26] = new CustomVertex.PositionTextured(-1.0f, -1.0f, 1.0f, 1.0f, 0.0f);
            verts[27] = new CustomVertex.PositionTextured(-1.0f, 1.0f, -1.0f, 0.0f, 1.0f);
            verts[28] = new CustomVertex.PositionTextured(-1.0f, -1.0f, -1.0f, 1.0f, 1.0f);
            verts[29] = new CustomVertex.PositionTextured(-1.0f, 1.0f, 1.0f, 0.0f, 0.0f);
            // Right face (remember this is facing *away* from the camera, so vertices should be clockwise order)
            verts[30] = new CustomVertex.PositionTextured(1.0f, 1.0f, 1.0f, 0.0f, 0.0f);
            verts[31] = new CustomVertex.PositionTextured(1.0f, -1.0f, 1.0f, 1.0f, 0.0f);
            verts[32] = new CustomVertex.PositionTextured(1.0f, -1.0f, -1.0f, 1.0f, 1.0f);
            verts[33] = new CustomVertex.PositionTextured(1.0f, 1.0f, -1.0f, 0.0f, 1.0f);
            verts[34] = new CustomVertex.PositionTextured(1.0f, 1.0f, 1.0f, 0.0f, 0.0f);
            verts[35] = new CustomVertex.PositionTextured(1.0f, -1.0f, -1.0f, 1.0f, 1.0f);
 
            texture = new Texture(device, new Bitmap("puck.bmp"), Usage.Dynamic, Pool.Default);
            device.SetTexture(0, texture);
            device.BeginScene();
            device.VertexFormat = CustomVertex.PositionTextured.Format;
            device.DrawUserPrimitives(PrimitiveType.TriangleList, 12, verts);
            device.EndScene();
            device.Present();
            Invalidate();
        }
    }
}
Миниатюры
DirectX: нарисовать несколько объектов   DirectX: нарисовать несколько объектов  
2
14 / 14 / 8
Регистрация: 31.05.2012
Сообщений: 210
Записей в блоге: 2
01.06.2012, 15:15  [ТС] 5
допустим куб сделал, как мне получить координаты вершин. длину граней?

Добавлено через 49 минут
вот длину грани узнать для Mesh.Box
каким образом можно?
0
Эксперт С++
3571 / 2826 / 450
Регистрация: 03.05.2011
Сообщений: 5,193
Записей в блоге: 22
01.06.2012, 16:13 6
Цитата Сообщение от myxasa Посмотреть сообщение
как мне получить координаты вершин?
массив
C#
1
CustomVertex.PositionTextured[] verts = new CustomVertex.PositionTextured[36];
и есть координаты. Есть же экранные координаты и мировые.

Цитата Сообщение от myxasa Посмотреть сообщение
вот длину грани узнать для Mesh.Box
каким образом можно?
обычно оперируют не постоянной длинной (как в графических редакторах), а матрицей вида. Измените значения вектора например на 80
C#
1
2
device.Transform.View = Matrix.LookAtLH(
    new Vector3(0, 0, 80.0f), new Vector3(), new Vector3(0, 1, 0));
0
14 / 14 / 8
Регистрация: 31.05.2012
Сообщений: 210
Записей в блоге: 2
01.06.2012, 16:29  [ТС] 7
Почему куб синий а не цветной?
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    device.Transform.Projection = Matrix.PerspectiveFovLH(
           (float)Math.PI / 4, this.Width / this.Height, 1.0f, 100.0f);
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0, 0, 20.0f), new Vector3(), new Vector3(0, 1, 0));
            device.Transform.World = Matrix.RotationYawPitchRoll(
                angle / (float)Math.PI, angle / (float)Math.PI * 2.0f, angle / (float)Math.PI);
            angle += 0.03f;
            device.RenderState.Ambient = Color.DarkBlue;
            device.Lights[0].Type = LightType.Directional;
            device.Lights[0].Diffuse = Color.DarkBlue;
            device.Lights[0].Direction = new Vector3(0, -1, -1);
            device.Lights[0].Enabled = true;
            Material boxMaterial = new Material();
            boxMaterial.Ambient = Color.White;
            boxMaterial.Diffuse = Color.White;
            device.Material = boxMaterial;
            device.Clear(ClearFlags.Target, System.Drawing.Color.Black, 1.0f, 0);
            CustomVertex.PositionColored[] verts = new CustomVertex.PositionColored[36];
            // Передняя грань
            verts[0] = new CustomVertex.PositionColored(-1.0f, 1.0f, 1.0f, Color.Red.ToArgb());
            verts[1] = new CustomVertex.PositionColored(-1.0f, -1.0f, 1.0f, Color.Red.ToArgb());
            verts[2] = new CustomVertex.PositionColored(1.0f, 1.0f, 1.0f, Color.Red.ToArgb());
            verts[3] = new CustomVertex.PositionColored(-1.0f, -1.0f, 1.0f, Color.Red.ToArgb());
            verts[4] = new CustomVertex.PositionColored(1.0f, -1.0f, 1.0f, Color.Red.ToArgb());
            verts[5] = new CustomVertex.PositionColored(1.0f, 1.0f, 1.0f, Color.Red.ToArgb());
 
            // Задняя грань (помните, что эта грань направлена от камеры
            // и вершины должны быть упорядочены по часовой стрелке)
            verts[6] = new CustomVertex.PositionColored(-1.0f, 1.0f, -1.0f, Color.Blue.ToArgb());
            verts[7] = new CustomVertex.PositionColored(1.0f, 1.0f, -1.0f, Color.Blue.ToArgb());
            verts[8] = new CustomVertex.PositionColored(-1.0f, -1.0f, -1.0f, Color.Blue.ToArgb());
            verts[9] = new CustomVertex.PositionColored(-1.0f, -1.0f, -1.0f, Color.Blue.ToArgb());
            verts[10] = new CustomVertex.PositionColored(1.0f, 1.0f, -1.0f, Color.Blue.ToArgb());
            verts[11] = new CustomVertex.PositionColored(1.0f, -1.0f, -1.0f, Color.Blue.ToArgb());
 
            // Верхняя грань
            verts[12] = new CustomVertex.PositionColored(-1.0f, 1.0f, 1.0f, Color.Yellow.ToArgb());
            verts[13] = new CustomVertex.PositionColored(1.0f, 1.0f, -1.0f, Color.Yellow.ToArgb());
            verts[14] = new CustomVertex.PositionColored(-1.0f, 1.0f, -1.0f, Color.Yellow.ToArgb());
            verts[15] = new CustomVertex.PositionColored(-1.0f, 1.0f, 1.0f, Color.Yellow.ToArgb());
            verts[16] = new CustomVertex.PositionColored(1.0f, 1.0f, 1.0f, Color.Yellow.ToArgb());
            verts[17] = new CustomVertex.PositionColored(1.0f, 1.0f, -1.0f, Color.Yellow.ToArgb());
 
            // Нижняя грань (помните, что эта грань направлена от камеры
            // и вершины должны быть упорядочены по часовой стрелке)
            verts[18] = new CustomVertex.PositionColored(-1.0f, -1.0f, 1.0f, Color.Black.ToArgb());
            verts[19] = new CustomVertex.PositionColored(-1.0f, -1.0f, -1.0f, Color.Black.ToArgb());
            verts[20] = new CustomVertex.PositionColored(1.0f, -1.0f, -1.0f, Color.Black.ToArgb());
            verts[21] = new CustomVertex.PositionColored(-1.0f, -1.0f, 1.0f, Color.Black.ToArgb());
            verts[22] = new CustomVertex.PositionColored(1.0f, -1.0f, -1.0f, Color.Black.ToArgb());
            verts[23] = new CustomVertex.PositionColored(1.0f, -1.0f, 1.0f, Color.Black.ToArgb());
 
            // Левая грань
            verts[24] = new CustomVertex.PositionColored(-1.0f, 1.0f, 1.0f, Color.Gray.ToArgb());
            verts[25] = new CustomVertex.PositionColored(-1.0f, -1.0f, -1.0f, Color.Gray.ToArgb());
            verts[26] = new CustomVertex.PositionColored(-1.0f, -1.0f, 1.0f, Color.Gray.ToArgb());
            verts[27] = new CustomVertex.PositionColored(-1.0f, 1.0f, -1.0f, Color.Gray.ToArgb());
            verts[28] = new CustomVertex.PositionColored(-1.0f, -1.0f, -1.0f, Color.Gray.ToArgb());
            verts[29] = new CustomVertex.PositionColored(-1.0f, 1.0f, 1.0f, Color.Gray.ToArgb());
 
            // Правая грань (помните, что эта грань направлена от камеры
            // и вершины должны быть упорядочены по часовой стрелке)
            verts[30] = new CustomVertex.PositionColored(1.0f, 1.0f, 1.0f, Color.Green.ToArgb());
            verts[31] = new CustomVertex.PositionColored(1.0f, -1.0f, 1.0f, Color.Green.ToArgb());
            verts[32] = new CustomVertex.PositionColored(1.0f, -1.0f, -1.0f, Color.Green.ToArgb());
            verts[33] = new CustomVertex.PositionColored(1.0f, 1.0f, -1.0f, Color.Green.ToArgb());
            verts[34] = new CustomVertex.PositionColored(1.0f, 1.0f, 1.0f, Color.Green.ToArgb());
            verts[35] = new CustomVertex.PositionColored(1.0f, -1.0f, -1.0f, Color.Green.ToArgb());
 
            device.BeginScene();
            device.VertexFormat = CustomVertex.PositionTextured.Format;
            device.DrawUserPrimitives(PrimitiveType.TriangleList, 12, verts);
            device.RenderState.CullMode = Cull.None;
            device.EndScene();
            device.Present();
0
Эксперт С++
3571 / 2826 / 450
Регистрация: 03.05.2011
Сообщений: 5,193
Записей в блоге: 22
01.06.2012, 18:22 8
Цитата Сообщение от myxasa Посмотреть сообщение
Почему куб синий а не цветной?
C#
1
device.RenderState.Ambient = Color.DarkBlue;
просто в моём пример наложена текстура
C#
1
texture = new Texture(device, new Bitmap("puck.bmp"), Usage.Dynamic, Pool.Default);
0
14 / 14 / 8
Регистрация: 31.05.2012
Сообщений: 210
Записей в блоге: 2
01.06.2012, 23:26  [ТС] 9
Как мне массив сделать? не получается... (

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        Texture2D[] test;
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            //загружаем текстуру с именем SomeTexture в объект myCoolPlayerSprite
            w_height = graphics.GraphicsDevice.Viewport.Height;
            w_width = graphics.GraphicsDevice.Viewport.Width;
            wall1 = Content.Load<Texture2D>("textures/Floor1");
            sand1 = Content.Load<Texture2D>("textures/sand1");
            player = Content.Load<Texture2D>("textures/player");
            for (int i = 0; i <= 64; i++)
            {
            test[i] = Content.Load<Texture2D>("textures/Floor1");
            }
        }
пишит
Ссылка на объект не указывает на экземпляр объекта.
для
test[i] = Content.Load<Texture2D>("textures/Floor1");
0
311 / 249 / 44
Регистрация: 06.12.2010
Сообщений: 527
02.06.2012, 12:42 10
Используйте списки, с ними проще.
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        List<Texture2D> test = new List<Texture2D>();
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            //загружаем текстуру с именем SomeTexture в объект myCoolPlayerSprite
            w_height = graphics.GraphicsDevice.Viewport.Height;
            w_width = graphics.GraphicsDevice.Viewport.Width;
            wall1 = Content.Load<Texture2D>("textures/Floor1");
            sand1 = Content.Load<Texture2D>("textures/sand1");
            player = Content.Load<Texture2D>("textures/player");
            for (int i = 0; i <= 64; i++)
            {
              test.Add(Content.Load<Texture2D>("textures/Floor1"));
            }
        }
А если все же нужен массив, то Вы объявили его, но не присвоили значение и размерность.
Вот так нужно:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        Texture2D[] test;
        protected override void LoadContent()
        {
            test = new Texture2D[64];//Эта строчка
            spriteBatch = new SpriteBatch(GraphicsDevice);
            //загружаем текстуру с именем SomeTexture в объект myCoolPlayerSprite
            w_height = graphics.GraphicsDevice.Viewport.Height;
            w_width = graphics.GraphicsDevice.Viewport.Width;
            wall1 = Content.Load<Texture2D>("textures/Floor1");
            sand1 = Content.Load<Texture2D>("textures/sand1");
            player = Content.Load<Texture2D>("textures/player");
            for (int i = 0; i <= 64; i++)
            {
            test[i] = Content.Load<Texture2D>("textures/Floor1");
            }
        }
0
14 / 14 / 8
Регистрация: 31.05.2012
Сообщений: 210
Записей в блоге: 2
03.06.2012, 15:04  [ТС] 11
C#
1
2
3
4
5
6
7
8
Texture2D[] green_cubes = new Texture2D[128]; 
 protected override void LoadContent() 
 { 
 for (int i = 0; i <= 127; i++) 
 { 
 green_cubes = Content.Load<texture2d>("textures/green"); 
} 
}
вот тут для одного значения.. я хочу чтобы потом значения параметров вытаскивать типа:

int health = green_cubes[5]["health"];
вот так ...как реализовать?
0
311 / 249 / 44
Регистрация: 06.12.2010
Сообщений: 527
04.06.2012, 14:45 12
Создайте класс и работайте с ним. Примерно так:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class GreenCube
{
   public int health;
   public Texture2D Texture;//вообще-то так делать нельзя. Класс не должен предоставлять прямой  доступ к своим объектам, но для наглядности сойдет. 
}
 
//....
 
GreenCube[] green_cubes = new GreenCube[128]; 
 protected override void LoadContent() 
 { 
 for (int i = 0; i <= 127; i++) 
 { 
 green_cubes.Texture = Content.Load<Texture2D>("textures/green"); 
 green_cubes.health = i;
} 
}
 
int health = green_cubes[5].health;
Как-то так
1
04.06.2012, 14:45
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
04.06.2012, 14:45
Помогаю со студенческими работами здесь

Нарисовать текст в окне чужой DirectX игры
Собственно сабж. Интересует как быстрее всего можно это сделать. Нужно просто нарисовать текст и...

Нужно несколько советов по DirectX + C++
Всем привет! Пару дней назад начал изучать DirectX + С++. Помогите немного структурировать...

Массивы Функций. DirectX 11. Отобразить несколько моделей
Всем привет, продолжаю пытаться изучать DirectX 11. Возникла задача отобразить более одной...

Несколько объектов
Мне необходимо через скрипт с# скрыть группу объектов. Некоторые из них принадлежат к канвасу...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
12
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru