Código de Python - Visor interactivo de modelos 3D

Filtrado por el tag: ssh
<<>>
Imágen de perfil
Val: 712
Bronce
Ha aumentado 1 puesto en Python (en relación al último mes)
Gráfica de Python

Visor interactivo de modelos 3Dgráfica de visualizaciones


Python

Actualizado el 5 de Junio del 2026 por Antonio (77 códigos) (Publicado el 7 de Febrero del 2025)
16.866 visualizaciones desde el 7 de Febrero del 2025
Este programa es un visor de modelos 3D en formato `.obj` que utiliza `OpenGL` y `pygame` para renderizar y manipular objetos 3D. Ofrece varias funciones de visualización como rotación, zoom, traslación, cambio entre vista en perspectiva y vista ortográfica, y otras acciones útiles para examinar el modelo cargado.

### Principales funciones del programa:

1. **Carga de modelo `.obj`:** El archivo `.obj` se especifica a través de un argumento y se carga mostrando los vértices, aristas y caras del modelo.
2. **Visualización en 3D:** Permite cambiar entre vista ortográfica y perspectiva.
3. **Rotación del modelo:** Utiliza cuaterniones para rotar el modelo sobre cualquier eje.
4. **Zoom y traslación:** Posibilidad de hacer zoom y mover el modelo en la pantalla.
5. **Información en pantalla:** Se puede mostrar/ocultar información como el nombre del modelo, escala, número de vértices, aristas y caras.

### Comandos principales:

- **Flechas del teclado:** Rotan el modelo en diferentes direcciones.
- **Tecla 'R':** Reinicia la rotación y escala del modelo.
- **Teclas 'M' y 'N':** Rotación en sentido horario y antihorario sobre el eje Z.
- **Tecla 'P':** Alterna entre vista en perspectiva y ortográfica.
- **Tecla 'X' y 'Z':** Zoom in y Zoom out, respectivamente.
- **Mouse:** Arrastrar con el clic izquierdo para mover la escena y usar la rueda del ratón para hacer zoom.
- **Tecla 'H':** Mostrar/ocultar la información en pantalla.
- **Tecla 'ESC':** Cierra el programa.
ov1
ov2
ship

Para cualquier duda u observación, usen la sección de comentarios.

Requerimientos

**Requerimientos de librerías:**

- **OpenGL**: Para renderizado gráfico en 3D.
- **PyGame**: Para manejo de ventana, eventos y controles de interfaz.
- **NumPy**: Para operaciones matemáticas y matrices (usado en cuaterniones y transformaciones).
- **Colorama**: Para manejo de colores en la consola.
- **GLU**: Utilizado para funciones adicionales de OpenGL como las proyecciones.

0.1

Actualizado el 21 de Marzo del 2025 (Publicado el 7 de Febrero del 2025)gráfica de visualizaciones de la versión: 0.1
5.159 visualizaciones desde el 7 de Febrero del 2025

0.2

Actualizado el 23 de Marzo del 2026 (Publicado el 7 de Abril del 2025)gráfica de visualizaciones de la versión: 0.2
9.984 visualizaciones desde el 7 de Abril del 2025

1.0

Actualizado el 5 de Junio del 2026 (Publicado el 23 de Marzo del 2026)gráfica de visualizaciones de la versión: 1.0
1.725 visualizaciones desde el 23 de Marzo del 2026
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

Esta versión del visor introduce mejoras importantes en robustez, flexibilidad y calidad del procesamiento del modelo. En primer lugar, se ha optimizado la función de carga de archivos `.obj`, añadiendo tipado explícito y soporte completo para distintos formatos de caras, así como para índices negativos, lo que aumenta la compatibilidad con modelos más complejos. Además, se ha mejorado el control de errores mostrando la línea exacta donde ocurre el problema, facilitando la depuración. También se ha refinado la validación de parámetros (como el ancho de línea, ahora más flexible) y se ha mejorado el centrado del modelo usando `numpy` de forma más eficiente. En el apartado visual, se han añadido mejoras como el antialiasing mediante multisampling, lo que proporciona un renderizado más suave, y pequeños ajustes en el control del zoom y la interacción. En conjunto, esta versión es más sólida, compatible y ofrece una experiencia de usuario más pulida.

