Qt3D: Texture is black - qt

I'm trying to render frames captured by 3D scanner using Qt3D. Mesh is constructed right in geometry but it's shown black.
Below is my function where I convert vertices, texture coordinates, normals and add result object to a Scene. For debug purposes I'm trying to map texture from one source .png file to all the frames. But it still looks black. Normalizing texture coordinates vector didn't help.
Please take a look at my code and clarify what I'm doing wring. Thanks in advance.
Qt3DCore::QEntity* object = new Qt3DCore::QEntity(parent);
Qt3DRender::QGeometryRenderer* renderer = new Qt3DRender::QGeometryRenderer(object);
Qt3DRender::QGeometry* geometry = new Qt3DRender::QGeometry(renderer);
Qt3DRender::QBuffer* vertexBuffer = new Qt3DRender::QBuffer(geometry);
Qt3DRender::QBuffer* indexBuffer = new Qt3DRender::QBuffer(geometry);
Qt3DRender::QAttribute* positionAttribute = new Qt3DRender::QAttribute(geometry);
Qt3DRender::QAttribute* normalAttribute = new Qt3DRender::QAttribute(geometry);
Qt3DRender::QAttribute* texCoordAttribute = new Qt3DRender::QAttribute(geometry);
Qt3DRender::QAttribute* indexAttribute = new Qt3DRender::QAttribute(geometry);
const quint32 stride = (3 + 3 + 2) * sizeof(float);
positionAttribute->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());
positionAttribute->setDataType(Qt3DRender::QAttribute::Float);
positionAttribute->setDataSize(3);
positionAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
positionAttribute->setBuffer(vertexBuffer);
positionAttribute->setByteOffset(0);
positionAttribute->setByteStride(stride);
normalAttribute->setName(Qt3DRender::QAttribute::defaultNormalAttributeName());
normalAttribute->setDataType(Qt3DRender::QAttribute::Float);
normalAttribute->setDataSize(3);
normalAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
normalAttribute->setBuffer(vertexBuffer);
normalAttribute->setByteOffset(3 * sizeof(float));
normalAttribute->setByteStride(stride);
texCoordAttribute->setName(Qt3DRender::QAttribute::defaultTextureCoordinateAttributeName());
texCoordAttribute->setDataType(Qt3DRender::QAttribute::Float);
texCoordAttribute->setDataSize(2);
texCoordAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
texCoordAttribute->setBuffer(vertexBuffer);
texCoordAttribute->setByteOffset((3 + 3) * sizeof(float));
texCoordAttribute->setByteStride(stride);
indexAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
indexAttribute->setDataType(Qt3DRender::QAttribute::Int);
indexAttribute->setDataSize(3);
indexAttribute->setByteOffset(0);
indexAttribute->setBuffer(indexBuffer);
indexAttribute->setCount(indices.size());
QByteArray* vertexArray = new QByteArray;
const auto t = vertices.size();
const auto r = sizeof(VertexData);
const auto d = t * r;
vertexArray->resize(vertices.size() * sizeof(VertexData));
float* rawVertexArray = reinterpret_cast<float*>(vertexArray->data());
int index = 0;
for (int i = 0; i < vertices.size(); ++i)
{
rawVertexArray[index++] = vertices[i].position_.x();
rawVertexArray[index++] = vertices[i].position_.y();
rawVertexArray[index++] = vertices[i].position_.z();
rawVertexArray[index++] = vertices[i].normal_.x();
rawVertexArray[index++] = vertices[i].normal_.y();
rawVertexArray[index++] = vertices[i].normal_.z();
const auto x = vertices[i].texCoords_.x();
rawVertexArray[index++] = vertices[i].texCoords_.x();
const auto y = vertices[i].texCoords_.y();
rawVertexArray[index++] = vertices[i].texCoords_.y();
}
QByteArray* indexArray = new QByteArray;
indexArray->resize(indices.size() * sizeof(VertexData));
auto* rawIndexArray = reinterpret_cast<int*>(indexArray->data());
index = 0;
for (int i = 0; i < indices.size(); ++i)
{
rawIndexArray[index++] = indices[i].x();
rawIndexArray[index++] = indices[i].y();
rawIndexArray[index++] = indices[i].z();
}
vertexBuffer->setData(*vertexArray);
indexBuffer->setData(*indexArray);
geometry->addAttribute(positionAttribute);
geometry->addAttribute(normalAttribute);
geometry->addAttribute(texCoordAttribute);
geometry->addAttribute(indexAttribute);
renderer->setGeometry(geometry);
renderer->setInstanceCount(1);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::TriangleFan);
object->addComponent(renderer);
// Texture
Qt3DRender::QTexture2D* targetTexture = new Qt3DRender::QTexture2D(renderer);
Qt3DRender::QTextureImage* textureImage = new Qt3DRender::QTextureImage(targetTexture);
Qt3DExtras::QDiffuseSpecularMaterial* material = new Qt3DExtras::QDiffuseSpecularMaterial(renderer);
//Qt3DExtras::QNormalDiffuseSpecularMapMaterial* material = new Qt3DExtras::QNormalDiffuseSpecularMapMaterial();
textureImage->setMirrored(true);
textureImage->setSource(QUrl::fromLocalFile("D://Calibration tool//app-calibration-tool//output//1.jpg"));
targetTexture->addTextureImage(textureImage);
material->setDiffuse(QVariant::fromValue<Qt3DRender::QAbstractTexture *>(targetTexture));
material->setAmbient(QColor(255, 255, 255, 1));
material->setSpecular(QColor(255, 255, 255, 1));
material->setTextureScale(4);
material->setAlphaBlendingEnabled(true);
const auto transform = new Qt3DCore::QTransform(renderer);
object->addComponent(transform);
object->addComponent(material);
return parent;

