Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Web программирование > HTML и CSS
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 15.11.2024, 11:55   #181
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Бэкрумс коридоры одноэтажный но гладкие без углов

Код:
import numpy as np
import trimesh
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
import os

# Функция для генерации 3D-поля с коридорами
def generate_field(shape):
    array = np.zeros(shape, dtype=float)

    # Генерация точек для коридоров
    points = []
    for _ in range(10):
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        points.append([x, y, shape[2] // 2])  # Генерируем точки на фиксированной высоте

    # Генерация коридоров между точками
    for i in range(len(points) - 1):
        start_point = points[i]
        end_point = points[i + 1]

        # Горизонтальный или вертикальный коридор
        for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
            new_y = start_point[1]
            new_z = start_point[2]
            array[new_x, new_y, new_z] = 1.0
            # Делаем коридоры более жирными
            for k in range(-2, 3):
                for l in range(-2, 3):
                    for m in range(-2, 3):
                        x1, y1, z1 = new_x + k, new_y + l, new_z + m
                        if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                            array[x1, y1, z1] = 1.0

        for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
            new_x = end_point[0]
            new_z = end_point[2]
            array[new_x, new_y, new_z] = 1.0
            # Делаем коридоры более жирными
            for k in range(-2, 3):
                for l in range(-2, 3):
                    for m in range(-2, 3):
                        x1, y1, z1 = new_x + k, new_y + l, new_z + m
                        if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                            array[x1, y1, z1] = 1.0

    return array

# Параметры
shape = (128, 128, 128)  # Размеры 3D массива

# Генерация 3D-поля с коридорами
field = generate_field(shape)

# Создание изосурфейса
verts, faces, _, _ = measure.marching_cubes(field, level=0.5)

# Создание mesh с острыми углами
mesh = trimesh.Trimesh(vertices=verts, faces=faces)

# Сохранение mesh на рабочий стол
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "mesh.stl")
mesh.export(filename)
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='r', alpha=0.5)
plt.show()

Последний раз редактировалось MakarovDs; 15.11.2024 в 12:06.
MakarovDs на форуме Ответить с цитированием
Старый 15.11.2024, 15:42   #182
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Гиперукуб прелюдия
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.spatial import Delaunay
import os

