3d cube using java3d virtualUniverse - java-3d

I am interested in java3d API. I have been following java 3d programming by Daniel Selman. I tried to create a simple 3d cube using the following code given in the book:
public static void main(String[] args)
{
Cude3d cd= new Cude3d();
cd.go();
//create the Universe
}
The go method is:
private void go() {
VirtualUniverse m_Universe = new VirtualUniverse();
//create the position for the Locale
int[] xPos = { 0, 0, 0, 0, 0, 0, 0, 0 }; int[] yPos = { 0, 0, 0, 0, 0, 0, 0, 0 };
int[] zPos = { 0, 0, 0, 1, 0, 0, 0, 0 };
HiResCoord hiResCoord = new HiResCoord( xPos, yPos, zPos );
//create the Locale and attach to the VirtualUniverse
Locale locale = new Locale( m_Universe, hiResCoord );
//create the BranchGroup containing the Geometry for the scene
BranchGroup sceneBranchGroup = createSceneBranchGroup();
sceneBranchGroup.compile();
//add the scene BranchGroup to the Locale
locale.addBranchGraph( sceneBranchGroup );
The scene graph is created as:
BranchGroup vpBranchGroup = new BranchGroup();
//create a TransformGroup to scale the ViewPlatform //(and hence View)
TransformGroup tg = new TransformGroup();
ColorCube cc= new ColorCube(.2);
cc.setBounds(new BoundingSphere());
tg.addChild(cc);
//create the ViewPlatform
ViewPlatform vp = new ViewPlatform(); vp.setViewAttachPolicy( View.RELATIVE_TO_FIELD_OF_VIEW );
//attach the ViewPlatform to the TransformGroup
tg.addChild( vp );
//attach the TransformGroup to the BranchGroup
vpBranchGroup.addChild( tg );
Transform3D t3d = new Transform3D();
t3d.setTranslation( new Vector3d( 10.0, 10.0, 10.0 ) ); tg.setTransform( t3d );
View view = new View();
//create the PhysicalBody and PhysicalEnvironment for the View
//and attach to the View
PhysicalBody pb = new PhysicalBody();
PhysicalEnvironment pe = new PhysicalEnvironment();
view.setPhysicalEnvironment( pe );
view.setPhysicalBody( pb );
//attach the View to the ViewPlatform
view.attachViewPlatform( vp );
//set the near and far clipping planes for the View
view.setBackClipDistance( 110 );
view.setFrontClipDistance( 10 );
GraphicsConfigTemplate3D gc3D = new GraphicsConfigTemplate3D();
gc3D.setSceneAntialiasing( GraphicsConfigTemplate.PREFERRED );
GraphicsDevice gd[] = GraphicsEnvironment.
getLocalGraphicsEnvironment().getScreenDevices();
Canvas3D c3d = new Canvas3D( gd[0].getBestConfiguration( gc3D ) );
//set the size of the Canvas3D
c3d.setSize( 512, 512 );
//add the Canvas3D to the View so that it is rendered into
view.addCanvas3D( c3d );
//add the Canvas3D component to a parent AWT or Swing Panel
add( c3d );
this.setVisible(true);
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return vpBranchGroup;
I am not able to know where it went wrong. Any help is appreciated.
Thanks in advance.

Related

How to use PDF Sharp objects in my Migradoc document

I have an application that generates PDFs using the MigraDoc framework, however I have a requirement to add in a text driven watermark. I have found some examples of this being done using PDF Sharp here, however I just cant seem t be able to figure out how this will integrate with my Migradoc Document() object I am rendering.
I have the following code:
public byte[] render()
{
PdfDocument document = new PdfDocument();
CreateWaterMarks(document);
// *****************************
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = this.document;
renderer.RenderDocument();
byte[] pdfContents = null;
using (MemoryStream stream = new MemoryStream())
{
renderer.PdfDocument.Save(stream, true);
pdfContents = stream.ToArray();
}
return pdfContents;
}
This method is what is called to render the MigraDoc document and pass it out as a byte array. The second line of code in here calls the following method which is not doing what I am looking for:
void CreateWaterMarks(PdfDocument document)
{
PdfPage page = document.AddPage();
Document doc = this.document;
MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
docRenderer.PrepareDocument();
XRect A4Rect = new XRect(0, 0, pageActiveWidth, pageActiveHeight);
int pageCount = docRenderer.FormattedDocument.PageCount;
for (int idx = 0; idx < pageCount; idx++)
{
XFont font = new XFont("Verdana", 13, XFontStyle.Bold);
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
XSize size = gfx.MeasureString("Watermark", font);
gfx.TranslateTransform(pageActiveWidth / 2, pageActiveHeight / 2);
gfx.RotateTransform(-Math.Atan(pageActiveHeight / pageActiveWidth) * 180 / Math.PI);
gfx.TranslateTransform(-pageActiveWidth / 2, -pageActiveHeight / 2);
XStringFormat format = new XStringFormat();
format.Alignment = XStringAlignment.Near;
format.LineAlignment = XLineAlignment.Near;
XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
gfx.DrawString("Watermark", font, brush, new XPoint((pageActiveWidth - size.Width) / 2, (pageActiveHeight - size.Height) / 2), format);
docRenderer.RenderPage(gfx, idx + 1);
}
}
I was hoping that this would magically make these PDFSharp watermarks appear but alas I get nothing!
I have this working using the following code:
public byte[] render()
{
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = this.document;
renderer.RenderDocument();
renderer.PrepareRenderPages();
CreateWatermarks(renderer);
byte[] pdfContents = null;
using (MemoryStream stream = new MemoryStream())
{
renderer.PdfDocument.Save(stream, true);
pdfContents = stream.ToArray();
}
return pdfContents;
}
private void CreateWatermarks(PdfDocumentRenderer renderer)
{
int pages = renderer.DocumentRenderer.FormattedDocument.PageCount;
for (int i = 0; i < pages; ++i)
{
var page = renderer.PdfDocument.Pages[i];
XFont font = new XFont("Verdana", 27, XFontStyle.Bold);
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
XSize size = gfx.MeasureString("Watermark", font);
gfx.TranslateTransform(pageActiveWidth / 2, pageActiveHeight / 2);
gfx.RotateTransform(-Math.Atan(pageActiveHeight / pageActiveWidth) * 180 / Math.PI);
gfx.TranslateTransform(-pageActiveWidth / 2, -pageActiveHeight / 2);
XStringFormat format = new XStringFormat();
format.Alignment = XStringAlignment.Near;
format.LineAlignment = XLineAlignment.Near;
XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
gfx.DrawString("Watermark", font, brush, new XPoint((pageActiveWidth - size.Width) / 2, (pageActiveHeight - size.Height) / 2), format);
}
}

First Person Camera controls

I have recently started up a 3d first person shooter game in Monogame and I am having some issues with the camera controls, I am unable to figure out how I make the camera slowly turn on it's X axis when I hold down the left/right arrow keys.
At the minute, the code I have is as follows:
Matrix view = Matrix.CreateLookAt(new Vector3(60, 20, 10), new Vector3(0, 0, 0), Vector3.UnitZ);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 600f, 0.1f, 100f);
And then down in the update section I have this:
if (kb.IsKeyDown(Keys.Left))
{
view = Matrix.CreateLookAt(new Vector3(60, 20, 10), new Vector3(-2, -2, -2), Vector3.UnitZ);
}
The issue is at the minute this code simply moves the camera to the side a little then stops. I am unsure on how to keep having it move until I let go of the key?
The entire of my code will be shown below incase I forgot something (the floor verts currently don't work and the names related to a ship is due to me working from a tutorial):
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Game1
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Model model;
Vector3 ship1Location = new Vector3(40, 0, 0);
Vector3 ship2Location = new Vector3(20, 0, 0);
Matrix view = Matrix.CreateLookAt(new Vector3(60, 20, 10), new Vector3(0, 0, 0), Vector3.UnitZ);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 600f, 0.1f, 100f);
VertexPositionTexture[] floorVerts;
BasicEffect effect;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
floorVerts = new VertexPositionTexture[6];
floorVerts[0].Position = new Vector3(-20, -20, 0);
floorVerts[1].Position = new Vector3(-20, 20, 0);
floorVerts[2].Position = new Vector3(20, -20, 0);
floorVerts[3].Position = floorVerts[1].Position;
floorVerts[4].Position = new Vector3(20, 20, 0);
floorVerts[5].Position = floorVerts[2].Position;
effect = new BasicEffect(graphics.GraphicsDevice);
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
model = Content.Load<Model>("health2");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
Matrix ship1WorldMatrix = Matrix.CreateTranslation(ship1Location);
Matrix ship2WorldMatrix = Matrix.CreateTranslation(ship2Location);
if (IsCollision(model, ship1WorldMatrix, model, ship2WorldMatrix))
{
ship1Location = new Vector3(0, -20, 0);
}
KeyboardState kb = Keyboard.GetState();
if (kb.IsKeyDown(Keys.A))
{
ship1Location += new Vector3(-0.1f, 0, 0);
}
if (kb.IsKeyDown(Keys.Left))
{
view = Matrix.CreateLookAt(new Vector3(60, 20, 10), new Vector3(-2, -2, -2), Vector3.UnitZ);
}
ship2Location += new Vector3(0, 0, 0);
base.Update(gameTime);
}
private bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2)
{
for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++)
{
BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere;
sphere1 = sphere1.Transform(world1);
for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++)
{
BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere;
sphere2 = sphere2.Transform(world2);
if (sphere1.Intersects(sphere2))
return true;
}
}
return false;
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
DrawGround();
Matrix ship1WorldMatrix = Matrix.CreateTranslation(ship1Location);
Matrix ship2WorldMatrix = Matrix.CreateTranslation(ship2Location);
DrawModel(model, ship1WorldMatrix, view, projection);
DrawModel(model, ship2WorldMatrix, view, projection);
base.Draw(gameTime);
}
void DrawGround()
{
// The assignment of effect.View and effect.Projection
// are nearly identical to the code in the Model drawing code.
float aspectRatio =
graphics.PreferredBackBufferWidth / (float)graphics.PreferredBackBufferHeight;
float fieldOfView = Microsoft.Xna.Framework.MathHelper.PiOver4;
float nearClipPlane = 1;
float farClipPlane = 200;
effect.Projection = Matrix.CreatePerspectiveFieldOfView(
fieldOfView, aspectRatio, nearClipPlane, farClipPlane);
foreach (var pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
graphics.GraphicsDevice.DrawUserPrimitives(
// We’ll be rendering two trinalges
PrimitiveType.TriangleList,
// The array of verts that we want to render
floorVerts,
// The offset, which is 0 since we want to start
// at the beginning of the floorVerts array
0,
// The number of triangles to draw
2);
}
}
private void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.AmbientLightColor = new Vector3(2f, 0, 0);
effect.World = world;
effect.View = view;
effect.Projection = projection;
}
mesh.Draw();
}
}
}
}
Since the camera's position and the point it is looking at are necessary parameters to create a view matrix, you can simply rotate (think orbit) the LookAt camLookAt around the camPosition like this:
//declare class scope variables
Vector3 camPosition = new Vector3(60, 20, 10);//your starting camera position
Vector3 camLookAt = Vector3.Zero;//your starting camera focus point (look at)
Vector2 camUp = Vector3.Up;
float camYawRate = 0.004f;//set to taste
//in the Update method
float elapsed = gameTime.ElapsedGameTime.TotalSeconds;
//later in the method...
if (kb.IsKeyDown(Keys.Left))
{
camLookAt = Vector3.Transform(camLookAt - camPosition,Matrix.CreateRotationY(-camYawRate * elapsedTime)) + camPosition;);//remove the - sign from camYawRate to rotate to the right (or vice versa)
view = Matrix.CreateLookAt(camPosition, camLookAt, camUp);
}
And that's it, give it a shot. Add another similar block to rotate to the right.

