AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79569069
Accepted
issamo
issamo
Asked: 2025-04-11 22:21:18 +0800 CST2025-04-11 22:21:18 +0800 CST 2025-04-11 22:21:18 +0800 CST

Projetar rostos corporais em esboços

  • 772

Prezados, comecei a desenvolver um código VBA que deve: 1- pedir para o usuário selecionar uma face de qualquer corpo no CATPART atual. 2- uma vez feito isso, o VBA deve extrair essa superfície em um conjunto geométrico e criar 3 pontos no contorno dessa superfície. 3- com base nesses pontos, criar um plano e, por fim, projetar o contorno da superfície dentro de um esboço.

abaixo do meu código, não funciona. Ele exibe incompatibilidade de tipo sem especificar onde.

A imagem descreve mais ou menos o que eu quero. NB: a parte do gato pode conter formas complexas, por isso a superfície extraída precisa estar em tangência

insira a descrição da imagem aqui

Sub ExtractSurfaceAndCreateSketch()
    Dim partDocument As Object
    Dim part1 As Object
    Dim selection1 As Object
    Dim face1 As Object
    Dim hybridShapeFactory As Object
    Dim hybridBody As Object
    Dim reference1 As Object
    Dim hybridShapeExtract As Object
    Dim hybridShapePoint As Object
    Dim sketch As Object
    Dim sketches As Object

    ' Initialize CATIA Document and Part
    Set partDocument = CATIA.activeDocument
    Set part1 = partDocument.part
    Set selection1 = partDocument.selection
    
    ' Clear previous selections
    selection1.Clear
    
    ' Prompt user to select a face
    MsgBox "Please select a face from a body."
    
    ' Select the face
    On Error Resume Next
    Dim result As Variant
    result = selection1.SelectElement2("Face", "Select a face", False)
    If Err.Number <> 0 Then
        MsgBox "Error during selection: " & Err.Description
        Err.Clear
        Exit Sub
    End If
    On Error GoTo 0
    
    ' Check the type of the result and compare accordingly
    If VarType(result) = vbString Then
        If result <> "Normal" Then
            MsgBox "No valid face selected. Exiting."
            Exit Sub
        End If
    Else
        MsgBox "Unexpected return type from SelectElement2. Exiting."
        Exit Sub
    End If
    
    ' Get the selected face
    If selection1.Count = 0 Then
        MsgBox "No face selected. Exiting."
        Exit Sub
    End If
    Set face1 = selection1.Item(1).Value
    
    ' Create a reference from the face
    On Error GoTo ErrorHandler
    Set reference1 = part1.CreateReferenceFromBRepName(face1.brepName)
    
    ' Create the Hybrid Shape Factory and Hybrid Body
    Set hybridShapeFactory = part1.hybridShapeFactory
    Set hybridBody = part1.hybridBodies.Add
    
    ' Extract the surface from the face
    Set hybridShapeExtract = hybridShapeFactory.AddNewExtract(reference1)
    hybridShapeExtract.Name = "ExtractedSurface"
    hybridBody.AppendHybridShape hybridShapeExtract
    
    ' Create points on the outline of the extracted surface
    Dim posX As Variant, posY As Variant
    Dim pointArray(2) As Object
    
    ' Define UV coordinates for point placement
    posX = Array(0.1, 0.5, 0.9) ' X coordinates
    posY = Array(0.1, 0.5, 0.9) ' Y coordinates
    
    Dim i As Integer
    For i = 0 To 2
        ' Create a point on the extracted surface using UV coordinates
        Set hybridShapePoint = hybridShapeFactory.AddNewPointOnSurface(reference1, posX(i), posY(i))
        hybridBody.AppendHybridShape hybridShapePoint
        Set pointArray(i) = hybridShapePoint ' Store the points for plane creation
    Next i
    
    ' Create a plane based on the three points
    Dim hybridShapePlane As Object
    Set hybridShapePlane = hybridShapeFactory.AddNewPlaneThroughPoints(pointArray(0), pointArray(1), pointArray(2))
    hybridBody.AppendHybridShape hybridShapePlane
    
    ' Create a sketch on the new plane
    Set sketches = part1.sketches
    Set sketch = sketches.Add(hybridShapePlane)
    
    ' Extract the projected profile of the extracted surface
    Dim projectedProfile As Object
    Set projectedProfile = hybridShapeFactory.AddNewProjection(hybridShapeExtract, hybridShapePlane)
    projectedProfile.Name = "ProjectedProfile"
    hybridBody.AppendHybridShape projectedProfile
    
    ' Set the sketch as editable
    Dim sketcherEditor As Object
    Set sketcherEditor = sketch.OpenEdition()
    
    ' Create lines based on the projected profile
    Dim iCurve As Integer
    Dim profile As Object

    ' Loop through all segments of the projected profile
    For iCurve = 1 To projectedProfile.Profiles.Count
        ' Get the profile curve
        Set profile = projectedProfile.Profiles.Item(iCurve)

        ' If it's a line, extract its start and end points
        If profile.Type = "Line" Then
            Dim startPoint As Object
            Dim endPoint As Object
            
            ' Retrieve the start and end points
            Set startPoint = profile.GetStartPoint()
            Set endPoint = profile.GetEndPoint()
            
            ' Create a line in the sketch using the Factory2D
            Dim factory2D As Object
            Set factory2D = sketcherEditor.factory2D
            
            ' Create the line in the sketch
            On Error Resume Next
            factory2D.CreateLine startPoint.X, startPoint.Y, endPoint.X, endPoint.Y
            If Err.Number <> 0 Then
                MsgBox "Error creating line: " & Err.Description
                Err.Clear
            End If
            On Error GoTo 0
        End If
    Next iCurve
    
    ' Close the sketch edition
    sketch.CloseEdition
    
    ' Update the part
    part1.Update
    
    MsgBox "Surface extracted, points created, plane established, and sketch projected successfully!"

    Exit Sub