# Функция для генерации 3D-поля с триангуляцией Делоне
def generate_delaunay_field(shape, num_cubes, distance):
    array = np.zeros(shape, dtype=float)

    # Генерация кубов на фиксированной высоте
    points = []
    for i in range(num_cubes):
        x = (i % 2) * distance + distance // 2
        y = ((i // 2) % 2) * distance + distance // 2
        z = (i // 4) * distance + distance // 2
        if x < shape[0] and y < shape[1] and z < shape[2]:
            points.append([x, y, z])  # Генерируем кубы на фиксированной высоте
            generate_cube(array, (x, y, z), 5)

    # Генерация коридоров между кубами
    for i in range(len(points) - 1):
        dx = points[i+1][0] - points[i][0]
        dy = points[i+1][1] - points[i][1]
        dz = points[i+1][2] - points[i][2]
        length = max(abs(dx), abs(dy), abs(dz))
        for j in range(length):
            new_x = int(points[i][0] + j * dx // length)
            new_y = int(points[i][1] + j * dy // length)
            new_z = int(points[i][2] + j * dz // length)
            if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                array[new_x, new_y, new_z] = 1.0
                # Делаем коридоры более жирными
                for k in range(-2, 3):
                    for l in range(-2, 3):
                        for m in range(-2, 3):
                            x1, y1, z1 = new_x + k, new_y + l, new_z + m
                            if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                array[x1, y1, z1] = 1.0

    return array

# Функция для генерации куба в заданной точке
def generate_cube(array, point, size):
    x, y, z = int(point[0]), int(point[1]), int(point[2])
    for i in range(-size, size+1):
        for j in range(-size, size+1):
            for k in range(-size, size+1):
                new_x, new_y, new_z = x + i, y + j, z + k
                if 0 <= new_x < array.shape[0] and 0 <= new_y < array.shape[1] and 0 <= new_z < array.shape[2]:
                    array[new_x, new_y, new_z] = 1.0

# Параметры
shape = (128, 128, 128)  # Размеры 3D массива
num_cubes = 20
distance = 20  # Расстояние между кубами

# Генерация 3D-поля с триангуляцией Делоне
delaunay_field = generate_delaunay_field(shape, num_cubes, distance)

# Создание изосурфейса
verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='blue', alpha=0.5)
plt.show()
MakarovDs на форуме Ответить с цитированием
Старый 15.11.2024, 17:20   #183
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Гиперкуб развилка
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.spatial import Delaunay
import os

def generate_delaunay_field(shape, num_cubes, distance):
    array = np.zeros(shape, dtype=float)

    points = []
    for i in range(num_cubes):
        x = (i % 2) * distance + distance // 2
        y = ((i // 2) % 2) * distance + distance // 2
        z = (i // 4) * distance + distance // 2
        if x < shape[0] and y < shape[1] and z < shape[2]:
            points.append([x, y, z])  # Генерируем кубы на фиксированной высоте
            generate_cube(array, (x, y, z), 5)

    for i in range(len(points) - 1):
        dx = points[i+1][0] - points[i][0]
        dy = points[i+1][1] - points[i][1]
        dz = points[i+1][2] - points[i][2]
        length = max(abs(dx), abs(dy), abs(dz))

        if abs(dx) > abs(dy) and abs(dx) > abs(dz):
            for j in range(abs(dx)):
                new_x = int(points[i][0] + j * np.sign(dx))
                new_y = points[i][1]
                new_z = points[i][2]
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
            for j in range(abs(dz)):
                new_x = new_x
                new_y = new_y
                new_z = int(points[i][2] + j * np.sign(dz))
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
        elif abs(dy) > abs(dx) and abs(dy) > abs(dz):
            for j in range(abs(dy)):
                new_x = points[i][0]
                new_y = int(points[i][1] + j * np.sign(dy))
                new_z = points[i][2]
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
            for j in range(abs(dz)):
                new_x = new_x
                new_y = new_y
                new_z = int(points[i][2] + j * np.sign(dz))
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
        else:
            for j in range(abs(dz)):
                new_x = points[i][0]
                new_y = points[i][1]
                new_z = int(points[i][2] + j * np.sign(dz))
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0

    for i in range(len(points)):
        x, y, z = points[i]
        if 0 <= x < shape[0] and 0 <= y < shape[1] and 0 <= z < shape[2]:
            for j in range(shape[0]):
                new_x = j
                new_y = y
                new_z = z
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
            for j in range(shape[1]):
                new_x = x
                new_y = j
                new_z = z
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
            for j in range(shape[2]):
                new_x = x
                new_y = y
                new_z = j
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0

    return array

def generate_cube(array, point, size):
    x, y, z = int(point[0]), int(point[1]), int(point[2])
    for i in range(-size, size+1):
        for j in range(-size, size+1):
            for k in range(-size, size+1):
                new_x, new_y, new_z = x + i, y + j, z + k
                if 0 <= new_x < array.shape[0] and 0 <= new_y < array.shape[1] and 0 <= new_z < array.shape[2]:
                    array[new_x, new_y, new_z] = 1.0

shape = (128, 128, 128) 
num_cubes = 60
distance = 20  

delaunay_field = generate_delaunay_field(shape, num_cubes, distance)

verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='blue', alpha=0.5)
plt.show()
MakarovDs на форуме Ответить с цитированием
Старый 15.11.2024, 19:34   #184
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Дырокольный куб
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.spatial import Delaunay
import os

# Функция для генерации 3D-поля с триангуляцией Делоне
def generate_delaunay_field(shape, num_cubes, distance):
    array = np.zeros(shape, dtype=float)

    # Генерация сетки коридоров
    for x in range(0, shape[0], distance):
        for y in range(0, shape[1], distance):
            for z in range(0, shape[2], distance):
                # Генерация коридора по оси X
                for i in range(distance):
                    new_x = x + i
                    new_y = y
                    new_z = z
                    if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                        array[new_x, new_y, new_z] = 1.0
                # Генерация коридора по оси Y
                for i in range(distance):
                    new_x = x
                    new_y = y + i
                    new_z = z
                    if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                        array[new_x, new_y, new_z] = 1.0
                # Генерация коридора по оси Z
                for i in range(distance):
                    new_x = x
                    new_y = y
                    new_z = z + i
                    if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                        array[new_x, new_y, new_z] = 1.0

    # Генерация комнат в стыке коридоров
    for x in range(0, shape[0], distance):
        for y in range(0, shape[1], distance):
            for z in range(0, shape[2], distance):
                # Генерация комнаты
                generate_cube(array, (x, y, z), 5)

    return array

# Функция для генерации куба в заданной точке
def generate_cube(array, point, size):
    x, y, z = int(point[0]), int(point[1]), int(point[2])
    for i in range(-size, size+1):
        for j in range(-size, size+1):
            for k in range(-size, size+1):
                new_x, new_y, new_z = x + i, y + j, z + k
                if 0 <= new_x < array.shape[0] and 0 <= new_y < array.shape[1] and 0 <= new_z < array.shape[2]:
                    array[new_x, new_y, new_z] = 1.0

# Параметры
shape = (128, 128, 128)  # Размеры 3D массива
num_cubes = 60
distance = 10  # Расстояние между кубами

# Генерация 3D-поля с триангуляцией Делоне
delaunay_field = generate_delaunay_field(shape, num_cubes, distance)

# Создание изосурфейса
verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='blue', alpha=0.5)
plt.show()
MakarovDs на форуме Ответить с цитированием
Старый 15.11.2024, 19:39   #185
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Супер развилка
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.spatial import Delaunay
import os

def generate_delaunay_field(shape, num_cubes, distance):
    array = np.zeros(shape, dtype=float)

    points = []
    for i in range(num_cubes):
        x = (i % 10) * distance + distance // 2
        y = ((i // 10) % 10) * distance + distance // 2
        z = (i // 100) * distance + distance // 2
        if x < shape[0] and y < shape[1] and z < shape[2]:
            points.append([x, y, z])  # Генерируем кубы в трех измерениях
            generate_cube(array, (x, y, z), 5)

    for i in range(len(points)):
        x, y, z = points[i]
        if 0 <= x < shape[0] and 0 <= y < shape[1] and 0 <= z < shape[2]:
            for j in range(shape[0]):
                new_x = j
                new_y = y
                new_z = z
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
            for j in range(shape[1]):
                new_x = x
                new_y = j
                new_z = z
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
            for j in range(shape[2]):
                new_x = x
                new_y = y
                new_z = j
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0

    return array

def generate_cube(array, point, size):
    x, y, z = int(point[0]), int(point[1]), int(point[2])
    for i in range(-size, size+1):
        for j in range(-size, size+1):
            for k in range(-size, size+1):
                new_x, new_y, new_z = x + i, y + j, z + k
                if 0 <= new_x < array.shape[0] and 0 <= new_y < array.shape[1] and 0 <= new_z < array.shape[2]:
                    array[new_x, new_y, new_z] = 1.0

shape = (128, 128, 128) 
num_cubes = 1000
distance = 10

delaunay_field = generate_delaunay_field(shape, num_cubes, distance)

verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='blue', alpha=0.5)
plt.show()

Особенно если модификатор mirror применить внутри выглядят очень зомбирующе

Последний раз редактировалось MakarovDs; 15.11.2024 в 19:42.
MakarovDs на форуме Ответить с цитированием
Старый 16.11.2024, 08:24   #186
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Гиперкуб
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.spatial import Delaunay
import os

def generate_delaunay_field(shape, num_cubes, distance):
    array = np.zeros(shape, dtype=float)

    points = []
    for i in range(num_cubes):
        x = (i % 4) * distance + distance // 2
        y = ((i // 4) % 4) * distance + distance // 2
        z = (i // 16) * distance + distance // 2
        if x < shape[0] and y < shape[1] and z < shape[2]:
            points.append([x, y, z]) 
            generate_cube(array, (x, y, z), 5)

    for point in points:
        x, y, z = point
        for i in range(-1, 2):
            for j in range(-1, 2):
                for k in range(-1, 2):
                    new_x, new_y, new_z = x + i * distance, y + j * distance, z + k * distance
                    if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                        generate_cube(array, (new_x, new_y, new_z), 5)

    for i in range(len(points)):
        x, y, z = points[i]
        for j in range(shape[0]):
            new_x = j
            new_y = y
            new_z = z
            if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                array[new_x, new_y, new_z] = 1.0
                for k in range(-2, 3):
                    for l in range(-2, 3):
                        for m in range(-2, 3):
                            x1, y1, z1 = new_x + k, new_y + l, new_z + m
                            if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                array[x1, y1, z1] = 1.0
        for j in range(shape[1]):
            new_x = x
            new_y = j
            new_z = z
            if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                array[new_x, new_y, new_z] = 1.0
                for k in range(-2, 3):
                    for l in range(-2, 3):
                        for m in range(-2, 3):
                            x1, y1, z1 = new_x + k, new_y + l, new_z + m
                            if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                array[x1, y1, z1] = 1.0
        for j in range(shape[2]):
            new_x = x
            new_y = y
            new_z = j
            if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                array[new_x, new_y, new_z] = 1.0
                for k in range(-2, 3):
                    for l in range(-2, 3):
                        for m in range(-2, 3):
                            x1, y1, z1 = new_x + k, new_y + l, new_z + m
                            if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                array[x1, y1, z1] = 1.0

    for i in range(len(points) - 1):
        dx = points[i+1][0] - points[i][0]
        dy = points[i+1][1] - points[i][1]
        dz = points[i+1][2] - points[i][2]
        length = max(abs(dx), abs(dy), abs(dz))

        if abs(dx) > abs(dy) and abs(dx) > abs(dz):
            for j in range(abs(dx)):
                new_x = int(points[i][0] + j * np.sign(dx))
                new_y = points[i][1]
                new_z = points[i][2]
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
            for j in range(abs(dz)):
                new_x = new_x
                new_y = new_y
                new_z = int(points[i][2] + j * np.sign(dz))
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
        elif abs(dy) > abs(dx) and abs(dy) > abs(dz):
            for j in range(abs(dy)):
                new_x = points[i][0]
                new_y = int(points[i][1] + j * np.sign(dy))
                new_z = points[i][2]
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
            for j in range(abs(dz)):
                new_x = new_x
                new_y = new_y
                new_z = int(points[i][2] + j * np.sign(dz))
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0
        else:
            for j in range(abs(dz)):
                new_x = points[i][0]
                new_y = points[i][1]
                new_z = int(points[i][2] + j * np.sign(dz))
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    array[new_x, new_y, new_z] = 1.0
                    for k in range(-2, 3):
                        for l in range(-2, 3):
                            for m in range(-2, 3):
                                x1, y1, z1 = new_x + k, new_y + l, new_z + m
                                if 0 <= x1 < shape[0] and 0 <= y1 < shape[1] and 0 <= z1 < shape[2]:
                                    array[x1, y1, z1] = 1.0

    return array

def generate_cube(array, point, size):
    x, y, z = int(point[0]), int(point[1]), int(point[2])
    for i in range(-size, size+1):
        for j in range(-size, size+1):
            for k in range(-size, size+1):
                new_x, new_y, new_z = x + i, y + j, z + k
                if 0 <= new_x < array.shape[0] and 0 <= new_y < array.shape[1] and 0 <= new_z < array.shape[2]:
                    array[new_x, new_y, new_z] = 1.0

shape = (64, 64, 64) 
num_cubes = 50
distance = 20  

delaunay_field = generate_delaunay_field(shape, num_cubes, distance)

verts, faces, _, _ = measure.marching_cubes(delaunay_field, level=0.5)

desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay.obj")
with open(filename, "w") as f:
    for j, vert in enumerate(verts):
        f.write(f"v {vert[0]} {vert[1]} {vert[2]}\n")
    for face in faces:
        f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1}\n")
print(f"Model saved as {filename}")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], verts[:, 2], color='blue', alpha=0.5)
plt.show()

Думал что не понадобиться
MakarovDs на форуме Ответить с цитированием
Старый 16.11.2024, 15:21   #187
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Дорожки остроугольные но это скрипт блендер
Код:
import bpy
import bgl
import mathutils
import random

def generate_plane_field(shape):
    points = []
    for _ in range(10):
        x = random.randint(10, shape[0] - 10)
        y = random.randint(10, shape[1] - 10)
        points.append((x, y))

    meshes = []
    for point in points:
        x, y = point
        bpy.ops.mesh.primitive_plane_add(location=(x, y, 0), size=2)
        meshes.append(bpy.context.active_object)

    for i in range(len(points) - 1):
        dx = points[i+1][0] - points[i][0]
        dy = points[i+1][1] - points[i][1]
        length = max(abs(dx), abs(dy))
        if abs(dx) > abs(dy):
            for j in range(length):
                new_x = int(points[i][0] + j * dx // length)
                new_y = points[i][1]
                bpy.ops.mesh.primitive_plane_add(location=(new_x, new_y, 0), size=2)
                meshes.append(bpy.context.active_object)
        else:
            for j in range(length):
                new_x = points[i][0]
                new_y = int(points[i][1] + j * dy // length)
                bpy.ops.mesh.primitive_plane_add(location=(new_x, new_y, 0), size=2)
                meshes.append(bpy.context.active_object)

    # Объединяем все меши в один
    bpy.ops.object.select_all(action='DESELECT')
    for mesh in meshes:
        mesh.select_set(True)
    bpy.ops.object.join()

    # Удаляем все грани, кроме верхней
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.select_all(action='SELECT')
    bpy.ops.mesh.remove_doubles(threshold=0.01)
    bpy.ops.mesh.delete_loose()

    # Выбираем все грани
    bpy.ops.mesh.select_all(action='SELECT')
    
    # Выбираем только нижние грани
    bpy.ops.mesh.select_mirror(axis=['Z'])
    # Удаляем нижние грани
    bpy.ops.mesh.delete(type='FACE')

    # Выбираем только нижние вершины
    bpy.ops.mesh.select_mirror(axis=['Z'])
    # Удаляем нижние вершины
    bpy.ops.mesh.delete(type='VERT')

    bpy.ops.object.mode_set(mode='OBJECT')

    bpy.ops.object.modifier_add(type='SOLIDIFY')
    bpy.context.object.modifiers['Solidify'].thickness = 2
    
def main():
    shape = (128, 128)
    generate_plane_field(shape)

if __name__ == "__main__":
    main()

Последний раз редактировалось MakarovDs; 16.11.2024 в 15:28.
MakarovDs на форуме Ответить с цитированием
Старый 17.11.2024, 06:31   #188
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Генератор остроугольных комнат бэкрумс но это скрипт для блендера зарисовка
Код:
import bpy
import math
import random

# Функция для генерации комнаты
def generate_room(x, z):
    room_size = random.randint(5, 15)
    room_height = random.randint(5, 10)
    room = bpy.data.meshes.new("Room")
    room_object = bpy.data.objects.new("Room", room)
    bpy.context.collection.objects.link(room_object)
    room_object.location = (x, 0, z)
    vertices = [
        (0, 0, 0),
        (room_size, 0, 0),
        (room_size, room_size, 0),
        (0, room_size, 0),
        (0, 0, room_height),
        (room_size, 0, room_height),
        (room_size, room_size, room_height),
        (0, room_size, room_height)
    ]
    edges = [
        (0, 1),
        (1, 2),
        (2, 3),
        (3, 0),
        (4, 5),
        (5, 6),
        (6, 7),
        (7, 4),
        (0, 4),
        (1, 5),
        (2, 6),
        (3, 7)
    ]
    faces = [
        (0, 1, 2, 3),
        (4, 5, 6, 7),
        (0, 1, 5, 4),
        (1, 2, 6, 5),
        (2, 3, 7, 6),
        (3, 0, 4, 7)
    ]
    room.from_pydata(vertices, edges, faces)
    room.update(calc_edges=True)
    return room_object

# Функция для генерации коридора
def generate_corridor(x, z, length, direction):
    corridor_width = 2
    corridor_height = 2
    corridor = bpy.data.meshes.new("Corridor")
    corridor_object = bpy.data.objects.new("Corridor", corridor)
    bpy.context.collection.objects.link(corridor_object)
    corridor_object.location = (x, 0, z)
    corridor_object.rotation_euler = (0, 0, direction)
    vertices = [
        (0, -corridor_width/2, 0),
        (length, -corridor_width/2, 0),
        (length, corridor_width/2, 0),
        (0, corridor_width/2, 0),
        (0, -corridor_width/2, corridor_height),
        (length, -corridor_width/2, corridor_height),
        (length, corridor_width/2, corridor_height),
        (0, corridor_width/2, corridor_height)
    ]
    edges = [
        (0, 1),
        (1, 2),
        (2, 3),
        (3, 0),
        (4, 5),
        (5, 6),
        (6, 7),
        (7, 4),
        (0, 4),
        (1, 5),
        (2, 6),
        (3, 7)
    ]
    faces = [
        (0, 1, 2, 3),
        (4, 5, 6, 7),
        (0, 1, 5, 4),
        (1, 2, 6, 5),
        (2, 3, 7, 6),
        (3, 0, 4, 7)
    ]
    corridor.from_pydata(vertices, edges, faces)
    corridor.update(calc_edges=True)
    return corridor_object

# Генерация комнат и коридоров
for _ in range(10):
    x = random.randint(-50, 50)
    z = random.randint(-50, 50)
    room = generate_room(x, z)
    if random.random() < 0.5:
        corridor_length = random.randint(5, 20)
        corridor_direction = random.uniform(0, math.pi)
        generate_corridor(x, z, corridor_length, corridor_direction)
    if random.random() < 0.5:
        x2 = x + random.randint(-10, 10)
        z = z + random.randint(-10, 10)
        room2 = generate_room(x, z)
        corridor_length = math.sqrt((x - x)**2 + (z - z)**2)
        corridor_direction = math.atan2(z - z, x - x)
        generate_corridor(x, z, corridor_length, corridor_direction)
MakarovDs на форуме Ответить с цитированием
Старый 17.11.2024, 09:55   #189
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Генератор остроугольных комнат бэкрумс но это python
Код:
import numpy as np
import trimesh
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import os

def generate_room(x, z):
    room_size = np.random.randint(5, 15)
    room_height = np.random.randint(5, 10)
    vertices = np.array([
        [0, 0, 0],
        [room_size, 0, 0],
        [room_size, room_size, 0],
        [0, room_size, 0],
        [0, 0, room_height],
        [room_size, 0, room_height],
        [room_size, room_size, room_height],
        [0, room_size, room_height]
    ])
    faces = np.array([
        [0, 1, 2, 3],
        [4, 5, 6, 7],
        [0, 1, 5, 4],
        [1, 2, 6, 5],
        [2, 3, 7, 6],
        [3, 0, 4, 7]
    ])
    mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
    mesh.vertices += [x, 0, z]
    return mesh

def generate_corridor(x, z, length, direction):
    corridor_width = 2
    corridor_height = 2
    vertices = np.array([
        [0, -corridor_width/2, 0],
        [length, -corridor_width/2, 0],
        [length, corridor_width/2, 0],
        [0, corridor_width/2, 0],
        [0, -corridor_width/2, corridor_height],
        [length, -corridor_width/2, corridor_height],
        [length, corridor_width/2, corridor_height],
        [0, corridor_width/2, corridor_height]
    ])
    faces = np.array([
        [0, 1, 2, 3],
        [4, 5, 6, 7],
        [0, 1, 5, 4],
        [1, 2, 6, 5],
        [2, 3, 7, 6],
        [3, 0, 4, 7]
    ])
    mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
    mesh.vertices += [x, 0, z]
    rotation_matrix = np.array([
        [np.cos(direction), -np.sin(direction), 0],
        [np.sin(direction), np.cos(direction), 0],
        [0, 0, 1]
    ])
    mesh.vertices = (rotation_matrix @ mesh.vertices.T).T
    return mesh

# Генерация комнат и коридоров
meshes = []
for _ in range(10):
    x = np.random.randint(-50, 50)
    z = np.random.randint(-50, 50)
    room = generate_room(x, z)
    meshes.append(room)
    if np.random.rand() < 0.5:
        corridor_length = np.random.randint(5, 20)
        corridor_direction = np.random.uniform(0, np.pi)
        corridor = generate_corridor(x, z, corridor_length, corridor_direction)
        meshes.append(corridor)
    if np.random.rand() < 0.5:
        x2 = x + np.random.randint(-10, 10)
        z2 = z + np.random.randint(-10, 10)
        room2 = generate_room(x2, z2)
        meshes.append(room2)
        corridor_length = np.sqrt((x - x2)**2 + (z - z2)**2)
        corridor_direction = np.arctan2(z2 - z, x2 - x)
        corridor = generate_corridor(x, z, corridor_length, corridor_direction)
        meshes.append(corridor)

# Сохранение модели
mesh = trimesh.util.concatenate(meshes)
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "model.obj")
mesh.export(filename)
print(f"Model saved as {filename}")

# Визуализация модели
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(mesh.vertices[:, 0], mesh.vertices[:, 1], mesh.vertices[:, 2], color='r', alpha=0.5)
for face in mesh.faces:
    v1, v2, v3 = mesh.vertices[face]
    ax.plot3D([v1[0], v2[0]], [v1[1], v2[1]], [v1[2], v2[2]], 'r', alpha=0.5)
    ax.plot3D([v2[0], v3[0]], [v2[1], v3[1]], [v2[2], v3[2]], 'r', alpha=0.5)
    ax.plot3D([v3[0], v1[0]], [v3[1], v1[1]], [v3[2], v1[2]], 'r', alpha=0.5)
plt.show()
Я бы назвал это чёрной зоной - это там где коридоры, и комнаты генерируются отдельно друг от друга вися в noclipping пространстве, и типа туда можно попасть выпав из реальности но оттуда нельзя вернуться... Хотя если попытаться проломить стену то можно ещё пролететь в noclipping пространстве, и если повезёт то выпасть в какой-то случайный коридор, и уже шансы повысятся хотя все равно сдохнешь от обезвоживания, и голода хотя если сдирать обои и жрать их то можно какой то время протянуть или если просто замкнуть провода, и сжечь нахер эти коридоры то можно питаться пеплом хотя тоже не вариант.

Типа по аналогии с тем видосом
https://youtu.be/zRPYpBHUGeM?si=VFutgAv9MU-V1Jnm&t=1276
Где был такой дом висящий в пустоте

Последний раз редактировалось MakarovDs; 17.11.2024 в 10:20.
MakarovDs на форуме Ответить с цитированием
Старый 17.11.2024, 14:59   #190
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 344
По умолчанию

Паутина глюков одноплоская
Код:
import numpy as np
import trimesh
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
import os

# Функция для генерации 2D-поля с коридорами
def generate_field(shape):
    array = np.zeros(shape, dtype=float)

    # Генерация точек для коридоров
    points = []
    for _ in range(10):
        x = np.random.randint(10, shape[0] - 10)
        y = np.random.randint(10, shape[1] - 10)
        points.append([x, y])  # Генерируем точки

    # Генерация коридоров между точками
    for i in range(len(points) - 1):
        start_point = points[i]
        end_point = points[i + 1]

        # Горизонтальный или вертикальный коридор
        if abs(start_point[0] - end_point[0]) > abs(start_point[1] - end_point[1]):
            for new_x in range(min(start_point[0], end_point[0]), max(start_point[0], end_point[0]) + 1):
                new_y = start_point[1]
                array[new_x, new_y] = 1.0
                # Делаем коридоры более жирными
                for k in range(-2, 3):
                    for l in range(-2, 3):
                        x1, y1 = new_x + k, new_y + l
                        if 0 <= x1 < shape[0] and 0 <= y1 < shape[1]:
                            array[x1, y1] = 1.0
        else:
            for new_y in range(min(start_point[1], end_point[1]), max(start_point[1], end_point[1]) + 1):
                new_x = start_point[0]
                array[new_x, new_y] = 1.0
                # Делаем коридоры более жирными
                for k in range(-2, 3):
                    for l in range(-2, 3):
                        x1, y1 = new_x + k, new_y + l
                        if 0 <= x1 < shape[0] and 0 <= y1 < shape[1]:
                            array[x1, y1] = 1.0

    return array

# Функция для генерации комнаты
def generate_room(x, y):
    room_size = np.random.randint(5, 15)
    room_height = np.random.randint(5, 10)
    vertices = np.array([
        [0, 0, 0],
        [room_size, 0, 0],
        [room_size, room_size, 0],
        [0, room_size, 0],
        [0, 0, room_height],
        [room_size, 0, room_height],
        [room_size, room_size, room_height],
        [0, room_size, room_height]
    ])
    faces = np.array([
        [0, 1, 2, 3],
        [4, 5, 6, 7],
        [0, 1, 5, 4],
        [1, 2, 6, 5],
        [2, 3, 7, 6],
        [3, 0, 4, 7]
    ])
    mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
    mesh.vertices += [x, y, 0]
    return mesh

# Параметры
shape = (128, 128)  # Размеры 2D массива

# Генерация 2D-поля с коридорами
field = generate_field(shape)

# Создание изосурфейса
contours = measure.find_contours(field, 0.5)

# Создание mesh с острыми углами
corridor_mesh = trimesh.Trimesh(vertices=None, faces=None)
for contour in contours:
    contour = contour.astype(int)
    contour = np.column_stack((contour[:, 0], contour[:, 1], np.zeros(contour.shape[0])))
    vertices = np.zeros((contour.shape[0] * 2, 3))
    for i in range(contour.shape[0]):
        vertices[i * 2] = contour[i]
        vertices[i * 2 + 1] = contour[i] + np.array([0, 0, 1])
    faces = np.zeros((contour.shape[0] * 4, 3), dtype=int)
    for i in range(contour.shape[0]):
        faces[i * 4] = [i * 2, (i + 1) % (contour.shape[0] * 2), i * 2 + 1]
        faces[i * 4 + 1] = [(i + 1) % (contour.shape[0] * 2), (i + 1) % (contour.shape[0] * 2) + 1, i * 2 + 1]
        faces[i * 4 + 2] = [i * 2, i * 2 + 1, (i + 1) % (contour.shape[0] * 2)]
        faces[i * 4 + 3] = [(i + 1) % (contour.shape[0] * 2), (i + 1) % (contour.shape[0] * 2) + 1, i * 2]
    mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
    corridor_mesh = trimesh.util.concatenate([corridor_mesh, mesh])

# Генерация комнат
rooms = []
for _ in range(10):
    x = np.random.randint(10, 128 - 10)
    y = np.random.randint(10, 128 - 10)
    room = generate_room(x, y)
    rooms.append(room)

# Объединение комнат и коридоров
meshes = [corridor_mesh] + rooms
mesh = trimesh.util.concatenate(meshes)

# Сохранение mesh на рабочий стол
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "mesh.stl")
mesh.export(filename)
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(mesh.vertices[:, 0], mesh.vertices[:, 1], mesh.vertices[:, 2], color='r', alpha=0.5)
plt.show()
MakarovDs на форуме Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
помогите с генератором слов Мой повелитель Общие вопросы C/C++ 6 27.02.2016 23:46
Зарубежные микроконтроллеры с встроенным ШИМ-генератором MyLastHit Компьютерное железо 6 22.10.2013 14:33
написание генератора фракталов Жюлиа kyzmich2370 Visual C++ 1 06.11.2012 09:57
Помогите с генератором чисел на Pascal vadmaruschak Помощь студентам 6 13.09.2009 17:06
Игры фракталов на VB Kail Свободное общение 1 29.05.2009 09:30