Interact with section plane - autodesk-forge

I am creating a section plane like:
this.viewer.loadExtension("Autodesk.Section")
const SectionTool = this.viewer.getExtension("Autodesk.Section")
SectionTool.load()
SectionTool.activate()
SectionTool.tool.setSectionPlane(this.hitTest.face.normal, this.hitTest.point)
const state = this.viewer.getState();
this.viewer.restoreState(state);
This works pretty well, and I get the section plane. But I am not able to interact with this plane like when creating with UI buttons. Can anyone point me in the correct direction to make this possible?
Thank you in advance!

Why store the hitTest results, then restore the other aspects of states without the cutplanes (if they were captured in the saved states ...) and then restore the cutplanes programmatically from the hittest results ... something like:
const hitTest = JSON.parse(localStorage.getItem('hitTestResult'))
delete state.cutplanes
viewer.restoreState(state)
const SectionTool = viewer.getExtension("Autodesk.Section")
SectionTool.activate()
SectionTool.tool.setSectionPlane(hitTest.face.normal, hitTest.point)

Related

Formula to convert Local coordinates to world coordinates

Can someone give me the formula?
I have a vector3d which represents the position of a vertex in local coordinates, I have a Matrix3d that represents the rotation and position of the object which this vertex is part of it's geometry, how do I convert the local position of this vertex to the coordinates of the world?
now it's working, I had a problem with keeping the original vertex3d, and I played with the order and this is working, thank you very much, here is the code, I did have to use m2.invert(); here is the code:
var m3d:Matrix3D = new Matrix3D();
obj.Transform.copyToMatrix3D(m3d);
var m2:Matrix3D = new Matrix3D();
m2.append(m3d);
m2.invert();
m2.prependTranslation(obj.BoundingBox[i].x,obj.BoundingBox[i].y,obj.BoundingBox[i].z);
obj.BoundingBox[i] = new Vector3D(m2.position.x,m2.position.y,m2.position.z);
in fact as I did it in the first place was also OK:
var m3d:Matrix3D = new Matrix3D();
obj.Transform.copyToMatrix3D(m3d);
m3d.invert();
obj.BoundingBox[i] = m3d.transformVector(obj.BoundingBox[i]);
The only thing I was missing was the invert(); and I wish I knew what it is for...
Some people told me I have to append (or prepend) the object matrix and then the world matrix, which makes sense, but adding the world matrix only caused me problems, while the invert(); made it good, but why?
Vesper, you are the one suggested it, thanks but why?
I know why, someone experienced gave me the answer: the camera shows everything mirrored, when you go left the world seems to be moving right, so you need to invert.

paint clears the data in qtableview

I have to display data in a QTableView, I have a model which has data but I subclassed QAbstractProxyModel to Transpose the data in my model, Further I need only one button in the QTableView which can be achieved by subclassing QItemDelegate,
Now the problem is when I set view->setItemDelegate(MyItemDelegate)(for the pushbutton);
view->setModel(myModel); view->show(); ... I find only the pushbutton which I painted in the paint method when delegating the QItemDelegate.
I searched and found that I need to setModelData() and setEditorData() to set the values from myModel.. But I dont know if it is correct and if it is How do I setdata().... Thanks in advance
PS:- when i try view->setModel(MyModel); view->show(); without setItemDelegate... I could see the data in the QTableView... But I dont see the data after delegating ... All this pain just for a QPushButton in a QTableView
The idea is to add QItemDelegate::paint(painter,option,index); inside the paint method of my derived class where I paint my button. Adding the above line of code ensures that the table is painted first and then I draw above the painted table.
So, the solution will look like
void PushButtonDelegate::paint(QPainter *painter,const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QItemDelegate::paint(painter,option,index);
//paint my pushbutton using drawcontrol();
}
If i dont do this I lose my data.. which is obvious when you understand how paint works but not easy to realize... took me hours

Best and most performant implementation of dynamic shapes in cesium

