Форум программистов, компьютерный форум, киберфорум
Unity, Unity3D
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.93/15: Рейтинг темы: голосов - 15, средняя оценка - 4.93
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404

Выдавить меш

03.02.2019, 21:16. Показов 3008. Ответов 9

Студворк — интернет-сервис помощи студентам
Хентай!

С помощью алгоритма ear clipping triangulation я создаю 2d меш. И мне нужно его просто выдавить. Сам не могу разобраться так как не знаю матриц.

В примере Procedural Examples от Unity я нашёл скрипт MeshExtrusion.

Поэкспериментировал и получилось выдавить примитивный куб:
TestExtrude.cs
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
using UnityEngine;
 
public class TestExtrude : MonoBehaviour
{
    [Header("Extrusion")]
    public Vector3 pos = Vector3.forward;
    public Quaternion q = Quaternion.identity;
    public Vector3 s = Vector3.one;
 
    public bool invertFaces = false;
    private Mesh mesh;
    private MeshFilter meshFilter;
    private MeshExtrusion.Edge[] edges;
    private Matrix4x4[] extrusion;
 
    private void Start()
    {
        meshFilter = GetComponent<MeshFilter>();
        mesh = meshFilter.mesh;
        edges = MeshExtrusion.BuildManifoldEdges(mesh);
 
        Matrix4x4 worldToLocal = transform.worldToLocalMatrix;
        extrusion = new Matrix4x4[] { worldToLocal * Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one), worldToLocal * Matrix4x4.TRS(pos, q, s) };
    }
 
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            MeshExtrusion.ExtrudeMesh(mesh, meshFilter.mesh, extrusion, edges, invertFaces);
    }
}
MeshExtrusion.cs
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
using UnityEngine;
using System.Collections;
 
/*
* An algorithm to extrude an arbitrary mesh along a number of sections.
 
The mesh extrusion has 2 steps:
 
1. Extracting an edge representation from an arbitrary mesh
- A general edge extraction algorithm is employed. (Same algorithm as traditionally used for stencil shadows) Once all unique edges are found, all edges that connect to only one triangle are extracted.
 Thus we end up with the outline of the mesh.
 
2. extruding the mesh from the edge representation.
We simply generate a segments joining the edges 
 
 
 
 
*/
 
public class MeshExtrusion
{
    public class Edge
    {
        // The indiex to each vertex
        public int[]  vertexIndex = new int[2];
        // The index into the face.
        // (faceindex[0] == faceindex[1] means the edge connects to only one triangle)
        public int[]  faceIndex = new int[2];
    }
    
    public static void ExtrudeMesh (Mesh srcMesh, Mesh extrudedMesh, Matrix4x4[] extrusion, bool invertFaces)
    {
        Edge[] edges = BuildManifoldEdges(srcMesh);
        ExtrudeMesh(srcMesh, extrudedMesh, extrusion, edges, invertFaces);
    }   
    