lo1
lo3
lo2
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from pathlib import Path
import os
#import re
import math
import numpy as np
import argparse
from colorama import init, Fore, Style
import time
 
# load_obj4c5.py -load 10477_Satellite_v1_L3.obj -ec -scl 0.001 -zr 0.0001 -width 1500 -height 770 -lw 0.3
 
init()
 
rgb_colors = {'blue':[0.0,0.0,1.0,1.0],
              'gray':[0.2,0.2,0.2,1.0],
              'black':[0.0,0.0,0.0,1.0],
              'white':[1.0,1.0,1.0,1.0]}
 
rgb_t = {'blue':[0,0,255],
               'gray':[51,51,51],
               'black':[0,0,0],
               'white':[255,255,255]}
 
def check_width_value(width):
    val = int(width)
    if val < 800 or val > 1600:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"Width value must be less than 1601 and greater than 799."+Fore.RESET+Style.RESET_ALL)
    return val
 
def check_height_value(height):
    val = int(height)
    if val < 600 or val > 900:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"Height value must be less than 901 and greater than 599."+Fore.RESET+Style.RESET_ALL)
    return val
 
def check_source_ext(file):
    if os.path.exists(file):
        supported_formats = [".obj",".txt"]
        name, ex = os.path.splitext(file)
        if not ex in supported_formats:
            raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"Source file must be '.obj' or 'txt' ('{ex}' is not valid)."+Fore.RESET+Style.RESET_ALL)
    else:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"FILE NOT FOUND: file or path '{file}' not found."+Fore.RESET+Style.RESET_ALL)
    return file
 
def load_obj(filename,color,args):
 
    vertices: list[list[float]] = []
    faces: list[list[int]] = []
    edges: set[tuple[int, int]] = set()
    num_verts: int = 0
    num_triangles: int = 0
    num_edges: int = 0
    polygon_verts: int = 0
    load_error: bool = False
    line_counter: int = 0
    #message_error: str
 
    try:
        with open(filename, 'r') as file:
 
            for line in file:
                line = line.strip(); line_counter += 1
                if not line or line.startswith('#'):
                    continue
 
                parts = line.split()
 
                # VERTICES
                if parts[0] == 'v':
                    if len(parts) < 4:
                        continue
 
                    vertex = [
                        float(parts[1]),
                        float(parts[2]),
                        float(parts[3])
                    ]
                    vertices.append(vertex)
                    num_verts += 1
 
                # FACES
                elif parts[0] == 'f':
 
                    face_indices: list[int] = []
                    for part in parts[1:]:
 
                        # soporta v, v/vt, v//vn, v/vt/vn
                        vals = part.split('/')
                        if vals[0] == '':
                            continue
                        idx = int(vals[0])
 
                        # soporte índices negativos OBJ
                        if idx < 0:
                            idx = len(vertices) + idx
                        else:
                            idx -= 1
                        face_indices.append(idx)
 
                    if len(face_indices) < 3:
                        continue
 
                    polygon_verts = len(face_indices)
 
                    if color:
                        faces.append(face_indices)
 
                    num_triangles += 1
 
                    # generar edges
                    for i in range(len(face_indices)):
                        v1 = face_indices[i]
                        v2 = face_indices[(i + 1) % len(face_indices)]
                        edges.add(tuple(sorted((v1, v2))))
 
        num_edges = len(edges)
 
        # CENTERING
        if args.enable_centering and vertices:
            verts_np = np.array(vertices)
            min_v = np.min(verts_np, axis=0)
            max_v = np.max(verts_np, axis=0)
            center = (min_v + max_v) / 2.0
 
            vertices = [list(np.array(v) - center) for v in vertices]
 
    except Exception as e:
        print(f"FILE ERROR ON LINE {line_counter}: {str(e)}")
        load_error = True
 
    #print(f'NV: {num_verts}')
    #print(f'NF: {num_triangles}')
 
    return vertices, edges, num_verts, num_triangles, num_edges, faces, polygon_verts, load_error
 
 