Related

First page is blackened after adding watermark

Page is blackened after adding watermark in case of some pdf files . Please see attached image.
What could be the reason , and possible fix.
see the blacked out page image
It does not happen for all the files but for some files only.
Code is here in dotnetfiddle.
var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
} var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
}

What is the most practical way to create coordinate grid with JavaFX 3D?

I would like to create a 3D demo application with JavaFX to visualize movements of points in 3D space and first I need to set up a coordinate grid for visual reference. Unfortunately, I was not able to find a sample code for a grid like in this picture:
Does anyone know what is the most practical way to create something like it?
There are a few solutions out there already.
FXyz3D library has a CubeWorld class, that gives you precisely a reference grid.
It is quite easy to use. Just import the 'org.fxyz3d:fxyz3d:0.3.0' dependency from JCenter and use it:
CubeWorld cubeWorld = new CubeWorld(5000, 500, true);
Sphere sphere = new Sphere(100);
sphere.setMaterial(new PhongMaterial(Color.FIREBRICK));
sphere.getTransforms().add(new Translate(100, 200, 300));
Scene scene = new Scene(new Group(cubeWorld, sphere), 800, 800, true, SceneAntialiasing.BALANCED);
As you can see, the solution is based on using 2D rectangles for each face, and the grid lines are created with 3D cylinders. It has very nice features (like self lightning or frontal faces according to camera don't show grid), but it is quite intensive in nodes (sample above has 168 nodes).
There are other solutions that use a lower number of nodes. For instance, for this sample, that also happens to be related to Leap Motion, I used a TriangleMesh.
This is an easy solution, and with just two meshes. However, you see the triangles, instead of squares.
So let's try to get rid of the triangles. For that I'll use a PolygonMesh, as in this other question, based on the 3DViewer project that is available at the OpenJFX repository, contains already a PolygonalMesh implementation, that allows any number of points per face, so any polygon can be a face.
This will give you a plane grid based in square faces:
private PolygonMesh createQuadrilateralMesh(float width, float height, int subDivX, int subDivY) {
final float minX = - width / 2f;
final float minY = - height / 2f;
final float maxX = width / 2f;
final float maxY = height / 2f;
final int pointSize = 3;
final int texCoordSize = 2;
// 4 point indices and 4 texCoord indices per face
final int faceSize = 8;
int numDivX = subDivX + 1;
int numVerts = (subDivY + 1) * numDivX;
float points[] = new float[numVerts * pointSize];
float texCoords[] = new float[numVerts * texCoordSize];
int faceCount = subDivX * subDivY;
int faces[][] = new int[faceCount][faceSize];
// Create points and texCoords
for (int y = 0; y <= subDivY; y++) {
float dy = (float) y / subDivY;
double fy = (1 - dy) * minY + dy * maxY;
for (int x = 0; x <= subDivX; x++) {
float dx = (float) x / subDivX;
double fx = (1 - dx) * minX + dx * maxX;
int index = y * numDivX * pointSize + (x * pointSize);
points[index] = (float) fx;
points[index + 1] = (float) fy;
points[index + 2] = 0.0f;
index = y * numDivX * texCoordSize + (x * texCoordSize);
texCoords[index] = dx;
texCoords[index + 1] = dy;
}
}
// Create faces
int index = 0;
for (int y = 0; y < subDivY; y++) {
for (int x = 0; x < subDivX; x++) {
int p00 = y * numDivX + x;
int p01 = p00 + 1;
int p10 = p00 + numDivX;
int p11 = p10 + 1;
int tc00 = y * numDivX + x;
int tc01 = tc00 + 1;
int tc10 = tc00 + numDivX;
int tc11 = tc10 + 1;
faces[index][0] = p00;
faces[index][1] = tc00;
faces[index][2] = p10;
faces[index][3] = tc10;
faces[index][4] = p11;
faces[index][5] = tc11;
faces[index][6] = p01;
faces[index++][7] = tc01;
}
}
int[] smooth = new int[faceCount];
PolygonMesh mesh = new PolygonMesh(points, texCoords, faces);
mesh.getFaceSmoothingGroups().addAll(smooth);
return mesh;
}
So you can use 2 or 3 of them to create a coordinate system like this:
public Group createGrid(float size, float delta) {
if (delta < 1) {
delta = 1;
}
final PolygonMesh plane = createQuadrilateralMesh(size, size, (int) (size / delta), (int) (size / delta));
final PolygonMesh plane2 = createQuadrilateralMesh(size, size, (int) (size / delta / 5), (int) (size / delta / 5));
PolygonMeshView meshViewXY = new PolygonMeshView(plane);
meshViewXY.setDrawMode(DrawMode.LINE);
meshViewXY.setCullFace(CullFace.NONE);
PolygonMeshView meshViewXZ = new PolygonMeshView(plane);
meshViewXZ.setDrawMode(DrawMode.LINE);
meshViewXZ.setCullFace(CullFace.NONE);
meshViewXZ.getTransforms().add(new Rotate(90, Rotate.X_AXIS));
PolygonMeshView meshViewYZ = new PolygonMeshView(plane);
meshViewYZ.setDrawMode(DrawMode.LINE);
meshViewYZ.setCullFace(CullFace.NONE);
meshViewYZ.getTransforms().add(new Rotate(90, Rotate.Y_AXIS));
PolygonMeshView meshViewXY2 = new PolygonMeshView(plane2);
meshViewXY2.setDrawMode(DrawMode.LINE);
meshViewXY2.setCullFace(CullFace.NONE);
meshViewXY2.getTransforms().add(new Translate(size / 1000f, size / 1000f, 0));
PolygonMeshView meshViewXZ2 = new PolygonMeshView(plane2);
meshViewXZ2.setDrawMode(DrawMode.LINE);
meshViewXZ2.setCullFace(CullFace.NONE);
meshViewXZ2.getTransforms().add(new Translate(size / 1000f, size / 1000f, 0));
meshViewXZ2.getTransforms().add(new Rotate(90, Rotate.X_AXIS));
PolygonMeshView meshViewYZ2 = new PolygonMeshView(plane2);
meshViewYZ2.setDrawMode(DrawMode.LINE);
meshViewYZ2.setCullFace(CullFace.NONE);
meshViewYZ2.getTransforms().add(new Translate(size / 1000f, size / 1000f, 0));
meshViewYZ2.getTransforms().add(new Rotate(90, Rotate.Y_AXIS));
return new Group(meshViewXY, meshViewXY2, meshViewXZ, meshViewXZ2 /*, meshViewYZ, meshViewYZ2 */);
}
Note that I've duplicated the plane to mock a wider stroke every 5 lines.
Finally adding axes:
public Group getAxes(double scale) {
Cylinder axisX = new Cylinder(1, 200);
axisX.getTransforms().addAll(new Rotate(90, Rotate.Z_AXIS), new Translate(0, -100, 0));
axisX.setMaterial(new PhongMaterial(Color.RED));
Cylinder axisY = new Cylinder(1, 200);
axisY.getTransforms().add(new Translate(0, 100, 0));
axisY.setMaterial(new PhongMaterial(Color.GREEN));
Cylinder axisZ = new Cylinder(1, 200);
axisZ.setMaterial(new PhongMaterial(Color.BLUE));
axisZ.getTransforms().addAll(new Rotate(90, Rotate.X_AXIS), new Translate(0, 100, 0));
Group group = new Group(axisX, axisY, axisZ);
group.getTransforms().add(new Scale(scale, scale, scale));
return group;
}
Now you have:
final Group axes = getAxes(0.5);
final Group grid = createGrid(200, 10);
final Sphere sphere = new Sphere(5);
sphere.getTransforms().add(new Translate(20, 15, 40));
Scene scene = new Scene(new Group(axes, grid, sphere), 800, 800, true, SceneAntialiasing.BALANCED);
The total amount of nodes of this sample is 14.
Of course, it can be improved to add labels and many other features.

how to dragging Threejs point

I'm trying to huge graph visualization with threejs r86(latest master version), for showing 600,000 nodes I found a way to draw them faster than using mesh with THREE.points but know I need to make them draggable, after many searches I found raycast to found closest object to mouse point but I have a problem becouse all of taht points are just an object and can not be changed seperately.
function Graph3(Nodes, Edges) {
this.renderer = new THREE.WebGLRenderer({ alpha: true});
var width = window.innerWidth , height = window.innerHeight;
this.renderer.setSize(width, height, false);
document.body.appendChild(this.renderer.domElement);
this.scene = new THREE.Scene(),
this.camera = new THREE.PerspectiveCamera(100, width / height, 0.1, 3000),
this.controls = new THREE.OrbitControls(this.camera);
this.controls.enableKeys = true;
this.controls.enableRotate = false;
var material, geometry;
self = this;
material = new THREE.LineBasicMaterial({color: '#ccc'});
geometry = new THREE.Geometry();
geometry.vertices = Nodes.map(function(item){return new THREE.Vector3(item.pos.x,item.pos.y,item.pos.z);});
// this.vertices = geometry.vertices;
this.line = new THREE.LineSegments(geometry, material);
this.scene.add(this.line);
var Node = new THREE.Group();
material = new THREE.PointsMaterial( { color:0x000060 ,size:1 } );
this.particles = new THREE.Mesh(geometry,material)
this.particles = new THREE.Points( geometry, material);
this.scene.add( this.particles );
dragControls = new THREE.DragControls([this.particles], this.camera/*,this.scene*/, this.renderer.domElement);
this.camera.position.z = 200;
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
document.addEventListener( 'click', function ( event ) {
// calculate mouse position in normalized device coordinates
// (-1 to +1) for both components
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
console.log(mouse);
}, false );
stats = new Stats();
document.body.appendChild(stats.dom);
this.animate = function()
{
raycaster.setFromCamera( mouse, self.camera );
var intersections = raycaster.intersectObject( self.particles );
intersection = ( intersections.length ) > 0 ? intersections[ 0 ] : null;
if ( intersection !== null) {
console.log(intersection);
}
requestAnimationFrame( self.animate );
stats.update();
self.renderer.render(self.scene, self.camera);
}
this.animate();}
I had able to change all the points with dragControls but can't move them seperatly
I had found EventsControls.js file which help us to handle events but I couldn't use it
Here you can check how to target individual parts of a buffer geometry with a raycaster:
https://github.com/mrdoob/three.js/blob/master/examples/webgl_interactive_buffergeometry.html
As for moving them, refer to this question and answer:
How to quickly update a large BufferGeometry?
Thanks for helping me in previous question.
I am making my points in 2d plane (z = 0) and I could making them with bufferGeometry and RawShaderMaterial but now I have another problem in dragging them, how raycaster do? it need vec3 positions but I have changed it for performance purpose.
var Geo = new THREE.BufferGeometry();
var position = new Float32Array( NodeCount * 2 );
var colors = new Float32Array( NodeCount * 3 );
var sizes = new Float32Array( NodeCount );
for ( var i = 0; i < NodeCount; i++ ) {
position[ 2*i ] = (Math.random() - 0.5) * 10;
position[ 2*i + 1 ] = (Math.random() - 0.5) * 10;
colors[ 3*i ] = Math.random();
colors[3*i+1] = Math.random();
colors[3*i+2] = Math.random();
// sizes
sizes[i] = Math.random() * 5 ;
}
Geo.addAttribute( 'position', new THREE.BufferAttribute( position, 2 ) );
Geo.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
Geo.addAttribute( 'size', new THREE.BufferAttribute( sizes, 1 ) );
points = new THREE.Points( Geo, new THREE.RawShaderMaterial({
vertexShader:`
precision highp float;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 cameraPosition;
attribute vec2 position; /// reason of problem
varying vec3 vColor;
attribute vec3 color;
attribute float size;
void main() {
vColor = color;
gl_PointSize = size;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position , 0, 1 );
}`,
fragmentShader:`
precision highp float;
varying vec3 vColor;
void main() {
gl_FragColor = vec4( vColor, 1.0 ) ;
}`
}) );
scene.add( points );
and my using of raycaster:
function mouseDown(e) {
e.preventDefault();
var mouse = new THREE.Vector2();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
// mouse.z = 0;
raycaster.setFromCamera(mouse, camera);
raycaster.far = camera.position.z + 3;
const intersect = raycaster.intersectObject(points);
console.log(intersect);
if (intersect.length > 0) {
controls.enabled = false;
console.log(intersect);
selection = intersect[0].index;
}
}
function mouseUp(e) {
controls.enabled = true;
var vector = new THREE.Vector3();
vector.x = (( event.clientX / window.innerWidth ) * 2 - 1);
vector.y = (- ( event.clientY / window.innerHeight ) * 2 + 1);
vector.z = 1.0;
console.log(camera.position.z);
vector.unproject( camera );
var dir = vector.sub( camera.position ).normalize();
var distance = - camera.position.z / dir.z;
var temp = camera.position.clone().add( dir.multiplyScalar( distance ) );
var pos = points.geometry.attributes.position;
pos.setXY(selection, temp.x, temp.y);
pos.updateRange.offset = selection; // where to start updating
pos.updateRange.count = 1; // how many vertices to update
pos.needsUpdate = true;
selection = undefined;
}

export to excel in asp.net using openxml

Hello everyone i am working on a project which requires me to export some data to excel on a button click using open xml.Here is the class i am using for exporting to excel:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using _14junexcel.Account;
namespace _14junexcel
{
public class CreateExcelOpen
{
public void BuildWorkbook1(string filename)
{
string sFile = #"D:\\ExcelOpenXmlWithImageAndStyles.xlsx";
if (File.Exists(sFile))
{
File.Delete(sFile);
}
BuildWorkbook(sFile);
}
private static void BuildWorkbook(string filename)
{
try
{
using (SpreadsheetDocument xl = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
SheetData sd = new SheetData();
WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
string sImagePath = #"C:\\Users\\Public\\Pictures\\Sample Pictures\\Jellyfish.jpg";
DrawingsPart dp = wsp.AddNewPart<DrawingsPart>();
ImagePart imgp = dp.AddImagePart(ImagePartType.Png, wsp.GetIdOfPart(dp));
using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
{
imgp.FeedData(fs);
}
NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
nvdp.Id = 1025;
nvdp.Name = "Picture 1";
nvdp.Description = "polymathlogo";
DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
picLocks.NoChangeAspect = true;
picLocks.NoChangeArrowheads = true;
NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
nvpdp.PictureLocks = picLocks;
NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
nvpp.NonVisualDrawingProperties = nvdp;
nvpp.NonVisualPictureDrawingProperties = nvpdp;
DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();
BlipFill blipFill = new BlipFill();
DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
blip.Embed = dp.GetIdOfPart(imgp);
blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
blipFill.Blip = blip;
blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
blipFill.Append(stretch);
DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
offset.X = 0;
offset.Y = 0;
t2d.Offset = offset;
Bitmap bm = new Bitmap(sImagePath);
//http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
//http://stackoverflow.com/questions/1341930/pixel-to-centimeter
//http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
extents.Cx = (long)bm.Width * (long)((float)0 / bm.HorizontalResolution);
extents.Cy = (long)bm.Height * (long)((float)0 / bm.VerticalResolution);
bm.Dispose();
t2d.Extents = extents;
ShapeProperties sp = new ShapeProperties();
sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
sp.Transform2D = t2d;
DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
sp.Append(prstGeom);
sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());
DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
picture.NonVisualPictureProperties = nvpp;
picture.BlipFill = blipFill;
picture.ShapeProperties = sp;
Position pos = new Position();
pos.X = 0;
pos.Y = 0;
Extent ext = new Extent();
ext.Cx = extents.Cx;
ext.Cy = extents.Cy;
AbsoluteAnchor anchor = new AbsoluteAnchor();
anchor.Position = pos;
anchor.Extent = ext;
anchor.Append(picture);
anchor.Append(new ClientData());
WorksheetDrawing wsd = new WorksheetDrawing();
wsd.Append(anchor);
Drawing drawing = new Drawing();
drawing.Id = dp.GetIdOfPart(imgp);
wsd.Save(dp);
UInt32 index;
Random rand = new Random();
sd.Append(CreateHeader(2));
sd.Append(CreateColumnHeader(4));
for (index = 5; index < 6; ++index)
{
sd.Append(CreateContent(index, ref rand));
}
ws.Append(sd);
ws.Append(drawing);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "Sheet1";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
//xl.WorkbookPart.Workbook.Save();
xl.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
}
private static Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Fonts fts = new Fonts();
DocumentFormat.OpenXml.Spreadsheet.Font ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
FontName ftn = new FontName();
ftn.Val = StringValue.FromString("Calibri");
FontSize ftsz = new FontSize();
ftsz.Val = DoubleValue.FromDouble(11);
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
ftn = new FontName();
ftn.Val = StringValue.FromString("Palatino Linotype");
ftsz = new FontSize();
ftsz.Val = DoubleValue.FromDouble(18);
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
fts.Count = UInt32Value.FromUInt32((uint)fts.ChildElements.Count);
Fills fills = new Fills();
Fill fill;
PatternFill patternFill;
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.None;
fill.PatternFill = patternFill;
fills.Append(fill);
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Gray125;
fill.PatternFill = patternFill;
fills.Append(fill);
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Solid;
patternFill.ForegroundColor = new ForegroundColor();
patternFill.ForegroundColor.Rgb = HexBinaryValue.FromString("00ff9728");
patternFill.BackgroundColor = new BackgroundColor();
patternFill.BackgroundColor.Rgb = patternFill.ForegroundColor.Rgb;
fill.PatternFill = patternFill;
fills.Append(fill);
fills.Count = UInt32Value.FromUInt32((uint)fills.ChildElements.Count);
Borders borders = new Borders();
Border border = new Border();
border.LeftBorder = new LeftBorder();
border.RightBorder = new RightBorder();
border.TopBorder = new TopBorder();
border.BottomBorder = new BottomBorder();
border.DiagonalBorder = new DiagonalBorder();
borders.Append(border);
border = new Border();
border.LeftBorder = new LeftBorder();
border.LeftBorder.Style = BorderStyleValues.Thin;
border.RightBorder = new RightBorder();
border.RightBorder.Style = BorderStyleValues.Thin;
border.TopBorder = new TopBorder();
border.TopBorder.Style = BorderStyleValues.Thin;
border.BottomBorder = new BottomBorder();
border.BottomBorder.Style = BorderStyleValues.Thin;
border.DiagonalBorder = new DiagonalBorder();
borders.Append(border);
borders.Count = UInt32Value.FromUInt32((uint)borders.ChildElements.Count);
CellStyleFormats csfs = new CellStyleFormats();
CellFormat cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
csfs.Append(cf);
csfs.Count = UInt32Value.FromUInt32((uint)csfs.ChildElements.Count);
uint iExcelIndex = 164;
NumberingFormats nfs = new NumberingFormats();
CellFormats cfs = new CellFormats();
cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cfs.Append(cf);
NumberingFormat nfDateTime = new NumberingFormat();
nfDateTime.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nfDateTime.FormatCode = StringValue.FromString("dd/mm/yyyy hh:mm:ss");
nfs.Append(nfDateTime);
NumberingFormat nf4decimal = new NumberingFormat();
nf4decimal.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nf4decimal.FormatCode = StringValue.FromString("#,##0.0000");
nfs.Append(nf4decimal);
// #,##0.00 is also Excel style index 4
NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nf2decimal.FormatCode = StringValue.FromString("#,##0.00");
nfs.Append(nf2decimal);
// # is also Excel style index 49
NumberingFormat nfForcedText = new NumberingFormat();
nfForcedText.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nfForcedText.FormatCode = StringValue.FromString("#");
nfs.Append(nfForcedText);
//Alignment
Alignment align = new Alignment(){Horizontal = HorizontalAlignmentValues.General,Vertical=VerticalAlignmentValues.Center};
//wraptext
// Alignment align1 = new Alignment(){Horizontal=HorizontalAlignmentValues.CenterContinuous,Vertical=VerticalAlignmentValues.Center};
// index 1
cf = new CellFormat();
cf.NumberFormatId = nfDateTime.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 2
cf = new CellFormat();
cf.NumberFormatId = nf4decimal.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 3
cf = new CellFormat();
cf.NumberFormatId = nf2decimal.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 4
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 5
// Header text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 1;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 6
// column text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 1;
cf.FillId = 1;
cf.BorderId = 1;
cf.FormatId = 1;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 7
// coloured 2 decimal text
cf = new CellFormat();
cf.NumberFormatId = nf2decimal.NumberFormatId;
cf.FontId = 0;
//cf.FillId = 2;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId =0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
//cf.Append(align);
cf.Append(align);
// index 8
// coloured column text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 0;
//cf.FillId = 2;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
nfs.Count = UInt32Value.FromUInt32((uint)nfs.ChildElements.Count);
cfs.Count = UInt32Value.FromUInt32((uint)cfs.ChildElements.Count);
ss.Append(nfs);
ss.Append(fts);
ss.Append(fills);
ss.Append(borders);
ss.Append(csfs);
ss.Append(cfs);
CellStyles css = new CellStyles();
CellStyle cs = new CellStyle();
cs.Name = StringValue.FromString("Normal");
cs.FormatId = 0;
cs.BuiltinId = 0;
css.Append(cs);
css.Count = UInt32Value.FromUInt32((uint)css.ChildElements.Count);
ss.Append(css);
DifferentialFormats dfs = new DifferentialFormats();
dfs.Count = 0;
ss.Append(dfs);
TableStyles tss = new TableStyles();
tss.Count = 0;
tss.DefaultTableStyle = StringValue.FromString("TableStyleMedium9");
tss.DefaultPivotStyle = StringValue.FromString("PivotStyleLight16");
ss.Append(tss);
return ss;
}
private static Row CreateHeader(UInt32 index)
{
Row r = new Row();
r.RowIndex = index;
Cell c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 5;
c.CellReference = "A" + index.ToString();
c.CellValue = new CellValue("REPORT");
r.Append(c);
return r;
}
private static Row CreateColumnHeader(UInt32 index)
{
Row r = new Row();
r.RowIndex = index;
Cell c;
c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 7;
c.CellReference = "A" + index.ToString();
c.CellValue = new CellValue("Retail Customer Group");
r.Append(c);
c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 7;
c.CellReference = "B" + index.ToString();
c.CellValue = new CellValue("Product Promotion Group");
r.Append(c);
return r;
}
private static Row CreateContent(UInt32 index, ref Random rd)
{
Row r = new Row();
r.RowIndex = index;
Cell c;
c = new Cell();
c.StyleIndex = 7;
c.CellReference = "A" + index.ToString();
//c.CellValue = new CellValue(rd.Next(1000000000).ToString());
c.CellValue = new CellValue("12334");
r.Append(c);
DateTime dtEpoch = new DateTime(1900, 1, 1, 0, 0, 0, 0);
DateTime dt = dtEpoch.AddDays(rd.NextDouble() * 100000.0);
TimeSpan ts = dt - dtEpoch;
double fExcelDateTime;
// Excel has "bug" of treating 29 Feb 1900 as valid
// 29 Feb 1900 is 59 days after 1 Jan 1900, so just skip to 1 Mar 1900
if (ts.Days >= 59)
{
fExcelDateTime = ts.TotalDays + 2.0;
}
else
{
fExcelDateTime = ts.TotalDays + 1.0;
}
c = new Cell();
c.StyleIndex = 7;
c.CellReference = "B" + index.ToString();
c.CellValue = new CellValue("124515");
//c.CellValue = new CellValue(fExcelDateTime.ToString());
r.Append(c);
return r;
}
}
}
and this is the function for button click :
protected void Button1_Click(object sender, EventArgs e)
{
string qwe = TextBox1.Text;
string ert = TextBox2.Text;
string filename = #"D:\\ExcelOpenXmlWithImageAndStyles.xlsx";
CreateExcelOpen exp = new CreateExcelOpen();
exp.BuildWorkbook1(filename);
}
here are my requirements:
1.I need to pass the values of two textboxes to the two cells(which now contain values 12334 and 124515).
2. The heading column does not adjust itself to accomodate the values which i have provided(Retail customer group etc).Please suggest the
modifications required in this class to enable the autofit.
Thank you.
In Your CreateContent method you have hard coded values like:
c.CellValue = new CellValue("12334");
change it with values of text boxes that you want to show.
for setting width of headers, you will have to add columns along with Cells as you need columns to define the width, following article will be of some help for you:
http://catalog.codeproject.com/script/Articles/ArticleVersion.aspx?aid=371203&av=543408
I wrote my own export to Excel writer. It is fast and allows for substantial formatting of the cells. You can review it at
https://openxmlexporttoexcel.codeplex.com/
I hope it helps.
I've spent a lot of time googling OpenXml related questions.
I finally found a solution to my problems by combining OpenXml features with Excel VBA.
So,
I have Excel - macro enabled file (xlsm) as template for my project.
Whatever logic is hard to implement in OpenXml I moved to VBA.
For AutoFit for example it is as easy as:
Sub Workbook_Open()
ActiveSheet.Columns.AutoFit
End Sub
Hope it may help.

getPixel-method - how do i get the R value of RGB?

i have a greyscale image and i want to scan the pixels out of the Image and this is what i get :
var i:int;
var j:int;
for (i = 0; i < img.contentWidth ; i++)
{
for(j = 0; j < img.contentHeight; j++){
pixeldaten.addItem({x:i,y:j,pixel:bmd.getPixel(i,j)});
}
}
but the table doesn't look like RGB Values . (R , B , and G must be the same)
: example
getPixel should return the hex value value of the pixel, you could then do something like
// get the red value
bmd.getPixel(i,j) >> 16
//for Image processing
Bitmap myBitmap = new Bitmap(CurrentBitmap);
int imgH = myBitmap.Height;
int imgW = myBitmap.Width;
ARed = new double[imgH, imgW];
AGreen = new double[imgH, imgW];
ABlue = new double[imgH, imgW];
doubles = new double[imgH, imgW];
var max = new double[imgH, imgW];
var min = new double[0, 0];
//seperating each RGB components
for (int x = 0; x < imgH; x++)
{
for (int y = 0; y < imgW; y++)
{
Color color = myBitmap.GetPixel(x, y);
// things we do with pixelColor
//ARed[x][y] = myBitmap.GetPixel >> 16;
ARed[x, y] = color.R;
ABlue[x, y] = color.B;
AGreen[x, y] = color.G;
max[x, y] = ARed[x, y];
}
}
Bitmap bmp = new Bitmap(pictureBox1.Image);
bmp.getPixel(i,j).R

Resources