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

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

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

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

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

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

Но всё таки зона Долонгов это изогнутые линии а не кривые...
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
from scipy.interpolate import interp1d

# Генерация случайной функции с двумя переменными
def generate_function():
    functions = [lambda x, y: x + y, lambda x, y: x - y, lambda x, y: x * y, lambda x, y: x / y]
    return random.choice(functions)

# Генерация фрактала
def generate_fractal(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_fractal(x1, y1, z1, depth - 1)

# Генерация полостей и самоподобия
def generate_cavity(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_cavity(x1, y1, z1, depth - 1)

# Генерация трехмерного пространства
def generate_space():
    x = np.random.uniform(-10, 10)
    y = np.random.uniform(-10, 10)
    z = np.random.uniform(-10, 10)
    depth = np.random.randint(1, 10)
    return generate_fractal(x, y, z, depth)

# Визуализация пространства
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points = []
for i in range(100):
    x, y, z = generate_space()
    points.append([x, y, z])

# Интерполяция
t = np.linspace(0, 1, len(points))
x = np.array([point[0] for point in points])
y = np.array([point[1] for point in points])
z = np.array([point[2] for point in points])

x_interp = interp1d(t, x, kind='cubic')
y_interp = interp1d(t, y, kind='cubic')
z_interp = interp1d(t, z, kind='cubic')

t_interp = np.linspace(0, 1, 1000)
x_interp = x_interp(t_interp)
y_interp = y_interp(t_interp)
z_interp = z_interp(t_interp)

ax.plot(x_interp, y_interp, z_interp, 'b-')

ax.scatter(*zip(*points))
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 26.10.2024, 17:35   #92
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 377
По умолчанию

TheMezzanine 2
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.interpolate import interp1d
import os

# Генерация изогнутой линии
def generate_curve():
    points = []
    for i in range(100):
        x = np.random.uniform(-10, 10)
        y = np.random.uniform(-10, 10)
        z = np.random.uniform(-10, 10)
        points.append([x, y, z])

    # Интерполяция
    t = np.linspace(0, 1, len(points))
    x = np.array([point[0] for point in points])
    y = np.array([point[1] for point in points])
    z = np.array([point[2] for point in points])

    x_interp = interp1d(t, x, kind='cubic')
    y_interp = interp1d(t, y, kind='cubic')
    z_interp = interp1d(t, z, kind='cubic')

    t_interp = np.linspace(0, 1, 1000)
    x_interp = x_interp(t_interp)
    y_interp = y_interp(t_interp)
    z_interp = z_interp(t_interp)

    return x_interp, y_interp, z_interp

# Генерация изосурфейса
def generate_surface(x, y, z):
    # Создание 3D массива
    array = np.zeros((64, 64, 64), dtype=float)

    # Создание трубчатой структуры
    for i in range(len(x)):
        x_idx = int((x[i] + 10) / 20 * 64)
        y_idx = int((y[i] + 10) / 20 * 64)
        z_idx = int((z[i] + 10) / 20 * 64)

        if 0 <= x_idx < 64 and 0 <= y_idx < 64 and 0 <= z_idx < 64:
            for dx in range(-2, 3):
                for dy in range(-2, 3):
                    for dz in range(-2, 3):
                        if 0 <= x_idx + dx < 64 and 0 <= y_idx + dy < 64 and 0 <= z_idx + dz < 64:
                            array[x_idx + dx, y_idx + dy, z_idx + dz] = 1.0

    return array

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

# Генерация изогнутой линии
x, y, z = generate_curve()

# Генерация изосурфейса
surface = generate_surface(x, y, z)

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

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "curve.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], faces, verts[:, 2], color='r', alpha=0.5)
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 26.10.2024, 17:52   #93
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 377
По умолчанию

Процедурный генератор изогнутых склонов...
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.interpolate import interp1d
import os

# Генерация изогнутой линии
def generate_curve():
    points = []
    for i in range(100):
        x = np.random.uniform(-10, 10)
        y = np.random.uniform(-10, 10)
        z = np.random.uniform(-10, 10)
        points.append([x, y, z])

    # Интерполяция
    t = np.linspace(0, 1, len(points))
    x = np.array([point[0] for point in points])
    y = np.array([point[1] for point in points])
    z = np.array([point[2] for point in points])

    x_interp = interp1d(t, x, kind='cubic')
    y_interp = interp1d(t, y, kind='cubic')
    z_interp = interp1d(t, z, kind='cubic')

    t_interp = np.linspace(0, 1, 1000)
    x_interp = x_interp(t_interp)
    y_interp = y_interp(t_interp)
    z_interp = z_interp(t_interp)

    return x_interp, y_interp, z_interp

# Генерация изосурфейса
def generate_surface(x, y, z):
    # Создание 3D массива
    array = np.zeros((64, 64, 64), dtype=float)

    # Создание трубчатой структуры
    for i in range(len(x) - 1):
        dx = x[i+1] - x[i]
        dy = y[i+1] - y[i]
        dz = z[i+1] - z[i]
        length = int(np.sqrt(dx**2 + dy**2 + dz**2))
        for j in range(length):
            new_x = x[i] + j * dx / length
            new_y = y[i] + j * dy / length
            new_z = z[i] + j * dz / length

            x_idx = int((new_x + 10) / 20 * 64)
            y_idx = int((new_y + 10) / 20 * 64)
            z_idx = int((new_z + 10) / 20 * 64)

            if 0 <= x_idx < 64 and 0 <= y_idx < 64 and 0 <= z_idx < 64:
                for dx in range(-2, 3):
                    for dy in range(-2, 3):
                        for dz in range(-2, 3):
                            if 0 <= x_idx + dx < 64 and 0 <= y_idx + dy < 64 and 0 <= z_idx + dz < 64:
                                distance = np.sqrt(dx**2 + dy**2 + dz**2)
                                if distance < 1.5:
                                    array[x_idx + dx, y_idx + dy, z_idx + dz] = 1.0

    # Удаление ненужных точек
    for x_idx in range(64):
        for y_idx in range(64):
            for z_idx in range(64):
                if array[x_idx, y_idx, z_idx] == 1.0:
                    for dx in range(-1, 2):
                        for dy in range(-1, 2):
                            for dz in range(-1, 2):
                                if 0 <= x_idx + dx < 64 and 0 <= y_idx + dy < 64 and 0 <= z_idx + dz < 64:
                                    if array[x_idx + dx, y_idx + dy, z_idx + dz] == 0.0:
                                        array[x_idx + dx, y_idx + dy, z_idx + dz] = 1.0

    return array

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

# Генерация изогнутой линии
x, y, z = generate_curve()

# Генерация изосурфейса
surface = generate_surface(x, y, z)

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

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "curve.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], faces, verts[:, 2], color='r', alpha=0.5)
plt.show()

Идеально подойдет для процедурной генераций каких нибудь подземелий гномов типа горы Эребор где есть такие пологие склоны

Последний раз редактировалось MakarovDs; 27.10.2024 в 00:11.
MakarovDs вне форума Ответить с цитированием
Старый 26.10.2024, 21:46   #94
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 377
По умолчанию

Процедурный генератор обломков столбов
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from skimage import measure
from scipy.interpolate import interp1d
import os
import random
# Генерация случайной функции с двумя переменными
def generate_function():
    functions = [lambda x, y: x + y, lambda x, y: x - y, lambda x, y: x * y, lambda x, y: x / y]
    return random.choice(functions)

# Генерация фрактала
def generate_fractal(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_fractal(x1, y1, z1, depth - 1)

# Генерация полостей и самоподобия
def generate_cavity(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_cavity(x1, y1, z1, depth - 1)

# Генерация трехмерного пространства
def generate_space():
    x = np.random.uniform(-10, 10)
    y = np.random.uniform(-10, 10)
    z = np.random.uniform(-10, 10)
    depth = np.random.randint(1, 10)
    return generate_fractal(x, y, z, depth)

# Визуализация пространства
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points = []
for i in range(100):
    x, y, z = generate_space()
    points.append([x, y, z])

# Интерполяция
t = np.linspace(0, 1, len(points))
x = np.array([point[0] for point in points])
y = np.array([point[1] for point in points])
z = np.array([point[2] for point in points])

x_interp = interp1d(t, x, kind='cubic')
y_interp = interp1d(t, y, kind='cubic')
z_interp = interp1d(t, z, kind='cubic')

t_interp = np.linspace(0, 1, 1000)
x_interp = x_interp(t_interp)
y_interp = y_interp(t_interp)
z_interp = z_interp(t_interp)

ax.plot(x_interp, y_interp, z_interp, 'b-')

ax.scatter(*zip(*points))

# Создание 3D массива для генерации изосурфейса
shape = (64, 64, 64)
array = np.zeros(shape, dtype=float)

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 = int(np.sqrt(dx**2 + dy**2 + dz**2))
    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
            # Делаем линии более жирными
            if new_x > 0:
                array[new_x-1, new_y, new_z] = 1.0
            if new_x < shape[0] - 1:
                array[new_x+1, new_y, new_z] = 1.0
            if new_y > 0:
                array[new_x, new_y-1, new_z] = 1.0
            if new_y < shape[1] - 1:
                array[new_x, new_y+1, new_z] = 1.0
            if new_z > 0:
                array[new_x, new_y, new_z-1] = 1.0
            if new_z < shape[2] - 1:
                array[new_x, new_y, new_z+1] = 1.0

# Генерация изосурфейса
verts, faces, _, _ = measure.marching_cubes(array, level=0.5)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "lines.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.scatter(verts[:, 0], verts[:, 1], verts[:, 2], c='b')

# Визуализация граней
for face in faces:
    ax.plot3D([verts[face[0], 0], verts[face[1], 0], verts[face[2], 0], verts[face[0], 0]],
              [verts[face[0], 1], verts[face[1], 1], verts[face[2], 1], verts[face[0], 1]],
              [verts[face[0], 2], verts[face[1], 2], verts[face[2], 2], verts[face[0], 2]], c='r')

plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 26.10.2024, 22:08   #95
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 377
По умолчанию

Процедурный генератор обломков столбов БОЛЬШОЙ
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.interpolate import interp1d
from skimage import measure
import random
import os
# Генерация случайной функции с двумя переменными
def generate_function():
    functions = [lambda x, y: x + y, lambda x, y: x - y, lambda x, y: x * y, lambda x, y: x / y]
    return random.choice(functions)

# Генерация фрактала
def generate_fractal(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_fractal(x1, y1, z1, depth - 1)

# Генерация полостей и самоподобия
def generate_cavity(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_cavity(x1, y1, z1, depth - 1)

# Генерация трехмерного пространства
def generate_space():
    x = np.random.uniform(-10, 10)
    y = np.random.uniform(-10, 10)
    z = np.random.uniform(-10, 10)
    depth = np.random.randint(1, 10)
    return generate_fractal(x, y, z, depth)

# Визуализация пространства
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points = []
for i in range(100):
    x, y, z = generate_space()
    points.append([x, y, z])

# Интерполяция
t = np.linspace(0, 1, len(points))
x = np.array([point[0] for point in points])
y = np.array([point[1] for point in points])
z = np.array([point[2] for point in points])

x_interp = interp1d(t, x, kind='cubic')
y_interp = interp1d(t, y, kind='cubic')
z_interp = interp1d(t, z, kind='cubic')

t_interp = np.linspace(0, 1, 1000)
x_interp = x_interp(t_interp)
y_interp = y_interp(t_interp)
z_interp = z_interp(t_interp)

ax.plot(x_interp, y_interp, z_interp, 'b-', linewidth=5)

# Создание 3D массива для генерации изосурфейса
shape = (64, 64, 64)
array = np.zeros(shape, dtype=float)

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 = int(np.sqrt(dx**2 + dy**2 + dz**2))
    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
            # Делаем линии более жирными
            if new_x > 0:
                array[new_x-1, new_y, new_z] = 1.0
            if new_x < shape[0] - 1:
                array[new_x+1, new_y, new_z] = 1.0
            if new_y > 0:
                array[new_x, new_y-1, new_z] = 1.0
            if new_y < shape[1] - 1:
                array[new_x, new_y+1, new_z] = 1.0
            if new_z > 0:
                array[new_x, new_y, new_z-1] = 1.0
            if new_z < shape[2] - 1:
                array[new_x, new_y, new_z+1] = 1.0

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

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "model.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}")

# Визуализация вершин и граней изосурфейса
for face in faces:
    ax.plot([verts[face[0], 0], verts[face[1], 0], verts[face[2], 0], verts[face[0], 0]],
            [verts[face[0], 1], verts[face[1], 1], verts[face[2], 1], verts[face[0], 1]],
            [verts[face[0], 2], verts[face[1], 2], verts[face[2], 2], verts[face[0], 2]], c='r', linewidth=5)

plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 26.10.2024, 22:46   #96
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 377
По умолчанию

Процедурный генератор стен небоскребов
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
from scipy.interpolate import interp1d
from skimage import measure
import os

# Генерация случайной функции с двумя переменными
def generate_function():
    functions = [lambda x, y: x + y, lambda x, y: x - y, lambda x, y: x * y, lambda x, y: x / y]
    return random.choice(functions)

# Генерация фрактала
def generate_fractal(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_fractal(x1, y1, z1, depth - 1)

# Генерация полостей и самоподобия
def generate_cavity(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_cavity(x1, y1, z1, depth - 1)

# Генерация трехмерного пространства
def generate_space():
    x = np.random.uniform(-10, 10)
    y = np.random.uniform(-10, 10)
    z = np.random.uniform(-10, 10)
    depth = np.random.randint(1, 10)
    return generate_fractal(x, y, z, depth)

# Визуализация пространства
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points = []
for i in range(100):
    x, y, z = generate_space()
    points.append([x, y, z])

# Интерполяция
t = np.linspace(0, 1, len(points))
x = np.array([point[0] for point in points])
y = np.array([point[1] for point in points])
z = np.array([point[2] for point in points])

x_interp = interp1d(t, x, kind='cubic')
y_interp = interp1d(t, y, kind='cubic')
z_interp = interp1d(t, z, kind='cubic')

x_interp_array = np.zeros((1000, 1000, 3))
for i in range(1000):
    for j in range(1000):
        x_interp_array[i, j, 0] = x_interp(i / 1000)
        x_interp_array[i, j, 1] = x_interp(j / 1000)
        x_interp_array[i, j, 2] = z_interp(i / 1000)

verts, faces, _, _ = measure.marching_cubes(x_interp_array, level=0.5)
# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "lines.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}")

# Визуализация
ax.scatter(*zip(*points))
plt.show()

Как раз подойдет для моего уровня -1000007 который удаляют некоторые пeдeрастическиe обезьянки на фандоме бэкрумса... Поэтому оставил описание на диске. Поэтому кстати ненавижу этот фандом закулисья написал свой эмоциональный порыв модератору он извинился, но потом всё равно удалил мой уровень ���� Какие же дуболомы! Непонимают что бэкрумс это мир бесконечностей где бесконечное число уровней! Там всевозможные вариаций размещений и сочетаний всевозможных пространств!

Последний раз редактировалось MakarovDs; 27.10.2024 в 00:42.
MakarovDs вне форума Ответить с цитированием
Старый 27.10.2024, 01:53   #97
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 377
По умолчанию

Триангуляция Делоне но линиями
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.spatial import Delaunay
import os

# Функция для генерации 3D-линии с триангуляцией Делоне
def generate_delaunay_line(shape):
    points = []
    for i in range(100):
        x = np.random.uniform(0, shape[0])
        y = np.random.uniform(0, shape[1])
        z = np.random.uniform(0, shape[2])
        points.append([x, y, z])

    # Преобразование точек в NumPy массив 
    points = np.array(points)

    # Выполнить триангуляцию Делоне
    triangulation = Delaunay(points)

    # Постройте график треугольников
    for triangle in triangulation.simplices:
        for i in range(3):
            dx = points[triangle[(i+1)%3], 0] - points[triangle[i], 0]
            dy = points[triangle[(i+1)%3], 1] - points[triangle[i], 1]
            dz = points[triangle[(i+1)%3], 2] - points[triangle[i], 2]
            length = int(np.sqrt(dx**2 + dy**2 + dz**2))
            for j in range(length):
                new_x = int(points[triangle[i], 0] + j * dx // length)
                new_y = int(points[triangle[i], 1] + j * dy // length)
                new_z = int(points[triangle[i], 2] + j * dz // length)
                if 0 <= new_x < shape[0] and 0 <= new_y < shape[1] and 0 <= new_z < shape[2]:
                    # Добавить точку в список точек
                    points = np.append(points, [[new_x, new_y, new_z]], axis=0)

    return points

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

# Генерация 3D-линии с триангуляцией Делоне
points = generate_delaunay_line(shape)

# Создание изосурфейса
verts = np.array(points)

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay_line.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 i in range(len(verts) - 1):
        f.write(f"l {i+1} {i+2}\n")
print(f"Model saved as {filename}")

# Визуализация
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(*zip(*verts), 'b-')
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 27.10.2024, 02:42   #98
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 377
По умолчанию

���� ��������
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.spatial import Delaunay
import os

# Функция для генерации 3D-трубки с триангуляцией Делоне
def generate_delaunay_tube(shape):
    points = []
    for i in range(100):
        x = np.random.uniform(0, shape[0])
        y = np.random.uniform(0, shape[1])
        z = np.random.uniform(0, shape[2])
        points.append([x, y, z])

    # Преобразование точек в NumPy массив 
    points = np.array(points)

    # Выполнить триангуляцию Делоне
    triangulation = Delaunay(points)

    # Создание трубки
    tube_points = []
    tube_faces = []
    for triangle in triangulation.simplices:
        for i in range(3):
            x1, y1, z1 = points[triangle[i]]
            x2, y2, z2 = points[triangle[(i+1)%3]]
            vec = np.array([x2-x1, y2-y1, z2-z1])
            vec = vec / np.linalg.norm(vec)
            perp_vec1 = np.array([vec[1], -vec[0], 0])
            perp_vec1 = perp_vec1 / np.linalg.norm(perp_vec1)
            perp_vec2 = np.cross(vec, perp_vec1)
            perp_vec2 = perp_vec2 / np.linalg.norm(perp_vec2)
            radius = 5
            num_points = 10
            angles = np.linspace(0, 2*np.pi, num_points)
            for k in range(num_points):
                pos1 = np.array([x1, y1, z1]) + radius * (np.cos(angles[k]) * perp_vec1 + np.sin(angles[k]) * perp_vec2)
                pos2 = np.array([x2, y2, z2]) + radius * (np.cos(angles[k]) * perp_vec1 + np.sin(angles[k]) * perp_vec2)
                tube_points.append(pos1.tolist())
                tube_points.append(pos2.tolist())
                tube_faces.append([len(tube_points)-2, len(tube_points)-1, len(tube_points)])
                tube_faces.append([len(tube_points)-1, len(tube_points)-2, len(tube_points)])

    return tube_points, tube_faces

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

# Генерация 3D-трубки с триангуляцией Делоне
tube_points, tube_faces = generate_delaunay_tube(shape)

# Сохранение трубки в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "delaunay_tube.obj")
with open(filename, "w") as f:
    for j, point in enumerate(tube_points):
        f.write(f"v {point[0]} {point[1]} {point[2]}\n")
    for face in tube_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')
for j in range(len(tube_points) - 1):
    ax.plot3D(*zip(tube_points[j], tube_points[j+1]), 'b-')
plt.show()
MakarovDs вне форума Ответить с цитированием
Старый 27.10.2024, 04:27   #99
MakarovDs
Форумчанин
 
Аватар для MakarovDs
 
Регистрация: 10.01.2020
Сообщений: 377
По умолчанию

���� ���������� ��������
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
from scipy.interpolate import make_interp_spline
from skimage import measure
import os

# Функция для генерации случайной точки в 3D пространстве
def generate_point():
    x = np.random.uniform(-10, 10)
    y = np.random.uniform(-10, 10)
    z = np.random.uniform(-10, 10)
    return np.array([x, y, z])

# Функция для генерации фрактала
def generate_fractal(point, depth):
    if depth == 0:
        return point
    else:
        x = point[0] + np.random.uniform(-1, 1)
        y = point[1] + np.random.uniform(-1, 1)
        z = point[2] + np.random.uniform(-1, 1)
        return generate_fractal(np.array([x, y, z]), depth - 1)

# Функция для генерации полостей и самоподобия
def generate_cavity(point, depth):
    if depth == 0:
        return point
    else:
        x = point[0] + np.random.uniform(-1, 1)
        y = point[1] + np.random.uniform(-1, 1)
        z = point[2] + np.random.uniform(-1, 1)
        return generate_cavity(np.array([x, y, z]), depth - 1)

# Функция для генерации 3D пространства
def generate_space(depth):
    point = generate_point()
    return generate_fractal(point, depth) + generate_cavity(point, depth)

# Функция для сохранения файла OBJ
def save_obj_file(verts, faces, filename):
    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")

# Параметры
num_points = 100
depth = 5

# Генерация точек в 3D пространстве
points = [generate_space(depth) for _ in range(num_points)]

# Интерполяция сплайном
t = np.linspace(0, 1, num_points)
x = np.array([point[0] for point in points])
y = np.array([point[1] for point in points])
z = np.array([point[2] for point in points])

t_interp = np.linspace(0, 1, 1000)
x_interp = make_interp_spline(t, x, k=3)(t_interp)
y_interp = make_interp_spline(t, y, k=3)(t_interp)
z_interp = make_interp_spline(t, z, k=3)(t_interp)

# Создание 3D массива из массива вершин
verts = np.column_stack((x_interp, y_interp, z_interp))
volume = np.zeros((10, 10, 10), dtype=bool)
volume[np.clip(np.round(verts[:, 0]), 0, 9).astype(np.int_), np.clip(np.round(verts[:, 1]), 0, 9).astype(np.int_), np.clip(np.round(verts[:, 2]), 0, 9).astype(np.int_)] = True

# Создание изосурфейса
faces = measure.marching_cubes(volume, level=0.5)[0]

# Сохранение изосурфейса в OBJ файл
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "output.obj")
save_obj_file(verts, faces, filename)
print(f"Model saved as {filename}")

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

Изогнутая линия с сохранением
Код:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
from scipy.interpolate import interp1d

# Генерация случайной функции с двумя переменными
def generate_function():
    functions = [lambda x, y: x + y, lambda x, y: x - y, lambda x, y: x * y, lambda x, y: x / y]
    return random.choice(functions)

# Генерация фрактала
def generate_fractal(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_fractal(x1, y1, z1, depth - 1)

# Генерация полостей и самоподобия
def generate_cavity(x, y, z, depth):
    if depth == 0:
        return np.array([x, y, z])
    else:
        x1 = x + np.random.uniform(-1, 1)
        y1 = y + np.random.uniform(-1, 1)
        z1 = z + np.random.uniform(-1, 1)
        return np.array([x1, y1, z1]) + generate_cavity(x1, y1, z1, depth - 1)

# Генерация трехмерного пространства
def generate_space():
    x = np.random.uniform(-10, 10)
    y = np.random.uniform(-10, 10)
    z = np.random.uniform(-10, 10)
    depth = np.random.randint(1, 10)
    return generate_fractal(x, y, z, depth)

# Визуализация пространства
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points = []
for i in range(100):
    x, y, z = generate_space()
    points.append([x, y, z])

# Интерполяция
t = np.linspace(0, 1, len(points))
x = np.array([point[0] for point in points])
y = np.array([point[1] for point in points])
z = np.array([point[2] for point in points])

x_interp = interp1d(t, x, kind='cubic')
y_interp = interp1d(t, y, kind='cubic')
z_interp = interp1d(t, z, kind='cubic')

t_interp = np.linspace(0, 1, 1000)
x_interp = x_interp(t_interp)
y_interp = y_interp(t_interp)
z_interp = z_interp(t_interp)

ax.plot(x_interp, y_interp, z_interp, 'b-')

ax.scatter(*zip(*points))

# Сохранение изогнутой линии изурфейсом
import os
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
filename = os.path.join(desktop_path, "curve.obj")
with open(filename, "w") as f:
    for i in range(len(x_interp)):
        f.write(f"v {x_interp[i]} {y_interp[i]} {z_interp[i]}\n")
    for i in range(len(x_interp) - 1):
        f.write(f"l {i+1} {i+2}\n")
print(f"Curve saved as {filename}")

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