How do you convert a Uint8ClampedArray string to an android Bitmap?

Im using a custom WebView component in android to display an html page with HTML5 canvas.
Due to lack of WebView support for the getDataUrl from canvas function,
im passing the getImageData.data Uint8ClampedArray to webview through web view JavascriptInterface.
It saves the images as a dark blue image. Any ideias?
// html
...canvas id="canvas" width="20px" height="20px"...
// javascript
imgData=context.getImageData(0,0,20,20);
webViewArray = Array.prototype.slice.call(imgData.data);
webviewApp.procData(webViewArraySTRING);
// android
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int[] results = new int[1600];
int[] icnt = 0;
int width = 20;
int height = 20;
int pos = 0, end;
while((end = webViewArraySTRING.indexOf(',', pos)) >= 0) {
results[icnt] = Integer.parseInt(webViewArraySTRING.substring(pos,end));
pos = end + 1;
icnt++;
}
// create image - tried using ARGB_8888, ARGB_4444
System.out.println("results size:" + icnt); // prints out 1599
Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.RGB_565);
bitmap.setPixels(results, 0, width, 0, 0, width, height);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
// save image `
FileOutputStream os = new FileOutputStream(file,true);
os.write(boas.toByteArray());

Special character doesn't appear the same on windows phone emulator and real device