I am currently working an application that is using a Cesium Viewer. I need to be able to display a collection of shapes that will be updated dynamically. I am having trouble understanding the best way to do this.
I currently am using Entities and using CallbackProperties to allow for the updating of shapes.
You can through this into a sandcastle to get an idea of how I am doing this. There is a polygon object that is being used as the basis for the cesiumCallback, and it is getting edited by another piece of code. (simulated with the setTimeout)
var viewer = new Cesium.Viewer('cesiumContainer', {});
var polygon = {};
polygon.coordinates = [
{longitude: 0, latitude: 0, altitude: 0},
{longitude: 10, latitude: 10, altitude: 0},
{longitude: 10, latitude: 0, altitude: 0}
];
// converts generic style options to cesium one (aka color -> material)
var polOpts = {};
// function for getting location
polOpts.hierarchy = new Cesium.CallbackProperty(function() {
var hierarchy = [];
for (var i = 0; i < polygon.coordinates.length; i++) {
var coordinate = polygon.coordinates[i];
hierarchy.push(Cesium.Cartesian3.fromDegrees(coordinate.longitude, coordinate.latitude, coordinate.altitude));
}
return hierarchy;
}, false);
viewer.entities.add({polygon: polOpts});
setInterval(function(polygon){
polygon.coordinates[0].longitude--;
}.bind(this, polygon), 1000);
The polygon being passed in is a class that generically describes a polygon, so it has an array of coordinates and style options, as well as a render method that calls this method renderPolygon passing in itself.
This method of rendering shapes works for everything I need it to, but it is not very performant. There are two cases for shapes updating, one type of shape will be updated over a long period of time, as a slow rate like once every few seconds. The other is shapes that will will get updated many times, like thousands, in a few seconds, then not change again for a long time, if ever.
I had two ideas for how to fix this.
Idea 1:
Have two methods, a renderDynamicPolygon and a renderStaticPolygon.
The renderDynamicPolygon method would do the above functionality, using the cesiumCallbackProperties. This would be used for shapes that are getting updated many times during the short time they are being updated.
The renderStaticPolygon method would replace the entities properties that are using callbackProperties with constant values, once the updating is done.
This creates a lot of other work to make sure shapes are in the right state, and doesn't help the shapes that are being updated slowly over a long period of time.
Idea 2:
Similarly to how the primitives work, I tried removing the old entity and adding it again with its updated properties each time its need to be updated, but this resulted in flickering, and unlike primitives, i could not find a async property for entities.
I also tried using primitives. It worked great for polylines, I would simply remove the old one and add a new one with the updated properties. I was also using the async = false to ensure there was no flickering. This issue I ran into here was not all shapes can be created using primitives. (Is this true?)
The other thing I tried was using the geometry instance using the geometry and appearance. After going through the tutorial on the cesium website I was able to render a few shapes, and could update the appearance, but found it close to impossible to figure out how to update the shapes correctly, and also have a very hard time getting them to look correct. Shapes need to have the right shape, a fill color and opacity and a stroke color, opacity and weight. I tried to use the polygonOutlineGeometry, but had not luck.
What would be the best way to implement this? Are one of these options headed the right way or is there some other method of doing this I have not uncovered yet?
[Edit] I added an answer of where I have gotten, but still not complete and looking for answers.
I have came up with a pretty good solution to this, but it still has one small issue.
I made too ways of showing entities. I am calling one render and one paint. Render uses the the Cesium.CallbackProperty with the isConstant property true, and paint with the isConstantProperty false.
Then I created a function to change the an entity from render to paint and vice vera. It goes through the entities callback properties an uses the setCallback property to overwrite the property with a the correct function and isConstant value.
Example:
I create a ellipse based on a circle object I have defined.
// isConst is True if it is being "painted" and false if it is being "rendered"
ellipse: lenz.util.extend(this._getStyleOptions(circle), {
semiMinorAxis: new Cesium.CallbackProperty(
this._getRadius.bind(this, circle),
isConst
),
semiMajorAxis: new Cesium.CallbackProperty(
this._getRadius.bind(this, circle),
isConst
),
})
So when the shape is being updated (while the user is drawing a shape) the shape is rendered with the isConstant being false.
Then when the drawing is complete it is converted to the painted version using some code like this:
existingEntity.ellipse.semiMinorAxis.setCallback(
this._getRadius.bind(this, circle),
isConst
);
existingEntity.ellipse.semiMajorAxis.setCallback(
this._getRadius.bind(this, circle, 1),
isConst
);
This works great performance wise. I am able to draw hundreds of shapes without the frame dropping much at all. I have attached a screen shot of the cesium map with 612 entities before and after my changes, the frame rate is in the upper right using the chrome render tool.
Before: Locked up at fps 0.9
Note: I redacted the rest of the ui, witch makes the globe look cut off, sorry
And after the changes: The fps remains at 59.9, almost perfect!
Whenever the entity is 'converted' from using constant to not constant callback properties, it and all other entities of the same type flash off then on again. I cannot find a better way to do this conversion. I feel as thought there must still be some thing I am missing.
You could try using a PositionPropertyArray as the polygon's hierarchy with SampledPositionProperty for any dynamic positions and ConstantPositionProperty for any static positions. I'm not sure if it would perform any better than your solution, but it might be worth testing. Here is an example of how it might work that you can paste into the Cesium Sandcastle:
var viewer = new Cesium.Viewer('cesiumContainer', {});
// required if you want no interpolation of position between times
var noInterpolation = {
type: 'No Interpolation',
getRequiredDataPoints: function (degree) {
return 2;
},
interpolateOrderZero: function (x, xTable, yTable, yStride, result) {
if (!Cesium.defined(result)) {
result = new Array(yStride);
}
for (var i = 0; i < yStride; i++) {
result[i] = yTable[i];
}
return result;
}
};
var start = viewer.clock.currentTime;
// set up the sampled position property
var sampledPositionProperty = new Cesium.SampledPositionProperty();
sampledPositionProperty.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD;
sampledPositionProperty.addSample(start, new Cesium.Cartesian3.fromDegrees(0, 0)); // initial position
sampledPositionProperty.setInterpolationOptions({
interpolationAlgorithm: noInterpolation
});
// set up the sampled position property array
var positions = [
sampledPositionProperty,
new Cesium.ConstantPositionProperty(new Cesium.Cartesian3.fromDegrees(10, 10)),
new Cesium.ConstantPositionProperty(new Cesium.Cartesian3.fromDegrees(10, 0))
];
// add the polygon to Cesium viewer
var polygonEntity = new Cesium.Entity({
polygon: {
hierarchy: new Cesium.PositionPropertyArray(positions)
}
});
viewer.zoomTo(viewer.entities.add(polygonEntity));
// add a sample every second
var counter = 1;
setInterval(function(positionArray) {
var time = new Cesium.JulianDate.addSeconds(start, counter, new Cesium.JulianDate());
var position = new Cesium.Cartesian3.fromDegrees(-counter, 0);
positionArray[0].addSample(time, position);
counter++;
}.bind(this, positions), 1000);
One nice thing about this is you can set the timeline start/end time to a reasonable range and use it to see your polygon at any time within the sample range so you can see the history of your polygons through time (See here for how to change the timeline start/end time). Additionally, you don't need to use timers to set the positions, the time is built in to the SampledPositionProperty (although you can still add samples asynchronously).
However, this also means that the position depends on the current time in the timeline instead of a real-time array value. And you might need to keep track of a time somewhere if you aren't adding all the samples at once.
I've also never done this using ellipses before, but the semiMinorAxis and semiMajorAxis are properties, so you might still be able to use a SampledProperty.
Of course, this doesn't really matter if there are still performance issues. Hopefully it will improve as you don't need to recreate the array from scratch each callback and, depending on how you're getting the data to update the polygons, you might be able to add multiple samples at once. This is just speculation, but it's something to consider.
EDIT
Cesium can handle quite a bit of samples added to a sampled position, for example in the above code if you add a million samples to the position it takes a few seconds to load them all, but renders the polygon at any time without any performance issues. To test this, instead of adding samples using a timer, just add them all directly to the property.
for (var i = 0; i < 1000000; i++) {
var time = new Cesium.JulianDate.addSeconds(start, i, new Cesium.JulianDate());
var position = new Cesium.Cartesian3.fromDegrees(-(i % 2), 0);
positions[0].addSample(time, position);
}
However, if you run into memory problems currently there is no way to remove samples from a position property without accessing private variables. A work around would be to periodically create a new array containing new position properties and use the previous position property array's setValue() method to clear previous values or perhaps to use a TimeIntervalCollectionProperty as in this answer and remove time intervals with the removeInterval method.