_text_cache: dict = {}
 
def drawText(f, x, y, text, c, bgc):
    if text not in _text_cache:
        textSurface = f.render(text, True, c, bgc)
        textData = pygame.image.tostring(textSurface, "RGBA", True)
        _text_cache[text] = (textSurface.get_width(), textSurface.get_height(), textData)
    w, h, data = _text_cache[text]
    glWindowPos2d(x, y)
    glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, data)
 
def show_controls():
    print("\n--------------------- Controls ---------------------")
 
    print("\nKeyboard Controls (Movement):")
    print("  - Up Arrow: Move the scene forward (rotate upwards)")
    print("  - Down Arrow: Move the scene backward (rotate downwards)")
    print("  - Left Arrow: Move the scene left (rotate left)")
    print("  - Right Arrow: Move the scene right (rotate right)")
 
    print("\nTranslation Controls:")
    print("  - 'A' Key: Translate scene left")
    print("  - 'S' Key: Translate scene right")
    print("  - 'D' Key: Translate scene up")
    print("  - 'F' Key: Translate scene down")
 
    print("\nRotation Controls:")
    print("  - 'R' Key: Reset the scene rotation and scaling")
    print("  - 'M' Key: Rotate the scene counterclockwise around the Z-axis")
    print("  - 'N' Key: Rotate the scene clockwise around the Z-axis")
 
    print("\nView Controls:")
    print("  - 'T' Key: Set top (zenith) view")
    print("  - 'B' Key: Set bottom view")
    print("  - 'J' Key: Set right view")
    print("  - 'L' Key: Set left view")
    print("  - 'G' Key: Set front view")
    print("  - 'K' Key: Set back view")
 
    print("\nView Mode Toggle:")
    print("  - 'P' Key: Toggle between Orthographic and Perspective views")
 
    print("\nZoom Controls:")
    print("  - 'Z' Key: Zoom out (decrease scale)")
    print("  - 'X' Key: Zoom in (increase scale)")
    print("  - Mouse Wheel: Zoom in/out")
 
    print("\nTranslation & Rotation Controls (Drag):")
    print("  - Hold Left Mouse Button: Drag to move the scene")
    print("  - Hold Right Mouse Button: Drag to rotate the scene")
 
    print("\nMiscellaneous:")
    print("  - 'H' Key: Toggle the visibility of on-screen information (model name, scale, view mode)")
    print("  - ESC Key: Exit the program")
 
    print("\n----------------------------------------------------")
 
 
 
# Clase para manejar cuaterniones
class Quaternion:
    def __init__(self, w, x, y, z):
        self.w = w
        self.x = x
        self.y = y
        self.z = z
 
    def to_matrix(self):
        ww, xx, yy, zz = self.w * self.w, self.x * self.x, self.y * self.y, self.z * self.z
        wx, wy, wz = self.w * self.x, self.w * self.y, self.w * self.z
        xy, xz, yz = self.x * self.y, self.x * self.z, self.y * self.z
 
        return np.array([
            [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0],
            [2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0],
            [2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0],
            [0, 0, 0, 1]
        ], dtype=np.float32)
 
    def __mul__(self, other):
        w1, x1, y1, z1 = self.w, self.x, self.y, self.z
        w2, x2, y2, z2 = other.w, other.x, other.y, other.z
        return Quaternion(
            w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
            w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
            w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
            w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2
        ).normalize()
 
    def normalize(self):
        mag = math.sqrt(self.w**2 + self.x**2 + self.y**2 + self.z**2)
        if mag == 0:
            return Quaternion(1, 0, 0, 0)
        return Quaternion(self.w / mag, self.x / mag, self.y / mag, self.z / mag)
 