my problem is a bit strange!! I'm going to create a calendar tile with writable bitmap for windows phone 8. so I'm using this character "📆".
I'm using the below code and everything works fine as I expected on emulator. but when I test my app on a real device,calendar character will be appeared different
private void RenderText9()
{
int width = 159;
int height = 159;
string imagename = "SmallBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var background = new Canvas();
background.Height = b.PixelHeight;
background.Width = b.PixelWidth;
SolidColorBrush backColor = new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"]);
background.Background = backColor;
var textBlock = new TextBlock();
textBlock.Text = "25";
textBlock.TextAlignment = TextAlignment.Center;
textBlock.Margin = new Thickness(0, 72, 0, 0);
textBlock.Width = 159;
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Foreground = new SolidColorBrush(Colors.White);
textBlock.FontSize = 35;
var textBlock2 = new TextBlock();
textBlock2.Text = "📆";
textBlock2.TextAlignment = TextAlignment.Center;
textBlock2.Margin = new Thickness(0, 40, 0, 0);
textBlock2.Width = 159;
textBlock2.TextWrapping = TextWrapping.Wrap;
textBlock2.Foreground = new SolidColorBrush(Colors.White); //color of the text on the Tile
textBlock2.FontSize = 75;
canvas.Children.Add(textBlock);
canvas.Children.Add(textBlock2);
b.Render(background, null);
b.Render(canvas, null);
b.Invalidate(); //Draw bitmap
//Save bitmap as jpeg file in Isolated Storage
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/" + imagename + ".jpg", System.IO.FileMode.Create, isf))
{
b.SaveJpeg(imageStream, b.PixelWidth, b.PixelHeight, 0, 100);
}
}
}
this is the tile on both emulator and real device(pay attention to difference).
anybody knows any solution??? I don't understand the reason !!

