After some hours doing some testing I figured out that my map contains the correct values, but the loop that I am using only seems to be using the last added value in this map. Am I missing something obvious here?
The function that adds items to the map: (controls is the map variable)
public static function CreateThumbstick(mActorType:ActorType, mLocation:Int, mDirectionLock:Int)
{
var controllerName = "Thumbstick"+mLocation;
if(!controls.exists(controllerName)){
createRecycledActor(mActorType, 0, 0, Script.FRONT);
var lastActor = getLastCreatedActor();
var myPosition = GetPosition(controllerName, lastActor);
lastActor.setX(myPosition.x);
lastActor.setY(myPosition.y);
var myPos = new Vector2(lastActor.getXCenter(), lastActor.getYCenter());
var controlUnit = new ControlUnit(lastActor, myPos, -1);
controls.set(controllerName, controlUnit);
trace("added key: " + controllerName +" with value: "+ lastActor);
} else {
trace("!!WARNING!! Control unit already exists in this position. Command ignored!");
}
}
Upon creating 3 thumbsticks, the log states the following:
added key: Thumbstick1 with value: [Actor 1,Thumbstick]
added key: Thumbstick2 with value: [Actor 2,Thumbstick]
added key: Thumbstick3 with value: [Actor 3,Thumbstick]
When the screen is touched, it should loop through each item in my map, but it is using the last added item 3 times to check the distance with, rather then all 3 items once. Here is the Listener that is being called when the screen is touched:
addMultiTouchStartListener(function(event:TouchEvent, list:Array<Dynamic>):Void
{
for (unit in controls){
trace(lastDebugLine + "checking distance to " + unit.GetActor());
if(GetDistance(unit.GetCenter(), touch.GetPosition()) < 64){
break;
}
}
});
// used "touch.GetPosition()" instead of actuall code for easy reading. This is not causing any problems!
Upon touching the screen, the log states the following:
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
I am quite new to the Haxe language, so my guess is that I am missing something obvious, even after I have followed the Haxe API very closely. This is the example used from the Haxe API page:
var map4 = ["M"=>"Monday", "T"=>"Tuesday"];
for (value in map4) {
trace(value); // Monday \n Tuesday
}
All explanations are welcome!
Added ControlUnit class:
import com.stencyl.models.Actor;
class ControlUnit
{
static var actor;
static var center;
static var touchID;
public function new(mActor:Actor, mPosition:Vector2, mTouchID:Int)
{
actor = mActor;
center = mPosition;
touchID = mTouchID;
}
public function GetActor():Actor{
return(actor);
}
public function GetCenter():Vector2{
return(center);
}
public function GetTouchID():Int{
return(touchID);
}
}
You just used static for vars in class definitions - they aren't instance aware/based.
Check 'properties', getters, setters etc. in https://haxe.org/manual/class-field-property.html
Are you sure that getLastCreatedActor() is returning a separate instance each time? If it's returning the same instance each time you will likely see what you're getting.
Isn't that because all of your keys map to the same value? Try mapping them to different values and test it.
Related
I am creating a plugin that makes use of the code available from BCFier to select elements from an external server version of the file and highlight them in a Revit view, except the elements are clearly not found in Revit as all elements appear and none are highlighted. The specific pieces of code I am using are:
private void SelectElements(Viewpoint v)
{
var elementsToSelect = new List<ElementId>();
var elementsToHide = new List<ElementId>();
var elementsToShow = new List<ElementId>();
var visibleElems = new FilteredElementCollector(OpenPlugin.doc, OpenPlugin.doc.ActiveView.Id)
.WhereElementIsNotElementType()
.WhereElementIsViewIndependent()
.ToElementIds()
.Where(e => OpenPlugin.doc.GetElement(e).CanBeHidden(OpenPlugin.doc.ActiveView)); //might affect performance, but it's necessary
bool canSetVisibility = (v.Components.Visibility != null &&
v.Components.Visibility.DefaultVisibility &&
v.Components.Visibility.Exceptions.Any());
bool canSetSelection = (v.Components.Selection != null && v.Components.Selection.Any());
//loop elements
foreach (var e in visibleElems)
{
//string guid = ExportUtils.GetExportId(OpenPlugin.doc, e).ToString();
var guid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(OpenPlugin.doc, e));
Trace.WriteLine(guid.ToString());
if (canSetVisibility)
{
if (v.Components.Visibility.DefaultVisibility)
{
if (v.Components.Visibility.Exceptions.Any(x => x.IfcGuid == guid))
elementsToHide.Add(e);
}
else
{
if (v.Components.Visibility.Exceptions.Any(x => x.IfcGuid == guid))
elementsToShow.Add(e);
}
}
if (canSetSelection)
{
if (v.Components.Selection.Any(x => x.IfcGuid == guid))
elementsToSelect.Add(e);
}
}
try
{
OpenPlugin.HandlerSelect.elementsToSelect = elementsToSelect;
OpenPlugin.HandlerSelect.elementsToHide = elementsToHide;
OpenPlugin.HandlerSelect.elementsToShow = elementsToShow;
OpenPlugin.selectEvent.Raise();
} catch (System.Exception ex)
{
TaskDialog.Show("Exception", ex.Message);
}
}
Which is the section that should filter the lists, which it does do as it produces IDs that look like this:
3GB5RcUGnAzQe9amE4i4IN
3GB5RcUGnAzQe9amE4i4Ib
3GB5RcUGnAzQe9amE4i4J6
3GB5RcUGnAzQe9amE4i4JH
3GB5RcUGnAzQe9amE4i4Ji
3GB5RcUGnAzQe9amE4i4J$
3GB5RcUGnAzQe9amE4i4GD
3GB5RcUGnAzQe9amE4i4Gy
3GB5RcUGnAzQe9amE4i4HM
3GB5RcUGnAzQe9amE4i4HX
3GB5RcUGnAzQe9amE4i4Hf
068MKId$X7hf9uMEB2S_no
The trouble with this is, comparing it to the list of IDs in the IFC file that we imported it from reveals that these IDs do not appear in the IFC file, and looking at it in Revit I found that none of the Guids in Revit weren't in the list that appeared either. Almost all the objects also matched the same main part of the IDs as well, and I'm not experienced enough to know how likely that is.
So my question is, is it something in this code that is an issue?
The IFC GUID is based on the Revit UniqueId but not identical. Please read about the Element Identifiers in RVT, IFC, NW and Forge to learn how they are connected.
I try to create a family instance using CreateAdaptiveComponentInstance and try to host it on a reference point, that's also a control point of a CurveByPoints (spline).
The family links properly to the reference point, but the rotation of the reference point's workplane is totally ignored.
Try this standalone example. Move the reference point P2 -> The cross section at P1 will not rotate.
Now, rebuild and change the >> if(true) << to 'false'. Now you see what I want. But as soon as you move the point P2, the link between P2's coordinates and the family is broken.
CurveByPoints spl = null;
ReferencePointArray pts = null;
// create ref points
var p1 = doc.FamilyCreate.NewReferencePoint(new XYZ( 0, 0, 0)); p1.Name = "P1";
var p2 = doc.FamilyCreate.NewReferencePoint(new XYZ(10,10, 0)); p2.Name = "P2";
var p3 = doc.FamilyCreate.NewReferencePoint(new XYZ(30,20, 0)); p3.Name = "P3";
pts = new ReferencePointArray();
pts.Append(p1); pts.Append(p2); pts.Append(p3);
// create a spline
spl = doc.FamilyCreate.NewCurveByPoints(pts);
spl.Visible = true;
spl.IsReferenceLine = false; // MOdelliinie
// change points to adaptive points
foreach(ReferencePoint p in pts)
{
AdaptiveComponentFamilyUtils.MakeAdaptivePoint(doc, p.Id, AdaptivePointType.PlacementPoint);
p.CoordinatePlaneVisibility = CoordinatePlaneVisibility.Always;
p.ShowNormalReferencePlaneOnly = true;
}
// find an adaptive family to place at the points
FamilySymbol fam_sym = null;
var filter = new FilteredElementCollector(doc);
ICollection<Element> col = filter.OfClass(typeof(FamilySymbol)).ToElements();
if(col!=null)
{
foreach(FamilySymbol ele in col)
{
if(ele == null || !AdaptiveComponentInstanceUtils.IsAdaptiveFamilySymbol(ele) ) {continue;}
if(fam_sym == null)
{
fam_sym=ele;
}
if(ele.Name == "profil_adapt_offset_einfach2") // use a special one instead of the first matching
{
fam_sym = ele as FamilySymbol;
break;
}
}
}
// create family instances
if(fam_sym != null)
{
if(true) // this is waht I want. Try "false" to see what I expect
{
foreach (ReferencePoint p in pts)
{
var inst = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(doc, fam_sym);
var placements = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(inst);
ReferencePoint fam_pt = doc.GetElement(placements.FirstOrDefault()) as ReferencePoint;
var pl = Plane.CreateByNormalAndOrigin(new XYZ(1,0,0), p.Position);
// #### I THINK HERE IS MY PROBLEM ####
// "plane" just points to the reference POINT,
// and not the XZ-PLANE of the reference point.
Reference plane = p.GetCoordinatePlaneReferenceYZ();
PointOnPlane pop = doc.Application.Create.NewPointOnPlane(plane, UV.Zero, UV.BasisU, 0.0);
fam_pt.SetPointElementReference(pop);
}
}
else
{
// create family instances and place along the path
// -> looks good until you move a reference point
double ltot=0.0;
for(var i=0; i<pts.Size-1; ++i)
{
ltot += pts.get_Item(i).Position.DistanceTo(pts.get_Item(i+1).Position);
}
double lfromstart=0;
for(var i=0; i<pts.Size; ++i)
{
if(i>0)
{
lfromstart += pts.get_Item(i).Position.DistanceTo(pts.get_Item(i-1).Position);
}
var inst = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(doc, fam_sym);
var placements = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(inst);
var location = new PointLocationOnCurve(PointOnCurveMeasurementType.NormalizedCurveParameter, lfromstart / ltot, PointOnCurveMeasureFrom.Beginning);
PointOnEdge po = doc.Application.Create.NewPointOnEdge(spl.GeometryCurve.Reference, location);
// attach first adaptive point to ref point
var firstPoint = doc.GetElement(placements.FirstOrDefault()) as ReferencePoint;
firstPoint.SetPointElementReference(po);
}
}
}
I'm using Revit 2018.2, here.
People might also search for: GetCoordinatePlaneReferenceXZ, GetCoordinatePlaneReferenceXY.
[edit1]
NewReferencePoint() does not create SketchPlanes
When I manually move a generated reference point -> Now the SketchPlane for this ReferencePoint is generated. But how create that with the API?
[edi2]
- I found that e.g. manually changing the ReferencePoint.CoordinatePlaneVisibility=true will create the SketchPlane I need. But I can't do that in code:
var sel = new List<ElementId>();
foreach (ReferencePoint p in pts)
{
sel.Add(p.Id);
// make plane visible
p.CoordinatePlaneVisibility = CoordinatePlaneVisibility.Always;
// shake point
ElementTransformUtils.MoveElement(doc, p.Id, XYZ.BasisX);
ElementTransformUtils.MoveElement(doc, p.Id, XYZ.BasisX.Negate());
}
ui_doc.Selection.SetElementIds(sel);
doc.Regenerate();
ui_doc.RefreshActiveView();
Will it help if you use the NewReferencePoint overload taking a Transform argument, cf. NewReferencePoint Method (Transform)? That might define the required plane for you and associate it with the point.
The development team replied to your detailed description and test project provided in the attached ZIP file:
The developer seems to be in need of some API we haven’t exposed. PointElement’s API was written before RIDL, so the entire user interface is not exposed to the API. They need an API to get the reference plane that is normal to the the curve that it is driving. This plane is not the same as what is exposed by API PointElement.GetCoordinatePlaneReferenceYZ() (one among the three planes exposed to API).
As per SketchPlanes not being created (in the macro seen in the linked zip file), yes that is correct and matches the UI. SketchPlanes are elements and are different from Autodesk.Revit.DB.Reference. We don’t create them until we have to. And they get garbage collected too. At the end of description, I see some code that should work (assuming they wrapped it in a transaction). Normally selection of the point alone will trigger creation of the SketchPlane from the UI. That aside, I would still not recommend putting the point on SketchPlane for what they want to do.
While, what they want does not exist in API, it still does not quite mean there is no workaround for what they want to achieve. If the Selection or Reference API exposes selectable/visible references on an element, Autodesk.Revit.DB.Reference, then one can iterate over these and host the point. This is generic Element/Reference API.
I hope this clarifies.
It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});
I am working with the D3.js force graph but I am not able to find out the element id from the element position (which I know).
I am using Leap motion. I need to simulate a mouse event (a click, a move, a drag, etc.) without a mouse. And, if I am right, in order to be able to do this, I need to find out what is the the element id from the coordinates x and y (these coordinates I know from the Leap motion pointer). So from what you wrote above, I need to find out the ('.node’).
Here is what I already tried but it did not work:
Is it possible to use non-mouse, non-touch events to interact with a D3.js graph? If so, what is the most efficient way to go about it?
So I used this function (see below), but I need to know the element id to make it work correctly:
//graph.simulate(document.getElementById("r_1"), 'dblclick', {pointerX: posX, pointerY: posY});
//here id r_1 is hardcoded, but I need to find out id from x and y coordinates.
this.simulate = function (element, eventName) {
function extend(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
var eventMatchers = {
'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
};
var defaultOptions = {
pointerX: 0,
pointerY: 0,
button: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
bubbles: true,
cancelable: true
};
var options = extend(defaultOptions, arguments[2] || {});
var oEvent, eventType = null;
for (var name in eventMatchers) {
if (eventMatchers[name].test(eventName)) {
eventType = name;
break;
}
}
if (!eventType)
throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
if (document.createEvent) {
oEvent = document.createEvent(eventType);
if (eventType == 'HTMLEvents') {
oEvent.initEvent(eventName, options.bubbles, options.cancelable);
}
else {
oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
}
element.dispatchEvent(oEvent);
}
else {
options.clientX = options.pointerX;
options.clientY = options.pointerY;
var evt = document.createEventObject();
oEvent = extend(evt, options);
element.fireEvent('on' + eventName, oEvent);
}
return element;
}
Many thanks for your help and ideas.
If you want access to the element, it's implicit in D3's iterators via this.
d3.selectAll('.node').each(function(d) {
console.log(this); // Logs the element attached to d.
});
If you really need access to the id, you can get it with selection.attr():
d3.selectAll('.node').each(function() {
console.log(d3.select(this).attr('id')); // Logs the id attribute.
});
You don't have to use each. Any of the iterators, such as attr or style, etc., have 'this' as the bound element:
d3.selectAll('.node').style('opacity', function(d) {
console.log(this);// Logs the element attached to d.
});
If you want the x and y coordinates of a node, it's part of the data:
d3.selectAll('.node').each(function(d) {
console.log(d.x, d.y); // Logs the x and y position of the datum.
});
If you really need the node attributes themselves, you can use the attr accessor.
d3.selectAll('.node').each(function(d) {
// Logs the cx and cy attributes of a node.
console.log(d3.select(this).attr('cx'), d3.select(this).attr('cy'));
});
EDIT: It looks like you need an element reference, but the only thing you know about the node in context is its position. One solution is to search through all nodes for a node with matching coordinates.
// Brute force search of all nodes.
function search(root, x, y) {
var found;
function recurse(node) {
if (node.x === x && node.y === y)
found = node;
!found && node.children && node.children.forEach(function(child) {
recurse(child);
});
}
recurse(root);
return found;
}
However this only gives you the node object, not the element itself. You will likely need to store the element references on the nodes:
// Give each node a reference to its dom element.
d3.selectAll('.node').each(function(d) {
d.element = this;
});
With that in place, you should be able to access the element and get its id.
var id, node = search(root, x, y);
if (node) {
id = node.element.getAttribute('id');
}
The brute-force search is fine for a small number of nodes, but if you're pushing a large number of nodes you might want to use D3's quadtree (example) to speed up the search.
Use d3.select('#yourElementId')
For more info check this out: https://github.com/mbostock/d3/wiki/Selections
II want an user to draw a route with polylines on GoogleMaps. I've found a way to snap a polyline ( example in the link, code in below ). The code works with the directions service to draw a polyline on a road, the only problem is this only works with G_TRAVELMODE_DRIVING but I want to use G_TRAVELMODE_WALKING and when you use WALKING you have to supply the map and a div in the constructor of the directions object. When I do that it automatically removes the last line and only displays the current line. I've tried several things like supplying the map as null, or leaving out the map in the constructor.. I've also tried to give a second map in the constructor, get the polylines from the directions service and display them on the right map. But nothing works! I'd appreciate it if someone could help me!
http://econym.org.uk/gmap/example_snappath.htm
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(53.7877, -2.9832),13)
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
var dirn = new GDirections();
var firstpoint = true;
var gmarkers = [];
var gpolys = [];
var dist = 0;
GEvent.addListener(map, "click", function(overlay,point) {
// == When the user clicks on a the map, get directiobns from that point to itself ==
if (!overlay) {
if (firstpoint) {
dirn.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{getPolyline:true});
} else {
dirn.loadFromWaypoints([gmarkers[gmarkers.length-1].getPoint(),point.toUrlValue(6)],{getPolyline:true});
}
}
});
// == when the load event completes, plot the point on the street ==
GEvent.addListener(dirn,"load", function() {
// snap to last vertex in the polyline
var n = dirn.getPolyline().getVertexCount();
var p=dirn.getPolyline().getVertex(n-1);
var marker=new GMarker(p);
map.addOverlay(marker);
// store the details
gmarkers.push(marker);
if (!firstpoint) {
map.addOverlay(dirn.getPolyline());
gpolys.push(dirn.getPolyline());
dist += dirn.getPolyline().Distance();
document.getElementById("distance").innerHTML="Path length: "+(dist/1000).toFixed(2)+" km. "+(dist/1609.344).toFixed(2)+" miles.";
}
firstpoint = false;
});
GEvent.addListener(dirn,"error", function() {
GLog.write("Failed: "+dirn.getStatus().code);
});
}
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
I know it's an old post, but since no answer came forward and I've recently been working on this sort of code (and got it working), try swapping the addListener with this.
GEvent.addListener(map, "click", function(overlay,point) {
// == When the user clicks on a the map, get directiobns from that point to itself ==
if (!overlay) {
if (firstpoint) {
dirn1.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{ getPolyline:true,travelMode:G_TRAVEL_MODE_WALKING});
} else {
dirn1.loadFromWaypoints([gmarkers[gmarkers.length-1].getPoint(),point.toUrlValue(6)],{ getPolyline:true,travelMode:G_TRAVEL_MODE_WALKING});
}
}
});