Sketch spline through points creation and relative functions API Sample

Description

Create a sketch spline with points and use some operations for spline tangent handle & curvature handle.

Code Samples

import adsk.core, adsk.fusion, traceback

def run(context):
    ui = None
    try: 
        app = adsk.core.Application.get()
        ui = app.userInterface

        doc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
        design = app.activeProduct

        # Get the root component of the active design.
        rootComp = design.rootComponent

        # Create a new sketch on the xy plane.
        sketch = rootComp.sketches.add(rootComp.xYConstructionPlane)

        # Create an object collection for the points.
        points = adsk.core.ObjectCollection.create()

        # Define the points the spline with fit through.
        points.add(adsk.core.Point3D.create(0, 0, 0))
        points.add(adsk.core.Point3D.create(5, 1, 0))
        points.add(adsk.core.Point3D.create(6, 4, 3))
        points.add(adsk.core.Point3D.create(7, 6, 6))
        points.add(adsk.core.Point3D.create(2, 3, 0))
        points.add(adsk.core.Point3D.create(0, 1, 0))

        # Create the spline.
        spline = sketch.sketchCurves.sketchFittedSplines.add(points)

        # Get spline fit points
        fitPoints = spline.fitPoints
        
        # Get the second fit point
        fitPoint = fitPoints.item(1)
        
        # If there is no the relative tangent handle, activate the tangent handle
        line = spline.getTangentHandle(fitPoint)
        if line is None:
             line = spline.activateTangentHandle(fitPoint)
                
        # Get the tangent handle           
        gottenLine = spline.getTangentHandle(fitPoint)
        
        # Delete the tangent handle
        gottenLine.deleteMe()

        # Activate the curvature handle
        # If the curvature handle activated. the relative tangentHandle is activated automatically
        activatedArc= spline.activateCurvatureHandle(fitPoint)
        
        # Get curvature handle and tangent handle
        gottenArc= spline.getCurvatureHandle(fitPoint)
        gottenLine = spline.getTangentHandle(fitPoint)
        
        # Delete curvature handle
        gottenArc.deleteMe();

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
#include <Core/Application/Application.h>
#include <Core/Application/Documents.h>
#include <Core/Application/Document.h>
#include <Core/Application/Product.h>
#include <Core/Application/ObjectCollection.h>
#include <Core/UserInterface/UserInterface.h>
#include <Core/Geometry/Point3D.h>
#include <Fusion/Fusion/Design.h>
#include <Fusion/Components/Component.h>
#include <Fusion/Sketch/Sketch.h>
#include <Fusion/Sketch/Sketches.h>
#include <Fusion/Sketch/SketchCurves.h>
#include <Fusion/Sketch/SketchFittedSplines.h>
#include <Fusion/Sketch/SketchFittedSpline.h>
#include <Fusion/Sketch/SketchPointList.h>
#include <Fusion/Sketch/SketchPoint.h>
#include <Fusion/Sketch/SketchLine.h>
#include <Fusion/Sketch/SketchArc.h>
#include <Fusion/Construction/ConstructionPlane.h>

using namespace adsk::core;
using namespace adsk::fusion;

Ptr<UserInterface> ui;