# Función para crear un cuaternión de rotación
def create_rotation_quaternion(angle, x, y, z):
    half_angle = math.radians(angle) / 2.0
    sin_half_angle = math.sin(half_angle)
    return Quaternion(math.cos(half_angle), x * sin_half_angle, y * sin_half_angle, z * sin_half_angle)
 
# Función para inicializar la proyección ortogonal
def setup_view_ortho(display):
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
 
    # Definir el rango de la proyección ortogonal
    aspect_ratio = display[0] / display[1]
    ortho_size = 10  # Tamaño del área visible en la proyección ortogonal 10
    #glOrtho(-ortho_size * aspect_ratio, ortho_size * aspect_ratio, -ortho_size, ortho_size, -50, 50)
    glOrtho(-ortho_size * 0.5 * aspect_ratio, ortho_size * 0.5 * aspect_ratio, -ortho_size * 0.5, ortho_size * 0.5, -50, 50)
 
 
    glMatrixMode(GL_MODELVIEW)
    #glLoadIdentity()
    #glTranslatef(0.0,0.0,-3.0)
 
def text_pos(h,p):
    inc_total = (h - 600)
    h_pos = p + inc_total
    return h_pos
 
def check_color(color):
    colors = ['blue','gray','black','white']
    if color not in colors:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+"Background color must be 'blue', 'white', 'gray' or 'black'."+Fore.RESET+Style.RESET_ALL)
    return color
 
def check_lw(w):
    width = float(w)
    if width < 0.1 or width > 10.0:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+"Line width must be in range 0.1 - 10.0."+Fore.RESET+Style.RESET_ALL)
    return width
 
def check_positive(v):
    ivalue = float(v)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError(Fore.RED+Style.BRIGHT+f"This value must be positive ('{v}' is not valid)."+Fore.RESET+Style.RESET_ALL)
    return ivalue
 
# Función para inicializar la proyección en perspectiva
def setup_view_perspective(display):
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(50, (display[0] / display[1]), 0.1, 80)#50.0)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslatef(0.0, 0.0, -10.0)
 
def fill_object(polygon_verts,faces,vertices):
    glEnable(GL_POLYGON_OFFSET_FILL)#############
    glPolygonOffset(1.0, 1.0)####################
 
    if polygon_verts == 3:
        glBegin(GL_TRIANGLES)##################
    elif polygon_verts == 4:
        glBegin(GL_QUADS)
    elif polygon_verts > 4:
        glBegin(GL_POLYGON)
    glColor3f(0.0, 0.5, 0.0)
    for face in faces:
        for vertex in face:
            glVertex3fv(vertices[vertex])
    glEnd()################################
    glDisable(GL_POLYGON_OFFSET_FILL)
 
 
