¿Es posible utilizar la biblioteca JCSG con Processing?

Villares:

El procesamiento es una plataforma de codificación creativa - lenguaje, IDE y del ecosistema - mantenido por la comunidad de procesamiento con el respaldo de la Fundación procesamiento https://processing.org . El procesamiento del modo de Java por lo general puede beneficiarse de código en las bibliotecas de Java.

JCSG es una implementación de Java de CSG basado BSP (constructiva Solid Geometry) https://github.com/miho/JCSG .

George Profenza:

Hay unos aros a través de saltos procedente de Procesamiento solo, pero eso sí, se puede utilizar cualquier biblioteca de Java en el procesamiento. (Basta con arrastrar el .jar de la biblioteca en la parte superior del dibujo guardado)

En primer lugar tendrá que compilar el JCSG librería .jar junto con el VVecMath librería .jar para ejecutar el código de ejemplo.

Para hacer esto usted necesitará Gradle . Se puede instalar desde cero o utilizar una instalación existente de su sistema si usted ha utilizado el SDK de Android / Android estudio / IntelliJ / etc.

A medida que el readme menciona, en OSX / Linux / etc. de cada ejecución carpeta de la biblioteca:

bash gradlew assemble

En ejecución de Windows:

gradlew assemble

En mi caso he usado el Gradle instalación que viene con Android Studio que tuve en mi mac:

bash /Applications/IDEsAndEditors/Android\ Studio.app/Contents/plugins/android/lib/templates/gradle/wrapper/gradlew assemble

Una vez que tenga los archivos .jar compilados que simplemente les puede caer en un dibujo de procesamiento salvado. Esto creará una codecarpeta. En esta etapa se pueden utilizar las bibliotecas en ese dibujo.

(Consejo: Ir a la producción> Preferencias y permitir la finalización de código con Ctrl + Espacio para hacer más fácil de ver el método y las propiedades disponibles (IDEs como Eclipse / IntelliJ / NetBeans / etc hacen que, por defecto).)

He hecho una prueba rápida, sin embargo, el archivo OBJ JCSG ahorra no se puede analizar mediante una función de PShape cargador de OBJ de procesamiento.

import java.nio.file.Paths;

PShape csgResult;

void setup(){
  size(900,900,P3D);
  // we use cube and sphere as base geometries
  CSG cube = new Cube(2).toCSG();
  CSG sphere = new Sphere(1.25).toCSG();

  // perform union, difference and intersection
  CSG cubePlusSphere = cube.union(sphere);
  CSG cubeMinusSphere = cube.difference(sphere);
  CSG cubeIntersectSphere = cube.intersect(sphere);

  // translate geometries to prevent overlapping 
  CSG union = cube.
          union(sphere.transformed(Transform.unity().translateX(3))).
          union(cubePlusSphere.transformed(Transform.unity().translateX(6))).
          union(cubeMinusSphere.transformed(Transform.unity().translateX(9))).
          union(cubeIntersectSphere.transformed(Transform.unity().translateX(12)));

  // save union as stl
  try {
      FileUtil.write(
              Paths.get(sketchPath("sample.obj")),
              union.toObjString()
      );
  } catch (IOException ex) {
      ex.printStackTrace();
  }

  //load shape into Processing
  csgResult = loadShape(sketchPath("sample.obj"));

}

void draw(){
  background(0);
  translate(width * 0.5, height * 0.5,0);
  scale(sin(frameCount * 0.1) * 100);
  if(csgResult != null){
    shape(csgResult);
  }
}

Hice la prueba y los vértices están ahí, las caras faltan través de:

vértices de demostración JCSG

Siente tratar de probar el formato STL y una biblioteca de procesamiento diferente a cargar, acceder de otro modo los vértices y dibujar en Procesamiento de tomar directamente en unidades de cuenta / escalas son diferentes entre JSCG y Procesamiento:

import java.nio.file.Paths;

CSG union;