Square bracket notation to dynamically load library items?

So I've spent an embarrassing number of hours trying to save myself a few minutes and make my code a bit neater, and Google has produced nothing, so now I come crawling to stackoverflow. The problem is with square bracket notation + library items:
So let's say you have a MovieClip called "myMC_5", and you want to set its X position to 0..
myMC_5.x = 0;
..and if you don't want to hard-code the name of the MC but instead you want one line of code to move a specific MovieClip based on a variable, you could do something like this:
var selectMC = 5;
root["myMC_"+selectMC]x = 0;
..and this will have the exact same effect as myMC_5.x = 0, except that this time you must specify the location ("root" or "this" or something).
THE PROBLEM:
I'm working on a game in which the graphic for the background is loaded from the library, and it's different for each level. The initial loading of the vector from the library looks like this:
private var land:vector_land0 = new vector_land0();
..and this works fine, but it only loads that one specific vector. There should be about 30 or more. I'd like to just have 1 line of code in the constructor to load any of them, based on a variable which keeps track of the current level, like this:
private var land:["vector_land"+theLevel] = new ["vector_land"+theLevel]();
..but that doesn't work. I get syntax errors ("expecting identifier before leftbracket") because you need to specify the location of the object, like in the first example:
root["myMC_"+"whatever"].x = 0;
..but this library item has no "location". So, how the heck do I dynamically load a vector from the library? It's not "on the root", or anywhere else. It has no location. I refuse to believe that the standard method for accomplishing this is to create 30 different classes or write a giant block of code with 30 "if" statements, but searching Google has found nothing. :(
It sounds like you're looking for getDefinitionByName(), which you could use to do something like this:
import flash.utils.getDefinitionByName;
private var LevelVectorClass:Class = getDefinitionByName("vector_land" + theLevel) as Class;
private var land:Object = new LevelVectorClass();
This is a horrible way to solve the situation, I don't recommend using square brackets anywhere but arrays. I recommend you putting the "lands" into a LandContainer MovieClip, each frame of that MovieClip would container 1 graphic. It is much cleaner, and you could create constants to store the "identity" of the frames.Example:
var land:LandContainer = new LandContainer();
land.gotoAndStop(FIRST_LEVEL); //FIRST_LEVEL is a constant integer
You can even reuse this LandContainer instance because you can set it's visibility, remove from the display list, set it's frame to the next level without creating another instance. On second thought, I would write a wrapper for this class. Aka link it to your own class which extends the MovieClip class and create custom functions, fields... etc..
This dynamic thing is horrible, hard to maintain, and not efficient at all. Don't know why did not they delete it from AS3... they should have.