def window(args):
    # Cargar el modelo OBJ
    try:
        path = args.load_object
        model_name = os.path.basename(path)
        vertices, edges, num_verts, num_triangles, num_edges, faces, polygon_verts, load_error = load_obj(path,args.fill_object,args)
 
        if not load_error:
            show_controls()
            pygame.init()
 
            text_bgR = rgb_t[args.bg_color][0]
            text_bgG = rgb_t[args.bg_color][1]
            text_bgB = rgb_t[args.bg_color][2]
 
            text_pos1 = text_pos(args.window_height,570)
            text_pos2 = text_pos(args.window_height,550)
            text_pos3 = text_pos(args.window_height,530)
            text_pos4 = text_pos(args.window_height,510)
            text_pos5 = text_pos(args.window_height,490)
            text_pos6 = text_pos(args.window_height,470)
 
            display = (args.window_width, args.window_height)
 
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)##
            pygame.display.gl_set_attribute(GL_MULTISAMPLESAMPLES, 6) ##########################
 
            pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
 
            glEnable(GL_MULTISAMPLE)
            glEnable(GL_LINE_SMOOTH)
            glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
            #glEnable(GL_BLEND)
            #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
 
            pygame.display.set_caption("Model Viewer")
            font = pygame.font.SysFont('arial', 15)
 
            glEnable(GL_DEPTH_TEST)#######################################################
 
            #glClearColor(0.0, 0.0, 1.0, 1.0)
 
            glClearColor(rgb_colors[args.bg_color][0],
                         rgb_colors[args.bg_color][1],
                         rgb_colors[args.bg_color][2],
                         rgb_colors[args.bg_color][3])
 
            ##
            scale = args.scale
            hide_data = False
            green_val = 255
            rotating = False
 
            # Crear la lista de display para el modelo
            model_list = glGenLists(1)
            glNewList(model_list, GL_COMPILE)
 
            glLineWidth(args.line_width)
 
            if args.fill_object:
                fill_object(polygon_verts,faces,vertices)
 
            if args.bg_color == 'white':
                glColor3f(0.0, 0.0, 0.0)  # Color negro
                green_val = 100
            else:
                glColor3f(1.0, 1.0, 1.0)  # Color blanco
 
            # Convertir el conjunto a una lista ordenada
            ordered_edges = sorted(list(edges))
 
            glBegin(GL_LINES)
            for edge in ordered_edges:
                for vertex in edge:
                    glVertex3fv(vertices[vertex])
            glEnd()
            glEndList()
 
            # Inicializar la vista en perspectiva por defecto
            is_ortho = False
            setup_view_perspective(display)
 
            # Inicializar el cuaternión de rotación (sin rotación inicial)
            quaternion = Quaternion(1, 0, 0, 0)
 
            dragging = False
            last_mouse_pos = (0, 0)
            translation = [0.0, 0.0]
 
            clock = pygame.time.Clock()
            last_time = time.perf_counter() ###
            running = True
            while running:
                now = time.perf_counter()
                #dt = clock.tick(60) / 1000.0   # Delta time en segundos, límite 60 FPS
                dt = min(now - last_time, 0.05)
                last_time = now
                rot_speed = args.rotation_speed * dt        # Grados por segundo (ajustable)
                trans_speed = args.translation_speed * dt   # Unidades por segundo (ajustable)
 
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        running = False
                    elif event.type == pygame.KEYDOWN:
                        '''if event.key == pygame.K_z:
                            scale += 0.05
                        elif event.key == pygame.K_x:
                            scale -= 0.05'''
                        if event.key == pygame.K_ESCAPE:
                            running = False
                        elif event.key == pygame.K_h:
                            hide_data = not hide_data
                        elif event.key == pygame.K_r:
                            quaternion = Quaternion(1, 0, 0, 0)
                            scale = args.scale
                            dragging = False
                            last_mouse_pos = (0, 0)
                            translation = [0.0, 0.0]
                            is_ortho = False
                            setup_view_perspective(display) # Restablece vista en perspectiva
                            args.solid = False
 
                        elif event.key == pygame.K_p:  # Cambiar entre ortogonal y perspectiva
                            is_ortho = not is_ortho
                            if is_ortho:
                                setup_view_ortho(display)
                            else:
                                setup_view_perspective(display)
 
                        elif event.key == pygame.K_t:  # Vista cenital (tecla 't')
                            # Aplicar rotación para la vista cenital
                            quaternion = Quaternion(1, 0, 0, 0)  # Restablece rotación
                            #translation = [0.0, 0.0]  # Restablece la traslación
                            #scale = 1  # Restablece el zoom
                            # Rotar la cámara 90 grados sobre el eje X para vista cenital
                            rotation = create_rotation_quaternion(-90, 1, 0, 0)
                            quaternion = quaternion * rotation
                        elif event.key == pygame.K_b:
                            quaternion = Quaternion(1, 0, 0, 0)  # Restablece rotación
                            rotation = create_rotation_quaternion(90, 1, 0, 0)
                            quaternion = quaternion * rotation
                        elif event.key == pygame.K_j:
                            quaternion = Quaternion(1, 0, 0, 0)  # Restablece rotación
                            rotation = create_rotation_quaternion(90, 0, 1, 0)
                            quaternion = quaternion * rotation
                        elif event.key == pygame.K_l:
                            quaternion = Quaternion(1, 0, 0, 0)  # Restablece rotación
                            rotation = create_rotation_quaternion(-90, 0, 1, 0)
                            quaternion = quaternion * rotation
                        elif event.key == pygame.K_g:
                            quaternion = Quaternion(1, 0, 0, 0)  # Restablece rotación
                            rotation = create_rotation_quaternion(0, 0, 1, 0)
                            quaternion = quaternion * rotation
                        elif event.key == pygame.K_k:
                            quaternion = Quaternion(1, 0, 0, 0)  # Restablece rotación
                            rotation = create_rotation_quaternion(180, 0, 1, 0)
                            quaternion = quaternion * rotation
 
 
                    elif event.type == pygame.MOUSEWHEEL:  # Rueda ratón
                        zoom_factor = 1.08 if event.y > 0 else (1/1.08 if event.y < 0 else 1.0)
                        scale *= zoom_factor
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        if event.button == 1:
                            dragging = True
                            last_mouse_pos = pygame.mouse.get_pos()
                        elif event.button == 3:  # botón derecho para rotación
                            rotating = True
                            last_mouse_pos = pygame.mouse.get_pos()
                    elif event.type == pygame.MOUSEBUTTONUP:
                        if event.button == 1:
                            dragging = False
                        elif event.button == 3:
                            rotating = False
                    elif event.type == pygame.MOUSEMOTION:
                        mouse_x, mouse_y = pygame.mouse.get_pos()
                        dx = mouse_x - last_mouse_pos[0]
                        dy = mouse_y - last_mouse_pos[1]
                        if dragging:
                            translation[0] += dx * 0.01
                            translation[1] -= dy * 0.01
                        if rotating:
                            # Sensibilidad proporcional al tiempo entre frames
                            mouse_rot_speed = 120.0 * dt
                            angle_x = dy * -mouse_rot_speed * 0.1
                            angle_y = dx * -mouse_rot_speed * 0.1
                            # Rotación alrededor del eje X e Y (en coordenadas del mundo)
                            qx = create_rotation_quaternion(angle_x, 1, 0, 0)
                            qy = create_rotation_quaternion(angle_y, 0, 1, 0)
                            quaternion = quaternion * qx * qy
 
                        last_mouse_pos = (mouse_x, mouse_y)
 
                key = pygame.key.get_pressed()
 
                # Rotación con cuaterniones (si se presionan las teclas de dirección)
                if key[pygame.K_UP]:
                    rotation = create_rotation_quaternion(rot_speed, 1, 0, 0)
                    quaternion = quaternion * rotation
                if key[pygame.K_DOWN]:
                    rotation = create_rotation_quaternion(-rot_speed, 1, 0, 0)
                    quaternion = quaternion * rotation
                if key[pygame.K_RIGHT]:
                    rotation = create_rotation_quaternion(-rot_speed, 0, 1, 0)
                    quaternion = quaternion * rotation
                if key[pygame.K_LEFT]:
                    rotation = create_rotation_quaternion(rot_speed, 0, 1, 0)
                    quaternion = quaternion * rotation
                if key[pygame.K_m]:
                    rotation = create_rotation_quaternion(rot_speed, 0, 0, 1)
                    quaternion = quaternion * rotation
                if key[pygame.K_n]:
                    rotation = create_rotation_quaternion(-rot_speed, 0, 0, 1)
                    quaternion = quaternion * rotation
                if key[pygame.K_z]:
                    scale -= args.zoom_rate * (dt / (1/60))
                if key[pygame.K_x]:
                    scale += args.zoom_rate * (dt / (1/60))
                # TRANSLATIONS
                if key[pygame.K_a]:
                    translation[0] -= trans_speed
                if key[pygame.K_s]:
                    translation[0] += trans_speed
                if key[pygame.K_d]:
                    translation[1] += trans_speed
                if key[pygame.K_f]:
                    translation[1] -= trans_speed
 
                # Limpiar la pantalla y cargar la nueva matriz de rotación
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
                glPushMatrix()
 
                glTranslatef(translation[0], translation[1], 0)
 
                # Convertir el cuaternión a matriz de rotación
                rotation_matrix = quaternion.to_matrix()
                glMultMatrixf(rotation_matrix)
 
                # Dibujar el modelo
                glScalef(scale, scale, scale)
                glCallList(model_list)
 
                glPopMatrix()
 
                if not hide_data:
                    drawText(font, 20, text_pos1, f'Model: {model_name}', (0, green_val, 0, 255), (text_bgR, text_bgG, text_bgB))
                    drawText(font, 20, text_pos2, f'Scale: {round(scale, 2)}', (0, green_val, 0, 255), (text_bgR, text_bgG, text_bgB))
                    view_mode = "Orthographic" if is_ortho else "Perspective"
                    drawText(font, 20, text_pos3, f'View: {view_mode}', (0, green_val, 0, 255),(text_bgR, text_bgG, text_bgB))
                    drawText(font, 20, text_pos4, f'Num Verts: {num_verts}',(0, green_val, 0, 255),(text_bgR, text_bgG, text_bgB))
                    drawText(font, 20, text_pos5, f'Num Faces: {num_triangles}',(0, green_val, 0, 255),(text_bgR, text_bgG, text_bgB))
                    drawText(font, 20, text_pos6, f'Num Edges: {num_edges}',(0, green_val, 0, 255),(text_bgR, text_bgG, text_bgB))
 
                pygame.display.flip()
                clock.tick(120)###########
 
            glDeleteLists(model_list, 1)
            pygame.quit()
        else:
            print(Fore.RED+Style.BRIGHT + "FILE ERROR" + Fore.RESET+Style.RESET_ALL)
            print("terminated")
 
    except Exception as e:
        print(Fore.RED+Style.BRIGHT + "UNEXPECTED ERROR: " + e.__str__() + Fore.RESET+Style.RESET_ALL)
 