Generate Image as byte[] in WinRT with SharpDX

I'm trying to generate a simple image and display it in WinRT/XAML.
For that I want the byte[] of an image drawn with SharpDX.
My Approach so far seems fine but the resulting buffer is empty.
I tried CopyPixels as well but it also only produced zeros.
Can somebody point me in the right direction?
private static byte[] Draw(TexRenderer trnder, int width, int height)
{
var wicFactory = new ImagingFactory();
var dddFactory = new SharpDX.Direct2D1.Factory();
var dwFactory = new SharpDX.DirectWrite.Factory();
var wicBitmap = new Bitmap(
wicFactory,
width,
height,
SharpDX.WIC.PixelFormat.Format32bppBGR,
BitmapCreateCacheOption.CacheOnLoad);
var renderTargetProperties = new RenderTargetProperties(
RenderTargetType.Default,
new SharpDX.Direct2D1.PixelFormat(Format.Unknown, AlphaMode.Unknown),
dddFactory.DesktopDpi.Width,
dddFactory.DesktopDpi.Height,
RenderTargetUsage.None,
FeatureLevel.Level_DEFAULT);
var renderTarget = new WicRenderTarget(
dddFactory,
wicBitmap,
renderTargetProperties)
{
TextAntialiasMode = TextAntialiasMode.Cleartype
};
renderTarget.BeginDraw();
var textFormat = new TextFormat(dwFactory, "Consolas", 48)
{
TextAlignment = TextAlignment.Center,
ParagraphAlignment = ParagraphAlignment.Center
};
var textBrush = new SolidColorBrush(
renderTarget,
Color.Blue);
renderTarget.Clear(Color.White);
renderTarget.DrawText(
"Hi, mom!",
textFormat,
new RectangleF(0, 0, width, height),
textBrush);
var bitmapRenderTarget = new BitmapRenderTarget(renderTarget, CompatibleRenderTargetOptions.None);
trnder.Render(bitmapRenderTarget, 0, 0);
renderTarget.EndDraw();
var bitmaplock = wicBitmap.Lock(null, BitmapLockFlags.Read);
var dStream = new DataStream(bitmaplock.Data.DataPointer, bitmaplock.Stride * bitmaplock.Size.Height, true, true);
var buffer = new byte[bitmaplock.Stride * bitmaplock.Size.Height];
dStream.Write(buffer, 0, buffer.Length);
return buffer;
}
I run in the same issue, i need acces to the raw texture data for phisics
DataStream dataStream = new DataStream(source.Size.Height * source.Size.Width, true, true);
bitmapSource.CopyPixels( source.Size.Width * sizeof(uint), dataStream);
var data = dataStream.ReadRange<uint>(source.Size.Width * source.Size.Height);
on the forums SharpDX forumsformore details