Connecting two handles in Matlab

I would like to connect my two axes.handles so that when the mouse button is clicked on one, the other one would also do what the first one do. I have an external function that executes out what I want to do when the mouse is clicked. I just need to update the two handles in GUI so that it will do the same thing when one axes is clicked.
In Main GUI
function testminiproj_OpeningFcn(hObject, ~, handles, varargin)
handles.output = hObject;
handles.done=0;
guidata(hObject, handles);
setappdata(0,'figureHandle',gcf);
setappdata(gcf,'axesHandle1',handles.axes6);
setappdata(gcf,'axesHandle2',handles.axes7);
And this is my external function which is callback into main GUI by calling mousemotion;
function varargout = mousemotion(this,varargin)
%// get the figure handle from the application main data
figureHandle = getappdata(0,'figureHandle');
%// get the axes handle from the figure data
axesHandle1 = getappdata(figureHandle,'axesHandle1');
%// get the axes handle from the figure data
axesHandle2 = getappdata(figureHandle,'axesHandle2');
global rdata;
if nargin<1
set(gcf,'WindowButtonDownFcn','mousemotion(''down'')');
set(gcf,'WindowButtonUpFcn','mousemotion(''up'')');
set(gcf,'WindowButtonMotionFcn','');
Appreciate any help. I am bad at trying to put the question across. Hope someone could help. Thanks.
You can make a handles vector. Like this:
axesHandles = [axesHandles1; axesHandles2];
set(axesHandles, 'PropertyName', PropertyValue);
This way both axes' property values will be set to PropertyValue.
You need to work around and manually find out which axes is clicked in.
It's actually not hard.
Just use the Position attribute of the figure and axes.