extern "C" XI_EXPORT bool run(const char* context)
{
    Ptr<Application> app = Application::get();
    if (!app)
        return false;

    ui = app->userInterface();
    if (!ui)
        return false;

    Ptr<Documents> documents = app->documents();
    if (!documents)
        return false;

    Ptr<Document> doc = documents->add(DocumentTypes::FusionDesignDocumentType);
    if (!doc)
        return false;

    Ptr<Product> product = app->activeProduct();
    if (!product)
        return false;

    Ptr<Design> design = product;
    if (!design)
        return false;

    // Get the root component.
    Ptr<Component> rootComp = design->rootComponent();
    if (!rootComp)
        return false;

    // Create a new sketch on the xy plane.
    Ptr<Sketches> sketches = rootComp->sketches();
    if (!sketches)
        return false;
    Ptr<ConstructionPlane> xyPlane = rootComp->xYConstructionPlane();
    if (!xyPlane)
        return false;
    Ptr<Sketch> sketch = sketches->add(xyPlane);
    if (!sketch)
        return false;

    // Create an object collection for the points.
    Ptr<ObjectCollection> points = ObjectCollection::create();
    if (!points)
        return false;

    // Define the points the spline with fit through.
    points->add(Point3D::create(0, 0, 0));
    points->add(Point3D::create(5, 1, 0));
    points->add(Point3D::create(6, 4, 3));
    points->add(Point3D::create(7, 6, 6));
    points->add(Point3D::create(2, 3, 0));
    points->add(Point3D::create(0, 1, 0));

    // Create the spline.
    Ptr<SketchCurves> sketchCurves = sketch->sketchCurves();
    if (!sketchCurves)
        return false;
    Ptr<SketchFittedSplines> splines = sketchCurves->sketchFittedSplines();
    if (!splines)
        return false;

    Ptr<SketchFittedSpline> spline = splines->add(points);
    if (!spline)
        return false;

    // Get spline fit points
    Ptr<SketchPointList> fitPoints = spline->fitPoints();
    if (!fitPoints)
        return false;

    // Get the second fit point
    Ptr<SketchPoint> fitPoint = fitPoints->item(1);
    if (!fitPoint)
        return false;

    // If there is no the relative tangent handle, activate the tangent handle
    Ptr<SketchLine> line = spline->getTangentHandle(fitPoint);
    if (line)
        return false;
    else
    {
        line = spline->activateTangentHandle(fitPoint);
        if (!line)
            return false;
    }

    // Get the tangent handle
    Ptr<SketchLine> gottenLine = spline->getTangentHandle(fitPoint);
    if (!gottenLine)
        return false;

    // Delete the tangent handle
    bool isSuccess = gottenLine->deleteMe();
    if (!isSuccess)
        return false;

    // Activate the curvature handle
    // If the curvature handle activated. the relative tangentHandle is activated automatically
    Ptr<SketchArc> activatedArc = spline->activateCurvatureHandle(fitPoint);
    if (!activatedArc)
        return false;

    // Get curvature handle and tangent handle
    Ptr<SketchArc> gottenArc = spline->getCurvatureHandle(fitPoint);
    if (!gottenArc)
        return false;

    gottenLine = spline->getTangentHandle(fitPoint);
    if (!gottenLine)
        return false;

    // Delete curvature handle
    bool isDeleted = gottenArc->deleteMe();
    if (!isDeleted)
        return false;


    return true;
}
/**
 * Sketch spline through points creation and relative functions API Sample
 * Create a sketch spline with points and use some operations for spline tangent handle & curvature handle.
 */

import { adsk } from '@adsk/fusion';

//Params
// {
//     "useCurrentDocument": false,
//     "saveAsNewDocument": false,
//     "message": "",
//     "hubId": "wip1fqaautodesk4298",
//     "fileURN": "urn:adsk.wipqa:dm.lineage:WlSCDh7RQN6zD2btrrO4SA"
// }

function run() {

// Read the parameters passed with the script
  const scriptParameters = JSON.parse(adsk.parameters);
  if (!scriptParameters) throw Error("Invalid parameters provided.");

  // Get the Fusion API's application object
  const app = adsk.core.Application.get();
  if (!app) throw Error("No adsk.core.Application.");

  // const doc: adsk.core.Document = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType);
  // Create a new empty document
  const doc = getDocument(
    app,
    scriptParameters.useCurrentDocument,
    scriptParameters.hubId,
    scriptParameters.fileURN,
  );
  if (!doc) throw Error("Invalid document.");

 // Ensure we are in the Design environment.
  const design = app.activeProduct as adsk.fusion.Design;

  //Get the root component of the active design.
  const rootComp = design.rootComponent

  // Create a new sketch on the xy plane.
  const sketch = rootComp.sketches.add(rootComp.xYConstructionPlane)
  // Create an object collection for the points.
  const points = adsk.core.ObjectCollection.create()

  // Define the points the spline with fit through.
  points.add(adsk.core.Point3D.create(0, 0, 0))
  points.add(adsk.core.Point3D.create(5, 1, 0))
  points.add(adsk.core.Point3D.create(6, 4, 3))
  points.add(adsk.core.Point3D.create(7, 6, 6))
  points.add(adsk.core.Point3D.create(2, 3, 0))
  points.add(adsk.core.Point3D.create(0, 1, 0))

  // Create the spline.
  const spline = sketch.sketchCurves.sketchFittedSplines.add(points)

  // Get spline fit points
  const fitPoints = spline.fitPoints

  // Get the second fit point
  const fitPoint = fitPoints.item(1)

  // If there is no the relative tangent handle, activate the tangent handle
  let line = spline.getTangentHandle(fitPoint)
  if (line == null){
      line = spline.activateTangentHandle(fitPoint)
  }

  // Get the tangent handle
  const gottenLineFirst = spline.getTangentHandle(fitPoint)

  // Delete the tangent handle
  gottenLineFirst.deleteMe()

  // Activate the curvature handle
  // If the curvature handle activated. the relative tangentHandle is activated automatically
  const activatedArc = spline.activateCurvatureHandle(fitPoint)

  // Get curvature handle and tangent handle
  const gottenArc = spline.getCurvatureHandle(fitPoint)
  const gottenLineSecond = spline.getTangentHandle(fitPoint)

  // Delete curvature handle
  gottenArc.deleteMe()

  saveDocument(
      doc,
      scriptParameters.saveAsNewDocument,
      scriptParameters.message,
      doc.dataFile.parentFolder,
    );

    while (app.hasActiveJobs) {
    wait(2000);
  }
}
function wait(ms: number) {
  const start = new Date().getTime();
  while (new Date().getTime() - start < ms) adsk.doEvents();
}

