How do I draw a 3D model using sharpDX? - draw

How do I draw a 3D model using sharpDX? Most examples on the web just say that I can't without some other library. My models are in .fbx format and the build action properties are ToolkitModel.

SharpDX used to come with a namespace called SharpDX.Toolkit.Graphics. In the more recent versions it has been deprecated in favour of Monogame and Xenko. https://github.com/sharpdx/Toolkit
The code to draw a model looks as follows:
using SharpDX.Toolkit;
using SharpDX.Toolkit.Content;
using SharpDX.Toolkit.Graphics;
...
protected override void LoadContent() {
//...
model = Content.Load<Model>("mymodel");
//...
}
...
protected override void Draw(GameTime gameTime){
//...
var view = Matrix.LookAtRH(cameraPos, modelPos, cameraUp);
var proj = Matrix.PerspectiveFovLH(fov, aspect, near, far);
var world = //arbitrary model position.
Matrix.Scaling(0.1f)*
Matrix.RotationY(Util.fPi/2)*
Matrix.Translation(modelPos);
model.Draw(GraphicsDevice, world, view, proj);
//...
}

Related

How to display Orchard shape only once?

I have a common shape that renders some HTML code to display an error dialog.
The HTML code needs to be included only once throughout the whole web site. For scripts and styles Orchard provides the Script.Include() and Style.Include() methods.
I wonder whether there is something similar for HTML code, any ideas?
So many options to do this
Can you add your code to Layout.cshtml in the theme
Create a new widget and attach the shape field then create it on the default layer (so on all pages) with the name of your shape in the shape field
Add the shape in a filter, or anywhere else you have access to the WorkContext :)
Code written from memory, may not compile
using System.Linq;
using System.Web.Mvc;
using Orchard;
using Orchard.DisplayManagement;
using Orchard.Mvc.Filters;
using Orchard.UI.Admin;
public class MyFilter : FilterProvider, IResultProvider {
private readonly dynamic _shapeFactory;
private readonly WorkContext _workContext;
public MyFilter(WorkContext workContext, IShapeFactory shapeFactory)
{
_workContext = workContext;
_shapeFactory = shapeFactory;
}
public void OnResultExecuting(ResultExecutingContext filterContext)
{
// should only run on a full view rendering result
if (!(filterContext.Result is ViewResult)) return;
// front end only
if (AdminFilter.IsApplied(new RequestContext(_workContext.HttpContext, new RouteData()))) return;
var body = _workContext.Layout.Body;
body.Add(_shapeFactory.MyShape());
}
public void OnResultExecuted(ResultExecutedContext filterContext) {}
}

Error 1119 when trying to access properties of the graphic which is an Image in flashpunk?

I created a new entity and defined the entities graphic as a new Image from an embedded image files.
graphic = new Image(PLAYER);
PLAYER is an embedded image, now since graphic is this image now, I should be able to do things like centerOrigin() or angle(), but I can't? It worked in the Flash IDE but now that i've switched to Flash Builder for using flashpunk, It gives me an error 1119, cannot access property centerOrigin() through static type net.flashpunk:Graphic.
What am I doing wrong? A lot of tutorials say it should work. If it is supposed to work but the problem is the environment and not my program, what is a workaround?
Here's my actual code:
public class Projectile extends Entity{
public var bearingIN:Number;
public var speedIN:Number;
public function Projectile(bearing,speed,gunX,gunY) {
setHitbox(2,2);
bearingIN = bearing;
speedIN = speed;
graphic = new Image(new BitmapData(8,1,false,0xFFFF32));
type = "projectile";
graphic.centerOrigin();
graphic.angle = (bearing / (Math.PI/180))*-1;
layer = 255
x = gunX + 16;
y = gunY + 16;
addTween(new Alarm(20,removeProj,2), true);
}
private function removeProj(){
FP.world.remove(this);
}
public override function update():void{
x += Math.cos(bearingIN)*speedIN;
y += Math.sin(bearingIN)*speedIN;
if(collide("wall",x,y)){
removeProj();
}
}
}
The graphic property of the Entity class is of type Graphic. However, the Graphic class has no method called centerOrigin only Image does. So you need to cast it. Do this for the line with centerOrigin():
((Image)graphic).centerOrigin();
You'll have to do the same thing for angle as well.

Application Design Patterns AS3

just thought I would share something I have found to help delivering data across an application I am wondering what others think about this I wanted to have a way to capture event bubbling up back down to other components but in a way that it would make it easy to use anywhere in may app so this is what i came up with.
I Extend the Application class and wrap in an abstract function registering a function of any component anywhere and capture it at the top most level and pass to where ever i chose to.
public class AxApplication extends Application
{
public var ___registeredEvents:Array = new Array();
public var ___registeredFunctions:Array = new Array();
function AxApplication()
{
super();
}
public function localRegisterForEvent(e:Event,func:*,caller:*):void
{
caller.addEventListener(e.type,localCallerEventHandler,true,3);
caller.addEventListener(e.type,localCallerEventHandler,false,3);
___registeredEvents.push(e);
___registeredFunctions.push(func);
}
public function localCallerEventHandler(e:*):void
{
if(e!=null)
{
for(var i:int = 0 ; i< ___registeredEvents.length; i++)
{
if(e.type == ___registeredEvents[i].type)
{
___registeredFunctions[i](e);
//the registered function gets called
//there no garbage collection implemented!
}
}
}
}
}
I think that is not a very useful solution. Why? Because you scatter AxApplication references around the application. Views and Model instance don't need any references to the application at all. It would be better to to implement a controller layer which uses a simple eventBus property, which could look like:
private static const _EVENT_BUS:IEventDispatcher = FlexGlobals.topLevelApplication;
protected final function eventBus():IEventDispatcher {
return _EVENT_BUS;
}
If you implement a base view controller/mediator (depending from which framework you're coming), you don't have any reference to non-framework classes at all, which makes it highly reusable. It is just a simple reuse of the Application singleton which you use to dispatch system wide events. You register listeners in the view controller/mediator and update the views or models accordingly. RobotLegs for example uses a system wide event dispatcher as well.
Why not just using the parentApplication approach? Because you can't implement tests (the generated test-runner of IDEs won't extend your AxApplication) or just yank the components/models in a different application - that is basically not possible.

Library design quandary

Ok so I am writing an open source library. A section of this library deals with moving an entity in a two and three dimensional space so it will have functions that manipulate the rotation, position etc.
Now ideally I would like my library to work well with other libraries, in particular things like Papervision3D and other Flash 3D engines, but not forgotting basic image objects like a Sprite or Movieclip.
So this is my quandary. The functions that will manipulate the entity will also need to modify the values of the underlying model data (so either a Sprite, Papervision object etc). What is the best way to make my library flexible so that it can support multiple data models. Performance is also important aspect too.
Currently I am thinking of something like this:
//this is the public function that I expose in my library
public function rotate(val:Number,func:Function,objData:*):void
{
func(val,objData);
}
//example of a function that could be passed in
//this one will rotate a MovieClip
private function modelFunction1(rot:Number,objData:*):void
{
var myMov:MovieClip = objData as MovieClip;
myMov.rotation = rot;
}
//second example of a function that could be pass in
//this one will rotate a point
private function modelFunction2(rot:Number,objData:*):void
{
//yes I know this piece of code makes no sense :P
var p:Point = objData as Point;
p.x = Math.cos(rot);
p.y = Math.sin(rot);
}
so then it could be used like:
rotate(4,modelFunction2,myPoint)
//or
rotate(4,modelFunction1,mySprite);
I should add that in reality I, as the client code, won't be able to directly call the rotate function. Instead the rotate function that I want to pass in would need to be stored somewhere as a class member and then be called by the rotate function. Its just less code for me to write it out like above.
This to me seems quite flexible although the performance implications of casting and passing functions concerns me (but might be ok). Can anyone else suggest an alternative or is what I have the most logical solution. Thanks :)
I suggest the adapter pattern.
In your case you could define interfaces which offer type safe definitions for what your library expects instead of having function arguments.
then you need to write adapter classes which implement your librarys interfaces and wrap for instance a papervision object and delegate the function calls to your interface methods to the papervision object.
interface IRotatatable {
function rotate(deg : Number) : void
}
class YourLibraryClass {
public function rotate(r : IRotatatable, val : Number):void {
r.rotate(val)
}
}
class P3DAdapter implements IRotatable {
public function P3DAdapter(p3d : SomePaperVisionObject) {
_p3d = p3d;
}
public function rotate(r :Number):void {
p3d.rot = r;
}
}
function someClientCode():void {
var adapter : IRotatable = new P3DAdapter(p3d)
new SomeLibraryClass().rotate(adapter, val));
}

Howto embed images in Actionscript 3 / Flex 3 the right way?

I'm creating a game where a lot of images are being used in Actionscript / Flex 3 (Flash). Now that I've reached the designer stage, I have to work out a structural way of using embedded images (which have to be manipulated with rotation, color, etc.).
Unfortunately, after investigating a bit, it looks like you have to manually embed images before you can use them. I currently have it setup like this:
Resource.as class file:
package
{
public final class Resource
{
[Embed (source="/assets/ships/1.gif" )]
public static const SHIPS_1:Class;
}
}
So, just for one ship I so for have to:
Put the image in the correct folder with the correct name
Name it in the same way in the Resource.as file
Create the constant with the same name in the Resource.as file
Even though this should all be possible by simply putting the file in a specified folder.
To make things even worse, I still have to call it using:
var test:Bitmap = new Resource.SHIPS_1();
There must be better ways to handle resources when creating very huge applications? Imagine I need thousands of images, this system simply wouldn't fit.
If you need to handle a large number of resources you can follow these 3 steps:
Place them in an uncompressed zip archive
Embed the zip file as binary data:
[Embed(source = 'resources.zip', mimeType = 'application/octet-stream')]
Access the resources using FZip
If you choose a different method that involves loading external files be aware that some flash game websites require the games they host to be contained within a single swf file.
instead of
var test:Bitmap = new Resource.SHIPS_1();
Use
myImage.source = Resource.SHIPS_1;
The embedding is correct. :D the way you use it is wrong :)
Adrian
This is really what Flash CS4 is for. Your way seems fine to me though - although I wouldn't use all caps for a class name even if it is a constant. Just put your head down and get copy-pasting!
Alternatively you could load the files at runtime.
This is old but since I stumbled across it searching for something different I'll write here for future generations : )
I use a different approach. I create a swf movie with flash professional and import all graphics in it and then mark them all for "Export for ActionScript".
Compile the swf and in your main project embed only the swf and access all the graphics through it...
I find this approach much more organized. Why write the whole resources class when you can make it by importing files right? ;)
I just watched this great tutorial on the Starling framework:
http://www.hsharma.com/tutorials/starting-with-starling-ep-3-sprite-sheets/
It sounds like spritesheets are exactly what you're looking for:
You bundle all your individual textures into one big texture that is called spritesheet and create an xml file that contains information where the textures are within the spritesheet. In order to do that you can use this tool:
http://www.codeandweb.com/texturepacker
I'm not sure if you can use it for commercial projects and the amount of textures you're speaking of doesn't sound like you're doing this just as a hobby, so you might want to check the license. There's a pro version available, too.
Texturepacker creates two files: spritesheet.png and spritesheet.xml. You just copy them into your project.
Then you add this code to one of your classes.
private static var gameTextureAtlas:TextureAtlas;
[Embed(source="../media/graphics/mySpriteSheet.png")]
public static const AtlasTextureGame:Class;
[Embed(source="../media/graphics/mySpritesheet.xml", mimeType="application/octet-stream")]
public static const AtlasXmlGame:Class;
public static function getAtlas():TextureAtlas
{
if(gameTextureAtlas==null)
{
var texture:Texture=getTexture("AtlasTextureGame");
var xml:XML=XML(new AtlasXmlGame());
gameTextureAtlas=new TextureAtlas(texture,xml);
}
return gameTextureAtlas;
}
Now you can access all the textures of the spritesheet by calling
YourClass.getAtlas().getTexture("name");
It's simply awesome. When you're using texturepacker the filename of each of the sprites you bundled into the spritesheet becomes its texturename.
This is probably too late to help you, but I hope that future visitors can profit from this elegant solution.
I would like to emphasize that this answer is basically an excerpt from sharma's tutorial. I even felt free to reproduce the code he used in his screencast. All the credit goes to him
It depends how big your individual images are but you could put them all in one image like a spritesheet. If you want to draw a particular ship use the correct xy offset in the image for that ship and use copyPixels to draw it to your bitmap.
package
{
public final class Resource
{
[Embed (source="/assets/ships/1.gif" )]
public static const SHIPS_1:Class;
}
}
[Embed (source="/assets/ships/1.gif" )]
public static const SHIPS_1:Class;
I like to do my Library classes like this.
I took GSkinners code for the singleton: http://gskinner.com/blog/archives/2006/07/as3_singletons.html
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
public class Lib
{
/*
Make this an Singleton, so you only load all the images only Once
*/
private static var instance:Lib;
public static function getInstance():Lib {
if (instance == null) {
instance = new Lib(new SingletonBlocker());
}
return instance;
}
public function Lib(p_key:SingletonBlocker):void {
// this shouldn't be necessary unless they fake out the compiler:
if (p_key == null) {
throw new Error("Error: Instantiation failed: Use Singleton.getInstance() instead of new.");
}
}
/*
The actual embedding
*/
[Embed(source="assets/images/someImage.png")]
private var ImageClass:Class;
private var _imageClass:Bitmap = new ImageClass() as Bitmap;
[Embed(source="assets/images/someOtherImage.png")]
private var OtherImageClass:Class;
private var _otherImageClass:Bitmap = new ImageClass() as Bitmap;
public function get imgClass():Bitmap{
return _imageClass;
}
public function get imgClassData():BitmapData{
return _imageClass.BitmapData;
}
public function get otherImageClass():Bitmap{
return _otherImageClass;
}
public function get otherImageClassData():BitmapData{
return _otherImageClass.BitmapData;
}
}
}
internal class SingletonBlocker {}
[Embed (source="/assets/images/123.png" )]
public static const className:Class;
Good idea, lhk
That is nice solution like Source-Engine with vtf and vmt
vtf = image
vmt = script ( like xml or javascript )
Good i would like to suggest for TexturePacker, TexturePath or TextureTarget :P
Thanky ou for tip.
For example:
mytexture.js:
xml or javascript:
function mytexture(){ basedir = "/assets/mytexture.png", normalmap =
"/assets/mytexture_bump.png", normalcube ) [ 1, 1, 1 ] };
I don't think because default texture gets error somewhere mytexture.png doesn't exists than it happens again :)
[Embed(source="../assets/editors/error_texture.png")] public static
const ERROR_TEX:Class; ...
How do i know because Actionscript 3 should "read" to javascript like jsBirdge or ExternalInterface.call();
Is it possible?