How to structure AngularJS and PaperJS project - html

The idea is to make use of Angular in a simple canvas game development. In theory the project should benefit from being more systematic, manageable and scalable. This is not a sprite/tile/collision game and PaperJS is used to do most canvas drawing and interactions.
What is the best approach to integrate Paper.js (or other canvas drawing library) into multiple NG views, in order to have each view representing a game stage?
Is it possible to setup Paper once and use paper across multiple views?
The game allows user to revisit previous stages/views. Do I have to re-setup Paper every time the view/canvas loads? (Shown in example below, if only setup once a blank canvas will appear on view's second visit)
How do I transfer Paper js information between views? e.g. captures user drawing in view 1, and display drawing in view 3.
Background:
Paper JS
I'm working on a project to create a simple canvas game with 4 stages. I decided to use PaperJS for its advantage for drawing and animating shapes. Content and ui for each stage is kept in a separate layer within the same paper project.
Angular JS
The game has become more complicated as it develops. After some research, I decided to use Angular to organise the whole game, although I'm new to Angular. The plan:
The 4 game stages are split into four views, each has its own canvas
Custom directives are used to setup paper on each canvas
Using service for communication between canvases. For example allow users to draw in stage one and display drawing in stage two
I have made a mock up in plunker showing the basic setup and animation with Paper.js. Each canvas sits in a separate view with routing enabled.
Plunker demo: http://plnkr.co/edit/Um1jTp8xTmAzVEdzk2Oq?p=preview
For testing sake, I have made
paper.project.layers[0].children
visible anytime. After a paper is setup, firing "add shapes" button would introduce children to the active layer as expected.
Problem 1 (Draw1 in demo)
In DRAW1, paper will only setup once on the canvas when the view first loads:
drawControllers.directive('drawingBoard',['drawService',function(drawService){
function link(scope, element, attrs){
// setup Paper
var canvas = element[0];
if ( scope.objectValue.count < 1){
paper = new paper.PaperScope();
paper.setup(canvas);
scope.setCount( scope.objectValue.count + 1 );
with (paper) {
var shape = new Shape.Circle(new Point(200, 200), 200);
shape.strokeColor = 'black';
shape.fillColor = 'yellow';
// Display data in canvas
var text = new PointText(new Point(20, 20));
text.justification = 'left';
text.fillColor = 'black';
var text2 = new PointText(new Point(200, 200));
text2.justification = 'center';
text2.fillColor = 'black';
text2.content = 'click to change size';
shape.onClick = function(event) {
this.fillColor = 'orange';
scope.$apply(function () {
scope.setWidth(Math.round((Math.random()*100)+100));
});
}
view.onFrame = function(event) {
if ( text.position.x > 440 ){
text.position.x = -40;
} else {
text.position.x = text.position.x + 3;
}
text.content = 'Shape width: ' + scope.objectValue.width;
shape.radius = scope.objectValue.width;
scope.$apply(function () {
scope.setMessage();
});
}
paper.view.draw();
}
} else {
scope.setMessage();
}
}
return {
link: link
}
}]);
However, if navigate from DRAW1 to HOME and back to DRAW1, the canvas would appear blank. But firing "add shapes" at this point would still create new children to the layer.
Problem 2 (DRAW2 in demo)
By removing this line
if ( scope.objectValue.count < 1){
// ... paper setup ...
}
Paper will setup in DRAW2 every time it loads.
But that introduces a new paper project every time.
Thank you
Thank you for any advice and suggestions.

You are creating new paper project inside the link function, which runs every time for every new use of your directive, in particular, every time a new view is generated.
If you want it to run only once, you can put it in the directive's compile function, or inside a dedicated Angular service or don't close/re-open the view.
The latter can be done simply using ng-show/ng-hide keeping the views inside your DOM instead of changing the routes: https://stackoverflow.com/a/26820013/1614973.

Related

After several times loading an object in THREE.js, the page crashes

I have a few buttons in my app which load a new object onto the scene when clicked. Below is the code being used for loading new objects:
character = new THREE.UCSCharacter();
var ucspath = "skinnedModel.json";
manager = new THREE.LoadingManager();
manager.onProgress = function(url, itemsLoaded, itemsTotal) {
console.log(url, itemsLoaded, itemsTotal);
};
var onProgress = function (xhr){
if(xhr.lengthComputable){
var bar = 150;
percentComplete = xhr.loaded / xhr.total * 100;
bar = Math.floor( xhr.loaded / xhr.total * bar );
document.getElementById("bar").style.width = bar + "px";
}
};
var loader = new THREE.XHRLoader(manager);
loader.crossOrigin = true;
loader.load(ucspath, function (text) {
var config = JSON.parse(text);
character.loadParts(config);
avatar = character.root;
avatar.name = "female";
scene.add(avatar);
}, onProgress);
After clicking the button 10~12 times, the loading becomes increasingly slow and eventually the page crashes. I could not detect any unsual behavior using Chrome DevTools.
Is there something that needs to be done in order to load as many objects as desired without overloading the browser?
[Update] Heap Snapshot
Thanks in advance.
It seems that you're facing a performance issue caused by your model file.
Fortunately, the problem of a having a huge model replicated with different traits is very common in the game industry so I can give you an hint though it's not that simple :
In your 3D editor, merge all of your different geometries into one single model and give to each of your model parts an easy name like hair_01, head_02, beard_03, ...
Load this model in your Three.js app just once. This is your template model.
Now, when you want to create a new model with a different appearance :
Clone the template model ;
Hide the parts you don't want ;
Show the parts you want.
Here's an example of the idea :
var copy = template.clone();
copy.getObjectByName('head_01').visible = false;
copy.getObjectByName('head_02').visible = true;
scene.add(copy);
Cloning the model prevents the engine from duplicating all geometry data (*).
This is a picture of a single 3D model file from an existing game that contains every character geometries and switch them in runtime to give a humanoid various appearances.
*See THREE.Mesh.clone()

Leaflet 0.7.7 Zoombased layer switching separated by theme

We are working on a school project where the aim is to create a map in which based on the amount of zoom the layer switches from one aggregate level to a smaller aggregate level. Additionally, we have several groups of layers based on a theme for which this needs to apply. So you'd click on a theme and a new group of layers that switches based on zoom level become active and when you click another theme another group of layers become active and switch based on zoom level. This means that the themes are exclusionary, ideally you can't have more than one theme active at a time.
We tried to make this work in several ways already but without much success. Using the L.Control.Layers we were unable to group different layers together under one radio button and have them switch based on zoom since the layer control build into leaflet always splits them up into separate ones. Even using L.layerGroup to combine several layer variables or creating several layers into one variable and then adding them to the map using l.control.layer.
We also tried to use L.easyButton (https://github.com/CliffCloud/Leaflet.EasyButton). This allowed us to put the variables under one button and add a zoom based layer switching inside of it. However, the issue here is that we are unable to deactivate the functionality once activated. Which results in several of them being active at one point and overlapping each other.
If possible we would like to know if we should use a different approach or if either the leaflet control function or the use of easyButton could work and how?
This is example code for one of the buttons, which would appear several times but show a different theme:
L.easyButton( '<span class="star">&starf;</span>', function (polygon) {
var ejerlav_polygon = new L.tileLayer.betterWms(
'http://[IP]:[PORT]/geoserver/prlayer/wms', {
layers: 'prlayer:ejerlav',
transparent: true,
styles: 'polygon',
format: 'image/png'});
var municipality_polygon = new L.tileLayer.betterWms(
'http://[IP]:[PORT]/geoserver/prlayer/wms', {
layers: 'prlayer:municipality',
transparent: true,
styles: 'polygon',
format: 'image/png'});
map.on("zoomend", function() {
if (map.getZoom() <= 10 && map.getZoom() >= 2) {
map.addLayer(municipality_polygon);
} else if (map.getZoom() > 10 || map.getZoom() < 2) {
map.removeLayer(municipality_polygon);
}
});
map.on("zoomend", function() {
if (map.getZoom() <= 11 && map.getZoom() >= 11) {
map.addLayer(ejerlav_polygon);
} else if (map.getZoom() > 11 || map.getZoom() < 11) {
map.removeLayer(ejerlav_polygon);
}
});
}).addTo(map);
If my understanding is correct, you would like to give the user the ability to switch between "themes" (some sort of group of layers that switch themselves based on the map current zoom level), possibly using Leaflet Layers Control?
And regarding the switch based on map zoom, you cannot just change the Tile Layer template URL because you use some WMS?
As for the latter functionality (switching layers within a group / theme based on map zoom), a "simple" solution would be to create your own type of layer that will listen to map "zoomend" event and change the Tile Layer WMS accordingly.
L.LayerSwitchByZoom = L.Class.extend({
initialize: function (layersArray) {
var self = this;
this._layersByZoom = layersArray;
this._maxZoom = layersArray.length - 1;
this._switchByZoomReferenced = function () {
self._switchByZoom();
};
},
onAdd: function (map) {
this._map = map;
map.on("zoomend", this._switchByZoomReferenced);
this._switchByZoom();
},
onRemove: function (map) {
map.off("zoomend", this._switchByZoomReferenced);
this._removeCurrentLayer();
this._map = null;
},
addTo: function (map) {
map.addLayer(this);
return this;
},
_switchByZoom: function () {
var map = this._map,
z = Math.min(map.getZoom(), this._maxZoom);
this._removeCurrentLayer();
this._currentLayer = this._layersByZoom[z];
map.addLayer(this._currentLayer);
},
_removeCurrentLayer: function () {
if (this._currentLayer) {
map.removeLayer(this._currentLayer);
}
}
});
You would then instantiate that layer "theme" / group by specifying an array of layers (your Tile Layers WMS), where the array index corresponds to the zoom level at which that Tile Layer should appear.
var myLayerSwitchByZoomA = new L.LayerSwitchByZoom([
osmMapnik, // zoom 0, osmMapnik is a Tile Layer or any other layer
osmDE, // zoom 1
osmFR, // zoom 2
osmHOT // zoom 3, etc.
]);
Once this new layer type is set, you can use it in the Layers Control like any other type of Layer / Tile Layer, etc.
L.control.layers({
"OpenStreetMap": myLayerSwitchByZoomA,
"ThunderForest": myLayerSwitchByZoomB
}).addTo(map);
Demo: http://jsfiddle.net/ve2huzxw/85/
Note that you could further improve the implementation of L.LayerSwitchByZoom to avoid flickering when changing the layer after zoom end, etc.

Printing in Actionscript 3

How would I go about making a print screen run in flash. So when a user has arranged some artwork via a drag and drop flash/app - they click a button to 'Print' and there current design activates a printer?
Is this straight forward?
Thanks
I had a similar project and managed with something like the following example:
//creating a container as main canvas
var artworkContainers:Sprite = new Sprite();
addChild(artworkContainers);
//example adding content
var anyContentIWantToPrint:Sprite = new Sprite();
anyContentIWantToPrint.graphics.beginFill(0xf67821, 1);
anyContentIWantToPrint.graphics.drawRect(0, 0, 100, 100);
anyContentIWantToPrint.graphics.endFill();
artworkContainers.addChild(anyContentIWantToPrint);
var button:Sprite = new Sprite();
button.graphics.beginFill(0xf67821, 1);
button.graphics.drawRect(0, 0, 120, 60);
button.graphics.endFill();
addChild(button);
button.addEventListener(MouseEvent.CLICK, startPrintJobHandler, false, 0, true);
function startPrintJobHandler(event:MouseEvent):void
{
var printJob:PrintJob = new PrintJob();
printJob.start()
var printJobOptions:PrintJobOptions = new PrintJobOptions();
printJobOptions.printAsBitmap = true;
//When 'artworkContainer' will be your artwork canvas, where the user will drag and drop. Replace for the instance name you are using.
printJob.addPage(artworkContainer, null, printJobOptions);
printJob.send();
}
You can check out the PrintJob class.
You use the FlexPrintJob class to print one or more Flex objects, such as a Form or VBox container. For each object that you specify, Flex prints the object and all objects that it contains. The objects can be all or part of the displayed interface, or they can be components that format data specifically for printing. The FlexPrintJob class lets you scale the output to fit the page, and automatically uses multiple pages to print an object that does not fit on a single page.
You use the FlexPrintJob class to print a dynamically rendered
document that you format specifically for printing. This capability is
especially useful for rendering and printing such information as
receipts, itineraries, and other displays that contain external
dynamic content, such as database content and dynamic text.
You often use the FlexPrintJob class within an event listener. For
example, you can use a Button control with an event listener that
prints some or all of the application.
Note: The FlexPrintJob class causes the operating system to display a
Print dialog box. You cannot print without some user action.
Here is an example from Adobe's Live Docs.
private function doPrint():void {
// Create an instance of the FlexPrintJob class.
var printJob:FlexPrintJob = new FlexPrintJob();
// Start the print job.
if (printJob.start() != true) return;
// Add the object to print. Do not scale it.
printJob.addObject(myDataGrid, FlexPrintJobScaleType.NONE);
// Send the job to the printer.
printJob.send();
}
You probably want to look at the PrintJob functionality. You can add and arrange pages, etc. Examples on the Adobe help page.

How can I move bones of a loaded asset programmatically in Away3D?

I'm loading a 3D asset into a Away3D scene and I'd like to move the position of the bones in code.
The asset loading all goes well, I grab a pointer to the Mesh and Skeleton while loading:
private function onAssetComplete(evt:AssetEvent):void
{
if(evt.asset.assetType == AssetType.SKELETON){
_skeleton = evt.asset as Skeleton;
} else if (evt.asset.assetType == AssetType.MESH) {
_mesh = evt.asset as Mesh;
}
}
After the asset(s) have finished loading, I have a valid Skeleton and Mesh instance, the model is also visible in my scene. The next thing I tried is the following.
// create a matrix with the desired joint (bone) position
var pos:Matrix3D = new Matrix3D();
pos.position = new Vector3D(60, 0, 0);
pos.invert();
// get the joint I'd like to modifiy. The bone is named "left"
var joint:SkeletonJoint = _skeleton.jointFromName("left");
// assign joint position
joint.inverseBindPose = pos.rawData;
This code runs without error, but the new position isn't being applied to the visible geometry, eg. the position of the bone doesn't change at all.
Is there an additional step I'm missing here? Do I have to re-assign the skeleton to the Mesh somehow? Or do I have to explicitly tell the mesh that the bone positions have changed?
This might not be the best way to solve this, but here's what I figured out:
Away3D only applies joint transformations to the geometry when an animation is present. In order to apply your transforms, your geometry must have an animation or you'll have to create an animation in code. Here's how you do that (preferably in your LoaderEvent.RESOURCE_COMPLETE handler method:
// create a new pose for the skeleton
var rootPose:SkeletonPose = new SkeletonPose();
// add all the joints to the pose
// the _skeleton member is being assigned during the loading phase where you
// look for AssetType.SKELETON inside a AssetEvent.ASSET_COMPLETE listener
for each(var joint:SkeletonJoint in _skeleton.joints){
var m:Matrix3D = new Matrix3D(joint.inverseBindPose);
m.invert();
var p:JointPose = new JointPose();
p.translation = m.transformVector(p.translation);
p.orientation.fromMatrix(m);
rootPose.jointPoses.push(p);
}
// create idle animation clip by adding the root pose twice
var clip:SkeletonClipNode = new SkeletonClipNode();
clip.addFrame(rootPose, 1000);
clip.addFrame(rootPose, 1000);
clip.name = "idle";
// build animation set
var animSet:SkeletonAnimationSet = new SkeletonAnimationSet(3);
animSet.addAnimation(clip);
// setup animator with set and skeleton
var animator:SkeletonAnimator = new SkeletonAnimator(animSet, _skeleton);
// assign the newly created animator to your Mesh.
// This example assumes that you grabbed the pointer to _myMesh during the
// asset loading stage (by looking for AssetType.MESH)
_myMesh.animator = animator;
// run the animation
animator.play("idle");
// it's best to keep a member that points to your pose for
// further modification
_myPose = rootPose;
After that initialization step, you can modify your joint poses dynamically (you alter the position by modifying the translation property and the rotation by altering the orientation property). Example:
_myPose.jointPoses[2].translation.x = 100;
If you don't know the indices of your joints and rather address bones by name, this should work:
var jointIndex:int = _skeleton.jointIndexFromName("myBoneName");
_myPose.jointPoses[jointIndex].translation.y = 10;
If you use the name-lookup frequently (say every frame) and you have a lot of bones in your model, it's advisable to build a Dictionary where you can look up bone indices by name. The reason for this is that the implementation of jointIndexFromName performs a linear search through all joints which is wasteful if you do this multiple times.

away3d change 3ds mesh material on run-time

I'am trying to figure out how to change material on loaded 3ds object/mesh during run-time after mouse click.
(Away3D 3.5/3.6)
3ds object is loaded with Loader3D:
//global mesh variable and view3d
var my_mesh:Mesh;
var view:View3D = new View3D();
//creating a parser with initial material
var max3ds_parser:Max3DS = new Max3DS();
max3ds_parser.material = new WireColorMaterial(0xFF0000);
var loader:Loader3D = new Loader3D();
loader.addEventListener(Loader3DEvent.ON_SUCCESS, onSuccess);
loader.loadGeometry("myMesh.3ds", max3ds_parser);
addChild(view);
addEventListener(Event.ENTER_FRAME, onEnterFrameRenderScene);
function onSuccess(e:Loader3DEvent):void{
my_mesh = Mesh(e.loader.handle);
view.scene.addChild(my_mesh)
}
function onEnterFrameRenderScene(e:Event):void{
my_mesh.rotationY += 15;
view.render();
}
So, after all this the 3ds object is added to the scene with initial material (WireColorMaterial) applied with parser object. But now I want to change the initial material after mouse click, so:
stage.addEventListener(MouseEvent.CLICK, onClick);
function onClick(e:MouseEvent):void{
//start FAIL here:
my_mesh.material = new WireframeMaterial(0x000000);
//end FAIL
trace("clicked!");
trace(my_mesh.material)
}
After the mouse click nothing changes in the view, my_mesh spins as it did with the initial material on. But the trace material shows that the new material was indeed applied.
Is there any other way to do this, or is there some kind of a way to refresh the scene to make it use the new material? Or refresh the view? Or should you somehow parse my_mesh again? Cheers.
I would recommend importing your models via Prefab3D. This will allows you to pre-process all these assets in a visual tool.
I either use the awd format or just export meshes as AS3 classes. Export as AS3 classes also compresses that data with the rest of you assets in the swf, a nice little bonus :)