function getDocument(
  app: adsk.core.Application,
  useCurrentDocument: boolean,
  hubId: string,
  fileURN: string,
): adsk.core.Document {
  if (useCurrentDocument === true) {
    adsk.log(`Using currently open document: ${app.activeDocument.name}.`);
    return app.activeDocument;
  }

  if (hubId) {
    // Possible hubId formats: base64 encoded string, or business:<id>,
    // or personal:<id> (deprecated)
    const hub =
      app.data.dataHubs.itemById(hubId) ||
      app.data.dataHubs.itemById(`a.${adsk.btoa(`business:${hubId}`, true)}`) ||
      app.data.dataHubs.itemById(`a.${adsk.btoa(`personal:${hubId}`, true)}`);
    if (!hub) throw Error(`Hub with id ${hubId} not found.`);
    adsk.log(`Setting hub: ${hub.name}.`);
    app.data.activeHub = hub;
  }

  const file = app.data.findFileById(fileURN);
  if (!file) throw Error(`File not found ${fileURN}.`);
  adsk.log(`Opening ${file.name}`);
  const document = app.documents.open(file, true);
  if (!document) throw Error(`Cannot open file ${file.name}.`);
  return document;
}

function saveDocument(
  doc: adsk.core.Document,
  saveAsNewDocument: boolean,
  message: string,
  destinationFolder: adsk.core.DataFolder,
): boolean {
  if (saveAsNewDocument) {
    adsk.log("Saving as new document.");
    try {
      destinationFolder.parentProject;
    } catch (e) {
      adsk.log(
        "Destination folder is not in a project, setting folder to Fusion Automation Service project.",
      );
      destinationFolder = defaultFolder(
        doc.parent,
        "Fusion Automation Service",
      );
    }
    if (
      doc.saveAs(doc.name + " Additive Ready", destinationFolder, message, "")
    ) {
      adsk.log("Document saved successfully.");
      return true;
    } else {
      adsk.log("Document failed to save.");
      return false;
    }
  }

  if (!doc.isModified) {
    adsk.log("Document not modified, not saving.");
    return true;
  }

  adsk.log(`Saving with message: "${message}".`);
  if (doc.save(message)) {
    adsk.log("Document saved successfully.");
    return true;
  } else {
    adsk.log("Document failed to save.");
    return false;
  }
}

function defaultFolder(app: adsk.core.Application, defaultProjectName: string) {
  const projects = app.data.activeHub.dataProjects;
  if (!projects) throw Error("Unable to get active hub's projects.");
  for (let i = 0; i < projects.count; ++i) {
    const project = projects.item(i)!;
    if (project.name === defaultProjectName) {
      return project.rootFolder;
    }
  }
  adsk.log(`Creating new project: ${defaultProjectName}`);
  const project = projects.add(defaultProjectName);
  if (!project) throw Error("Unable to create new project.");
  return project.rootFolder;
}

run();