def main():
    parser = argparse.ArgumentParser(prog="ModelVisor1.0", conflict_handler='resolve',
                                     description="Show obj models",allow_abbrev=False)
    parser.add_argument('-load','--load_object',required=True,type=check_source_ext,help="Obj model to load")
    parser.add_argument('-width','--window_width',type=check_width_value,default=800,help="Window width (default is 800)")
    parser.add_argument('-height','--window_height',type=check_height_value,default=600,help="Window height (default is 600)")
    parser.add_argument('-bg','--bg_color',type=check_color,default='black',help="Background color (default is 'black')")
    parser.add_argument('-lw','--line_width',type=check_lw,default=1.0,help="Line width (default is 1.0)")
    parser.add_argument('-fill','--fill_object',action='store_true',help="Add solid color to model")
    parser.add_argument('-scl','--scale',type=check_positive,default=1.0,help="Object scale (default is 1.0)")
    parser.add_argument('-zr','--zoom_rate',type=check_positive,default=0.05,help="Zoom Rate (default is 0.05)")
    parser.add_argument('-ec','--enable_centering',action='store_true',help="Enable automatic centering")
    parser.add_argument('-rspd','--rotation_speed',type=check_positive,default=90.0,help="Rotation speed (default is 90.0)")
    parser.add_argument('-tspd','--translation_speed',type=check_positive,default=2.0,help="Translation speed (default is 2.0)")
 
    args = parser.parse_args()
    window(args)
 
if __name__ =="__main__":
    main()



Comentarios sobre la versión: 1.0 (0)


No hay comentarios
 

Comentar la versión: 1.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s7560