ErrorHandler:
    MsgBox "Error: " & Err.Description
    Exit Sub
End Sub
vba
  • 1 1 respostas
  • 51 Views

1 respostas

  • Voted
  1. Best Answer
    Shrotter
    2025-04-12T13:59:02+08:002025-04-12T13:59:02+08:00

    Você pode projetar o rosto/extrato diretamente no esboço, dispensando projeções e a criação de linhas adicionais.
    Aqui está um exemplo mais curto. Usei um dos exemplos OriginElementpara o esboço.

    Sub CATMain()
        Dim partDocument As PartDocument
        Dim part1 As Part
        Dim selection1 As Selection
        Dim hybridShapeFactory As Object
        Dim hybridBody As hybridBody 
        Dim reference1 As Reference
        Dim hybridShapeExtract As hybridShapeExtrac
        Dim sketch As Sketch
        Dim sketches As Sketches
        Dim InputObjectType(0)
        Dim Result as String
    
        ' Initialize CATIA Document and Part
        Set partDocument = CATIA.activeDocument
        Set part1 = partDocument.part
        Set selection1 = partDocument.selection
        
        ' Clear previous selections
        selection1.Clear
    
        ' Select the face
        InputObjectType(0)="PlanarFace" 
        result = selection1.SelectElement2(InputObjectType, "Select a face", False)
        
        ' Check the type of the result and compare accordingly
        If result <> "Normal"  Then
            MsgBox "No valid face selected. Exiting."
            Exit Sub
        End If
        
        ' Get the selected face
        If selection1.Count = 0 Then
            MsgBox "No face selected. Exiting."
            Exit Sub
        End If
    
        ' Create a reference from the face
        Set reference1 = selection1.Item(1).Reference
        
        ' Create the Hybrid Shape Factory and Hybrid Body
        Set hybridShapeFactory = part1.hybridShapeFactory
        Set hybridBody = part1.hybridBodies.Add
        
        ' Extract the surface from the face
        Set hybridShapeExtract = hybridShapeFactory.AddNewExtract(reference1)
        hybridShapeExtract.Name = "ExtractedSurface"
        hybridBody.AppendHybridShape hybridShapeExtract
        part1.Update
        
        ' Create a sketch on on YZ plane
        Set oRefPlane = part1.OriginElements.PlaneYZ
        Set sketches = hybridBody.HybridSketches
        Set sketch = sketches.Add(oRefPlane)
    
        ' Open the sketch
        Dim factory2D As Object
        Set factory2D = sketch.OpenEdition()
    
        'project extract in sketch
        Dim oProjection
        Set oProjection = factory2D.CreateProjection(hybridShapeExtract)
        
        ' Close the sketch edition
        sketch.CloseEdition
        
        ' Update the part
        part1.Update
        
        MsgBox "Surface extracted and sketch projected successfully!"
    
    End Sub
    
    • 0

relate perguntas

  • Pesquise e formate texto entre parênteses

  • Atribuindo formas a um grupo no PowerPoint usando VBA

  • Word VBA, mova o cursor para o início do próximo número em uma lista numerada

  • Execute uma regra do Outlook para cada conta usando macro vba

  • Extrair arquivos de um objeto OLE do Access

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve