Delaunay triangulation using opentk - opentk

I am using openTK library to load xyz file in order to transform it to 3d meshes. When i use the tools of triangulation of this library i have an object where the triangles not connected..
i have used the code below:
string fileNameLong = "bunny.xyz";
vertices = IOUtils.ReadXYZFile_ToVertices(fileNameLong, false);
Vertices.SetColorOfListTo(vertices, new Vector3d(1, 0, 0));
Model3D myModel = new Model3D("bunny");
myModel.VertexList = vertices;
myModel.CalculateNormals_Triangulation();
this.CreateLinesForNormals(myModel);
ShowModel_WithLines(myModel, true);
Model3D.Save_OBJ(myModel, path, "bunny_Triangulated.obj");

Related

How can I improve the performance of converting an SVG to PDF using Apache Batik?

I am using Apache Batik version 1.9 to convert from SVG to PDF. I am getting the desired result, but it is consuming a lot of time to generate the PDF output. Below is the code. I am not sure how to improve its performance. Is there a way I can achieve better performance?
// svgBytes is the input
ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
Transcoder transcoder = new PDFTranscoder();
InputStream svgInputStream = new ByteArrayInputStream(svgBytes);
// Parse SVG
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(XMLResourceDescriptor.getXMLParserClassName());
Document svgDoc = f.createDocument(null, svgInputStream);
SVGDocument svgDocument = (SVGDocument) svgDoc;
SVGElement root = svgDocument.getRootElement();
Float svgWidth = Float.parseFloat(null == root.getAttribute("width") ? SVG_DEFAULT_WIDTH : root.getAttribute("width"));
Float svgHeight = Float.parseFloat(null == root.getAttribute("height") ? SVG_DEFAULT_HEIGHT : root.getAttribute("height"));
// Convert SVG to PDF using batik
float scalePercentage = 1f;
transcoder.addTranscodingHint(PDFTranscoder.KEY_WIDTH, new Float(svgWidth * scalePercentage));
transcoder.addTranscodingHint(PDFTranscoder.KEY_HEIGHT, new Float(svgHeight * scalePercentage));
transcoder.transcode(new TranscoderInput(new ByteArrayInputStream(svgBytes)), new TranscoderOutput(pdfOutputStream));
pdfOutputStream.flush();
pdfOutputStream.close();

PDFs generated with iTextSharp generated watermark giving error

We are applying a watermark using iTextSharp to PDF documents before passing them to client. On some machines (all using v.11 of PDF viewer), the following error is being displayed.
An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF Document to correct the problem.
The watermarking code is as follows:
protected static byte[] GetStampedDocument(byte[] content, string mark, string heading)
{
PdfReader reader = new PdfReader(content);
using (MemoryStream stream = new MemoryStream())
{
PdfStamper pdfStamper = new PdfStamper(reader, stream);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
iTextSharp.text.Rectangle pageSize = reader.GetPageSizeWithRotation(i);
PdfContentByte pdfPageContents = pdfStamper.GetOverContent(i);
pdfPageContents.BeginText();
PdfGState gstate = new PdfGState();
gstate.FillOpacity = 0.2f;
gstate.StrokeOpacity = 0.3f;
pdfPageContents.SaveState();
pdfPageContents.SetGState(gstate);
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
pdfPageContents.SetFontAndSize(baseFont, 46);
pdfPageContents.SetRGBColorFill(32, 32, 32);
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, mark, pageSize.Width / 2, pageSize.Height / 2, 66);
if (heading != null && heading.Length > 0)
{
pdfPageContents.SetFontAndSize(baseFont, 12);
pdfPageContents.SetRGBColorFill(32, 32, 32);
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, heading, 5, pageSize.Height - 15, 0);
}
pdfPageContents.EndText();
pdfPageContents.RestoreState();
}
pdfStamper.FormFlattening = true;
pdfStamper.FreeTextFlattening = true;
pdfStamper.Close();
return stream.ToArray();
}
}
I cannot recreate this on any machine I have tried so there is an environmental element to this as well I expect.
Any ideas?
You save the graphics state inside a text object:
pdfPageContents.BeginText();
[...]
pdfPageContents.SaveState();
[...]
pdfPageContents.EndText();
pdfPageContents.RestoreState();
This is not allowed, cf. Figure 9 — Graphics objects — in ISO 32000-2, special graphics state operators (like saving or restoring the graphics state) may not be used inside a text object.
To prevent this invalid syntax, move pdfPageContents.SaveState() before pdfPageContents.BeginText(). This furthermore makes the nesting of saving/restoring the state and beginning and ending the text object more natural.

Unable to add margins in iTextSharp document having images