    public static void ExtrudeMesh (Mesh srcMesh, Mesh extrudedMesh, Matrix4x4[] extrusion, Edge[] edges, bool invertFaces)
    {
        int extrudedVertexCount = edges.Length * 2 * extrusion.Length;
        int triIndicesPerStep = edges.Length * 6;
        int extrudedTriIndexCount = triIndicesPerStep * (extrusion.Length -1);
        
        Vector3[] inputVertices = srcMesh.vertices;
        Vector2[] inputUV = srcMesh.uv;
        int[] inputTriangles = srcMesh.triangles;
 
        Vector3[] vertices = new Vector3[extrudedVertexCount + srcMesh.vertexCount * 2];
        Vector2[] uvs = new Vector2[vertices.Length];
        int[] triangles = new int[extrudedTriIndexCount + inputTriangles.Length * 2];
 
        // Build extruded vertices
        int v = 0;
        for (int i=0;i<extrusion.Length;i++)
        {
            Matrix4x4 matrix = extrusion[i];
            float vcoord = (float)i / (extrusion.Length -1);
            foreach (Edge e in edges)
            {
                vertices[v+0] = matrix.MultiplyPoint(inputVertices[e.vertexIndex[0]]);
                vertices[v+1] = matrix.MultiplyPoint(inputVertices[e.vertexIndex[1]]);
 
                uvs[v+0] = new Vector2 (inputUV[e.vertexIndex[0]].x, vcoord);
                uvs[v+1] = new Vector2 (inputUV[e.vertexIndex[1]].x, vcoord);
                
                v += 2;
            }
        }       
        
        // Build cap vertices
        // * The bottom mesh we scale along it's negative extrusion direction. This way extruding a half sphere results in a capsule.
        for (int c=0;c<2;c++)
        {
            Matrix4x4 matrix = extrusion[c == 0 ? 0 : extrusion.Length-1];
            int firstCapVertex = c == 0 ? extrudedVertexCount : extrudedVertexCount + inputVertices.Length;
            for (int i=0;i<inputVertices.Length;i++)
            {
                vertices[firstCapVertex + i] = matrix.MultiplyPoint(inputVertices[i]);
                uvs[firstCapVertex + i] = inputUV[i];
            }
        }
        
        // Build extruded triangles
        for (int i=0;i<extrusion.Length-1;i++)
        {
            int baseVertexIndex = (edges.Length * 2) * i;
            int nextVertexIndex = (edges.Length * 2) * (i+1);
            for (int e=0;e<edges.Length;e++)
            {
                int triIndex = i * triIndicesPerStep + e * 6;
 
                triangles[triIndex + 0] = baseVertexIndex + e * 2;
                triangles[triIndex + 1] = nextVertexIndex  + e * 2;
                triangles[triIndex + 2] = baseVertexIndex + e * 2 + 1;
                triangles[triIndex + 3] = nextVertexIndex + e * 2;
                triangles[triIndex + 4] = nextVertexIndex + e * 2 + 1;
                triangles[triIndex + 5] = baseVertexIndex  + e * 2 + 1;
            }
        }
        
        // build cap triangles
        int triCount = inputTriangles.Length / 3;
        // Top
        {
            int firstCapVertex = extrudedVertexCount;
            int firstCapTriIndex = extrudedTriIndexCount;
            for (int i=0;i<triCount;i++)
            {
                triangles[i*3 + firstCapTriIndex + 0] = inputTriangles[i * 3 + 1] + firstCapVertex;
                triangles[i*3 + firstCapTriIndex + 1] = inputTriangles[i * 3 + 2] + firstCapVertex;
                triangles[i*3 + firstCapTriIndex + 2] = inputTriangles[i * 3 + 0] + firstCapVertex;
            }
        }
        
        // Bottom
        {
            int firstCapVertex = extrudedVertexCount + inputVertices.Length;
            int firstCapTriIndex = extrudedTriIndexCount + inputTriangles.Length;
            for (int i=0;i<triCount;i++)
            {
                triangles[i*3 + firstCapTriIndex + 0] = inputTriangles[i * 3 + 0] + firstCapVertex;
                triangles[i*3 + firstCapTriIndex + 1] = inputTriangles[i * 3 + 2] + firstCapVertex;
                triangles[i*3 + firstCapTriIndex + 2] = inputTriangles[i * 3 + 1] + firstCapVertex;
            }
        }
        
        if (invertFaces)
        {
            for (int i=0;i<triangles.Length/3;i++)
            {
                int temp = triangles[i*3 + 0];
                triangles[i*3 + 0] = triangles[i*3 + 1];
                triangles[i*3 + 1] = temp;
            }
        }
        
        extrudedMesh.Clear();
        extrudedMesh.name= "extruded";
        extrudedMesh.vertices = vertices;
        extrudedMesh.uv = uvs;
        extrudedMesh.triangles = triangles;
        extrudedMesh.RecalculateNormals();
    }
 