void setup(){
  size(900,900,P3D);
  stroke(255);
  //strokeWeight(3);
  // we use cube and sphere as base geometries
  CSG cube = new Cube(2).toCSG();
  CSG sphere = new Sphere(1.25).toCSG();

  // perform union, difference and intersection
  CSG cubePlusSphere = cube.union(sphere);
  CSG cubeMinusSphere = cube.difference(sphere);
  CSG cubeIntersectSphere = cube.intersect(sphere);

  // translate geometries to prevent overlapping 
  union = cube.
          union(sphere.transformed(Transform.unity().translateX(3))).
          union(cubePlusSphere.transformed(Transform.unity().translateX(6))).
          union(cubeMinusSphere.transformed(Transform.unity().translateX(9))).
          union(cubeIntersectSphere.transformed(Transform.unity().translateX(12)));

}

void drawCSG(CSG mesh,float scale){
  beginShape(POINTS);
  for(Polygon p : mesh.getPolygons()){
    for(Vertex v : p.vertices){
      vertex((float)v.pos.getX() * scale,(float)v.pos.getY() * scale,(float)v.pos.getZ() * scale);
    }
  }
  endShape();
}

void draw(){
  background(0);
  translate(width * 0.5, height * 0.5,0);
  rotateY(map(mouseX,0,width,-PI,PI));
  rotateX(map(mouseY,0,height,PI,-PI));

  drawCSG(union,sin(frameCount * 0.01) * 100);
}

JSCG vértice traversal

Puede descargar el dibujo anterior (con bibliotecas precompilados) aquí (y la documentación generada JCSG aquí ). Asegúrese de ir a través de código de documentación / fuente de las bibliotecas para un uso más avanzado.

Actualización: Por eficiencia se puede hacer uso de createShape()la creación de un grupo de PShapeobjetos en vez de configuración, a continuación, simplemente hacer que en draw()(a diferencia de mi ejemplo anterior, que atraviesa todos los polígonos y vértices una y otra vez):

// the PShape reference which will contain the converted 
PShape csgResult;

void setup(){
  size(900,900,P3D);
  noStroke();
  // JCSG sample code:
    // we use cube and sphere as base geometries
    CSG cube = new Cube(2).toCSG();
    CSG sphere = new Sphere(1.25).toCSG();

    // perform union, difference and intersection
    CSG cubePlusSphere = cube.union(sphere);
    CSG cubeMinusSphere = cube.difference(sphere);
    CSG cubeIntersectSphere = cube.intersect(sphere);

    // translate geometries to prevent overlapping 
    CSG union = cube.
            union(sphere.transformed(Transform.unity().translateX(3))).
            union(cubePlusSphere.transformed(Transform.unity().translateX(6))).
            union(cubeMinusSphere.transformed(Transform.unity().translateX(9))).
            union(cubeIntersectSphere.transformed(Transform.unity().translateX(12)));

    // translate merged geometry back by half the total translation to pivot around centre
    union = union.transformed(Transform.unity().translateX(-6));

  // Convert CSG to PShape -> Note: CSG units are small so we scale them up so the shapes are visible in Processing
  csgResult = CSGToPShape(union,45);
}
// re-usable function to convert a CSG mesh to a Processing PShape
PShape CSGToPShape(CSG mesh,float scale){
  // allocate a PShape group
  PShape csgResult = createShape(GROUP);
  // for each CSG polygon (Note: these can have 3,4 or more vertices)
  for(Polygon p : mesh.getPolygons()){
    // make a child PShape
    PShape polyShape = createShape();
    // begin setting vertices to it
    polyShape.beginShape();
    // for each vertex in the polygon
    for(Vertex v : p.vertices){
      // add each (scaled) polygon vertex 
      polyShape.vertex((float)v.pos.getX() * scale,(float)v.pos.getY() * scale,(float)v.pos.getZ() * scale);
    }
    // finish this polygon
    polyShape.endShape();
    //append the child PShape to the parent
    csgResult.addChild(polyShape);
  }
  return csgResult;
}

void draw(){
  background(0);
  lights();
  translate(width * 0.5, height * 0.5,0);
  rotateY(map(mouseX,0,width,-PI,PI));
  rotateX(map(mouseY,0,height,PI,-PI));
  shape(csgResult);
}

JCSG representa como PShape en el Procesamiento

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=232001&siteId=1
Recomendado
Clasificación