Requirement:
A large image (dynamic) needs to be split and shown in PDF pages. If image can't be accomodated in one page then we need to add another page and try to fit the remaining portion and so on.
So far I am able to split the image in multiple pages, however it appears that they are completely ignoring the margin values and so images are shown without any margins.
Please see below code:
string fileStringReplace = imageByteArray.Replace("data:image/jpeg;base64,", "");
Byte[] imageByte = Convert.FromBase64String(fileStringReplace);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageByte);
float w = image.ScaledWidth;
float h = image.ScaledHeight;
float cropHeight = 1500f;
iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(1150f, cropHeight);
var x = page.Height;
Byte[] created;
iTextSharp.text.Document document = new iTextSharp.text.Document(page, 20f, 20f, 20f, 40f); --This has no impact
using (var outputMemoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(document, outputMemoryStream);
writer.CloseStream = false;
document.Open();
PdfContentByte canvas = writer.DirectContentUnder;
float usedHeights = h;
while (usedHeights >= 0)
{
usedHeights -= cropHeight;
document.SetPageSize(new iTextSharp.text.Rectangle(1150f, cropHeight));
canvas.AddImage(image, w, 0, 0, h, 0, -usedHeights);
document.NewPage();
}
document.Close();
created = outputMemoryStream.ToArray();
outputMemoryStream.Write(created, 0, created.Length);
outputMemoryStream.Position = 0;
}
return created;
I also tried to set margin in the loop by document.SetMargins() - but that's not working.
You are mixing different things.
When you create margins, be it while constructing the Document instance or by using the setMargins() method, you create margins for when you let iText(Sharp) decide on the layout. That is: the margins will be respected when you do something like document.Add(image).
However, you do not allow iText to create the layout. You create a PdfContentByte named canvas and you decide to add the image to that canvas using a transformation matrix. This means that you will calculate the a, b, c, d, e, and f value needed for the AddImage() method.
You are supposed to do that Math. If you want to see a margin, then the values w, 0, 0, h, 0, and -usedHeights are wrong, and you shouldn't blame iTextSharp, you should blame your lack of insight in analytical geometrics (that's the stuff you learn in high school at the age of 16).
This might be easier for you:
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageByte);
float w = image.ScaledWidth;
float h = image.ScaledHeight;
// For the sake of simplicity, I don't crop the image, I just add 20 user units
iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(w + 20, h + 20);
iTextSharp.text.Document document = new iTextSharp.text.Document(page);
PdfWriter writer = PdfWriter.GetInstance(document, outputMemoryStream);
// Please drop the line that prevents closing the output stream!
// Why are so many people making this mistake?
// Who told you you shouldn't close the output stream???
document.Open();
// We define an absolute position for the image
// it will leave a margin of 10 to the left and to the bottom
// as we created a page that is 20 user units to wide and to high,
// we will also have a margin of 10 to the right and to the top
img.SetAbsolutePosition(10, 10);
document.Add(Image);
document.Close();
Note that SetAbsolutePosition() also lets you take control, regardless of the margins, as an alternative, you could use:
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageByte);
float w = image.ScaledWidth;
float h = image.ScaledHeight;
// For the sake of simplicity, I don't crop the image, I just add 20 user units
iTextSharp.text.Rectangle page = new iTextSharp.text.Rectangle(w + 20, h + 20);
iTextSharp.text.Document document = new iTextSharp.text.Document(page, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(document, outputMemoryStream);
// Please drop the line that prevents closing the output stream!
// Why are so many people making this mistake?
// Who told you you shouldn't close the output stream???
document.Open();
// We add the image to the document, and we let iTextSharp decide where to put it
// As there is just sufficient space to fit the image inside the page, it should fit,
// But be aware of the existence of a leading; that could create side-effects
// such as forwarding the image to the next page because it doesn't fit vertically
document.Add(Image);
document.Close();

Convert g722 audio to WAV using NAudio

I'm starting to write a Windows Service that will convert G.722 audio files into WAV files and I'm planning on using the NAudio library.
After looking at the NAudio demos, I've found that I will need to use the G722Codec to decode the audio data from the file but I'm having trouble figuring out how to read the G722 file. Which reader should I use?\
The G722 files are 7 kHz.
I'm working my way through the Pluralsight course for NAudio but it would be great to get a small code sample.
I got it working with the RawSourceWaveStreambut then tried to simply read the bytes of the file, decode using the G722 Codec and write the bytes out to a wave file. It worked.
private readonly G722CodecState _state = new G722CodecState(64000, G722Flags.SampleRate8000);
private readonly G722Codec _codec = new G722Codec();
private readonly WaveFormat _waveFormat = new WaveFormat(8000, 1);
public MainWindow()
{
InitializeComponent();
var data = File.ReadAllBytes(#"C:\Recordings\000-06Z_chunk00000.g722");
var output = Decode(data, 0, data.Length);
using (WaveFileWriter waveFileWriter = new WaveFileWriter(#"C:\Recordings\000-06Z_chunk00000.wav", _waveFormat))
{
waveFileWriter.Write(output, 0, output.Length);
}
}
private byte[] Decode(byte[] data, int offset, int length)
{
if (offset != 0)
{
throw new ArgumentException("G722 does not yet support non-zero offsets");
}
int decodedLength = length * 4;
var outputBuffer = new byte[decodedLength];
var wb = new WaveBuffer(outputBuffer);
int decoded = _codec.Decode(_state, wb.ShortBuffer, data, length);
return outputBuffer;
}

How to draw a triangle in a math graph?

How to draw a triangle in a math graph which displays X and Y axis.
To draw shapes using ActionScript2, you can use the moveTo() and lineTo() methods of the MovieClip object. You can specify line colour and thickness with lineStyle(), or make a solid shape using beginFill() and endFill().
So to draw your graph and triangle you could do the following steps:
Make a movieClip named "graph"
Define how big your graph should be (using the flash.geom.Rectangle object)
Draw a grey background using graph.beginFill(grey) and then moveTo() and lineTo()
Draw some blue lines at regular intervals for a grid
Draw the X and Y axes on the side and bottom of your grid
Make a second movieClip named "shape"
Pick 3 random points: moveTo(point1), lineTo(point2), lineTo(point3), lineTo(point1)
Here's how the code might look:
import flash.geom.Point;
import flash.geom.Rectangle;
function drawGraph(mc:MovieClip, rect:Rectangle):Void {
//this is a function to draw the graph
//draw the background
mc.beginFill(0xF8F8F8);
mc.moveTo(rect.left, rect.bottom);
mc.lineTo(rect.left, rect.top);
mc.lineTo(rect.right, rect.top);
mc.lineTo(rect.right, rect.bottom);
mc.lineTo(rect.left, rect.bottom);
mc.endFill();
//draw a grid
var unit:Number = 20;
mc.lineStyle(1, 0x0000FF, 20, true, "none", "round", "round");
var i:Number=rect.x;
do {
i=i+unit;
mc.moveTo(i, rect.bottom);
mc.lineTo(i, rect.top);
} while (i<rect.right);
i=rect.bottom;
do {
i=i-unit;
mc.moveTo(rect.left, i);
mc.lineTo(rect.right,i);
} while (i>rect.top);
//draw the axes
mc.lineStyle(2, 0x808080, 100, true, "none", "round", "round");
mc.moveTo(rect.left, rect.bottom);
mc.lineTo(rect.left, rect.top);
mc.moveTo(rect.left, rect.bottom);
mc.lineTo(rect.right, rect.bottom);
}
function randomPoint(rect:Rectangle):Point {
//this is a function which returns a random point within rect
var p:Point = new Point(rect.x+Math.random()*rect.width, rect.y+Math.random()*rect.height);
return p;
}
function drawTriangle(mc:MovieClip, rect:Rectangle):Void {
//this is a function to draw the triangle
// pick 3 random points within rect
var p1:Point = randomPoint(rect);
var p2:Point = randomPoint(rect);
var p3:Point = randomPoint(rect);
//connect the points to make a triangle
mc.lineStyle(3, 0xFF0000, 100, true, "none", "round", "round");
mc.moveTo(p1.x, p1.y);
mc.lineTo(p2.x, p2.y);
mc.lineTo(p3.x, p3.y);
mc.lineTo(p1.x, p1.y);
}
//make the 'graph' clip:
var myGraph:MovieClip = this.createEmptyMovieClip("myGraph", this.getNextHighestDepth());
//define the graph size:
var myRect:Rectangle = new Rectangle(50,50,300,300);
drawGraph(myGraph,myRect);//draw the graph
var myShape:MovieClip = this.createEmptyMovieClip("myShape", this.getNextHighestDepth());//make the 'shape' clip
drawTriangle(myShape,myRect);//draw a random triangle
//add a function to draw a new triangle when the graph is clicked:
myGraph.onRelease = function() {
myShape.clear();//erase the old triangle
drawTriangle(myShape,myRect);//draw a new one
}
You can click the graph to generate a new random triangle.
(source: webfactional.com)
It sounds like you need to know how the drawing API works in Flash. Your question is kind of vague, but this might help to get you started - google "Flash Drawing API" for more information.
var point1:Point = new Point (0, 0);
var point2:Point = new Point (25, -50);
var point3:Point = new Point (50, 0);
var s:Sprite = new Sprite();
s.graphics.lineStyle(1, 0xff0000);
s.graphics.beginFill(0x000000);
s.graphics.moveTo(point1.x, point1.y);
s.graphics.lineTo(point2.x, point2.y);
s.graphics.lineTo(point3.x, point3.y);
s.graphics.lineTo(point1.x, point1.y);
s.graphics.endFill();
s.graphics.lineStyle(0);
s.x = (stage.stageWidth - s.width) / 2;
s.y = ((stage.stageHeight - s.height) / 2) + 50;
addChild(s);
I hope that helps, let me know if you have any questions.
NOTE: This solution is using ActionScript 3. If you need AS2 this won't work, and off the top of my head I don't know how to help but you might just try googling "AS2 Drawing API" or something to that effect.