    /// Builds an array of edges that connect to only one triangle.
    /// In other words, the outline of the mesh 
    public static Edge[] BuildManifoldEdges (Mesh mesh)
    {
        // Build a edge list for all unique edges in the mesh
        Edge[] edges = BuildEdges(mesh.vertexCount, mesh.triangles);
        
        // We only want edges that connect to a single triangle
        ArrayList culledEdges = new ArrayList();
        foreach (Edge edge in edges)
        {
            if (edge.faceIndex[0] == edge.faceIndex[1])
            {
                culledEdges.Add(edge);
            }
        }
 
        return culledEdges.ToArray(typeof(Edge)) as Edge[];
    }
 
    /// Builds an array of unique edges
    /// This requires that your mesh has all vertices welded. However on import, Unity has to split
    /// vertices at uv seams and normal seams. Thus for a mesh with seams in your mesh you
    /// will get two edges adjoining one triangle.
    /// Often this is not a problem but you can fix it by welding vertices 
    /// and passing in the triangle array of the welded vertices.
    public static Edge[] BuildEdges(int vertexCount, int[] triangleArray)
    {
        int maxEdgeCount = triangleArray.Length;
        int[] firstEdge = new int[vertexCount + maxEdgeCount];
        int nextEdge = vertexCount;
        int triangleCount = triangleArray.Length / 3;
        
        for (int a = 0; a < vertexCount; a++)
            firstEdge[a] = -1;
            
        // First pass over all triangles. This finds all the edges satisfying the
        // condition that the first vertex index is less than the second vertex index
        // when the direction from the first vertex to the second vertex represents
        // a counterclockwise winding around the triangle to which the edge belongs.
        // For each edge found, the edge index is stored in a linked list of edges
        // belonging to the lower-numbered vertex index i. This allows us to quickly
        // find an edge in the second pass whose higher-numbered vertex index is i.
        Edge[] edgeArray = new Edge[maxEdgeCount];
        
        int edgeCount = 0;
        for (int a = 0; a < triangleCount; a++)
        {
            int i1 = triangleArray[a*3 + 2];
            for (int b = 0; b < 3; b++)
            {
                int i2 = triangleArray[a*3 + b];
                if (i1 < i2)
                {
                    Edge newEdge = new Edge();
                    newEdge.vertexIndex[0] = i1;
                    newEdge.vertexIndex[1] = i2;
                    newEdge.faceIndex[0] = a;
                    newEdge.faceIndex[1] = a;
                    edgeArray[edgeCount] = newEdge;
                    
                    int edgeIndex = firstEdge[i1];
                    if (edgeIndex == -1)
                    {
                        firstEdge[i1] = edgeCount;
                    }
                    else
                    {
                        while (true)
                        {
                            int index = firstEdge[nextEdge + edgeIndex];
                            if (index == -1)
                            {
                                firstEdge[nextEdge + edgeIndex] = edgeCount;
                                break;
                            }
                        
                            edgeIndex = index;
                        }
                    }
            
                    firstEdge[nextEdge + edgeCount] = -1;
                    edgeCount++;
                }
            
                i1 = i2;
            }
        }
        
        // Second pass over all triangles. This finds all the edges satisfying the
        // condition that the first vertex index is greater than the second vertex index
        // when the direction from the first vertex to the second vertex represents
        // a counterclockwise winding around the triangle to which the edge belongs.
        // For each of these edges, the same edge should have already been found in
        // the first pass for a different triangle. Of course we might have edges with only one triangle
        // in that case we just add the edge here
        // So we search the list of edges
        // for the higher-numbered vertex index for the matching edge and fill in the
        // second triangle index. The maximum number of comparisons in this search for
        // any vertex is the number of edges having that vertex as an endpoint.
        
        for (int a = 0; a < triangleCount; a++)
        {
            int i1 = triangleArray[a*3+2];
            for (int b = 0; b < 3; b++)
            {
                int i2 = triangleArray[a*3+b];
                if (i1 > i2)
                {
                    bool foundEdge = false;
                    for (int edgeIndex = firstEdge[i2]; edgeIndex != -1;edgeIndex = firstEdge[nextEdge + edgeIndex])
                    {
                        Edge edge = edgeArray[edgeIndex];
                        if ((edge.vertexIndex[1] == i1) && (edge.faceIndex[0] == edge.faceIndex[1]))
                        {
                            edgeArray[edgeIndex].faceIndex[1] = a;
                            foundEdge = true;
                            break;
                        }
                    }
                    
                    if (!foundEdge)
                    {
                        Edge newEdge = new Edge();
                        newEdge.vertexIndex[0] = i1;
                        newEdge.vertexIndex[1] = i2;
                        newEdge.faceIndex[0] = a;
                        newEdge.faceIndex[1] = a;
                        edgeArray[edgeCount] = newEdge;
                        edgeCount++;
                    }
                }
                
                i1 = i2;
            }
        }
        
        Edge[] compactedEdges = new Edge[edgeCount];
        for (int e=0;e<edgeCount;e++)
            compactedEdges[e] = edgeArray[e];
        
        return compactedEdges;
    }
}
Что мне нужно
Мне нужно выдавить 2d меш в 3d. Как?
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
03.02.2019, 21:16
Ответы с готовыми решениями:

Как программно создать своего рода Меш для UI
допустим есть экран игры, и мне нужно кликнуть в некую область UI (которая может затрагивать несколько элементов). 1) если это...

Растягивается меш directx 9
Рисую шар, но шаром он становится только когда окно квадратное аля 400x400, но если изменить расширение окна на прямоугольное то и меш...

Как растянуть меш в directx 9
У меня есть меш круга, как можно растянуть его в эллипс методами directx 9?

9
490 / 286 / 129
Регистрация: 30.10.2018
Сообщений: 1,309
03.02.2019, 21:29
Цитата Сообщение от NotGoodEnough Посмотреть сообщение
Мне нужно выдавить 2d меш в 3d. Как?
я так понял тебе нужно в рантайме делать, пока так далеко не заходил, но в чем проблема пройтись по всем точкам, и создать по одной на каждую с отклонениям по z?
0
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404
03.02.2019, 21:49  [ТС]
kitsoRik,
Цитата Сообщение от kitsoRik Посмотреть сообщение
я так понял тебе нужно в рантайме делать, пока так далеко не заходил, но в чем проблема пройтись по всем точкам, и создать по одной на каждую с отклонениям по z?
в том, что я с мешами работаю от силы неделю.
0
 Аватар для Cr0c
753 / 600 / 204
Регистрация: 06.08.2015
Сообщений: 2,432
04.02.2019, 00:48
Надо создать вертексы, которые будешь выдавливать, внутри области и сменить им нужный компонент.
0
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404
04.02.2019, 14:09  [ТС]
Цитата Сообщение от Cr0c Посмотреть сообщение
Надо создать вертексы, которые будешь выдавливать, внутри области и сменить им нужный компонент.
какой ещё сменить компонент?

Добавлено через 2 минуты
Как я понял код из MeshExtrusion.cs, там находятся все точки которые присоеденены только к одному треугольнику и потом создаётся копия этих точек(используя Matrix4x4) в нужных местах и заполняется треугольниками.
0
 Аватар для Cr0c
753 / 600 / 204
Регистрация: 06.08.2015
Сообщений: 2,432
04.02.2019, 15:15
NotGoodEnough, вертекс (вершина) имеет три компонента: X, Y, Z
Треугольников, как таковых, нет, есть набор ребер, которые формируют треугольник (каждые три ребра) в одномерном массиве ребер.

Добавлено через 55 секунд
Очередность обхода ребер определяет направление треугольника (его нормали)
0
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404
04.02.2019, 15:15  [ТС]
Cr0c, я это знаю.
0
 Аватар для Cr0c
753 / 600 / 204
Регистрация: 06.08.2015
Сообщений: 2,432
04.02.2019, 15:18
Ребра треугольника формируются из индексов вершин.

Добавлено через 1 минуту
Но для удобства проще рассматривать ребра как набор из трёх вершин треугольника (по часовой - лицо, против - изнанка)

Добавлено через 49 секунд
NotGoodEnough, если ты всё это знаешь, то в чём проблема?
0
 Аватар для NotGoodEnough
34 / 30 / 8
Регистрация: 22.02.2017
Сообщений: 404
04.02.2019, 15:19  [ТС]
Cr0c, в том, что я путаюсь в циклах и не могу представить как сделать заполнение всего треугольниками(если я создам копию нужных мне вершин)
0
 Аватар для Cr0c
753 / 600 / 204
Регистрация: 06.08.2015
Сообщений: 2,432
04.02.2019, 15:21
NotGoodEnough, строишь вершины и сразу назначаешь в треугольники.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
04.02.2019, 15:21
Помогаю со студенческими работами здесь

Как "выдавить" бит знаковости?
Не понимаю за что авторы жпбы так люто ненавидят бинарные данные, но мне с ними надо как то работать.А оператора &lt;&lt;&lt; нету :( Что...

Direct3D растянуть меш на весь экран
Всем привет! Проблема в том, что я столкнулся с проблемой в матричных преобразованиях и просто запутался, не могу понять как сделать...

Меш, VBO, VAO, IBO, отрисовка треугольников
Добрый вечер, хочу попросить по возможности совет и коррекцию кода. Дан VBO с координатами и цветами Нужно, чтобы отображалась...

Рельеф. Как правильно генерить нормали и меш без квадратных затенений
Доброго времени! Делаю свой Google Earth. Возникли проблемы с качеством отображения. А конкретно - появляются квадратные затенения на...


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

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Работа со звуком через SDL3_mixer
8Observer8 08.02.2026
Содержание блога Пошагово создадим проект для загрузки звукового файла и воспроизведения звука с помощью библиотеки SDL3_mixer. Звук будет воспроизводиться по клику мышки по холсту на Desktop и по. . .
SDL3 для Web (WebAssembly): Основы отладки веб-приложений на SDL3 по USB и Wi-Fi, запущенных в браузере мобильных устройств
8Observer8 07.02.2026
Содержание блога Браузер Chrome имеет средства для отладки мобильных веб-приложений по USB. В этой пошаговой инструкции ограничимся работой с консолью. Вывод в консоль - это часть процесса. . .
SDL3 для Web (WebAssembly): Обработчик клика мыши в браузере ПК и касания экрана в браузере на мобильном устройстве
8Observer8 02.02.2026
Содержание блога Для начала пошагово создадим рабочий пример для подготовки к экспериментам в браузере ПК и в браузере мобильного устройства. Потом напишем обработчик клика мыши и обработчик. . .
Философия технологии
iceja 01.02.2026
На мой взгляд у человека в технических проектах остается роль генерального директора. Все остальное нейронки делают уже лучше человека. Они не могут нести предпринимательские риски, не могут. . .
SDL3 для Web (WebAssembly): Вывод текста со шрифтом TTF с помощью SDL3_ttf
8Observer8 01.02.2026
Содержание блога В этой пошаговой инструкции создадим с нуля веб-приложение, которое выводит текст в окне браузера. Запустим на Android на локальном сервере. Загрузим Release на бесплатный. . .
SDL3 для Web (WebAssembly): Сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
SDL3 для Web (WebAssembly): Установка Emscripten SDK (emsdk) и CMake для сборки C и C++ приложений в Wasm
8Observer8 30.01.2026
Содержание блога Для того чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. . . .
SDL3 для Android: Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru