Polymorphism in node.js - node.js

I have a 2D matrix with 0s and 1s - respectively representing Water and Land. It is used to generate an animated gif with Perlin noise (moving water and waves clashing on shores...).
However I wish to refactor my code and use polymorphism in the following manner:
For each element in my matrix, based on the value, I wish to create a new WaterTile or LandTile (which will represent a 30x30 set of pixels that are either a mixture of blue for water, and some combinations of green/yellow/blue for land).
WaterTile and LandTile will be inherited from BaseTile (this is an abstract class), having just 2 vars (x, y for coordinates) and a draw() method (this method for the BaseTile class does nothing, its just there if it has to be defined).
Child classes will be overriding the draw() method.
Map will be a 2D array that whose elements will be WaterTiles and LandTiles.
After that, in my main method, I will have this (pseudocode for simplicity, i is index of row, j is index of element in that row):
foreach (row in matrix) {
foreach (element in row) {
if (matrix[i][j] == 0) map[i][j] == new WaterTile();
else map[i][j] == new LandTile();
}
}
After this I will need to invoke more methods for the LandTiles, and then have a new foreach loop, simply having
map[i][j].draw();//invoking draw method based on type
I know this can be done in other ways, but i wish to avoid having if statements that check for the type and call the draw method based on the type, and also practice clean code and learn something new.
If someone can provide me a simple example, ive looked at some already but havent found what I want.

Put the different actions inside the if statement you already have.
Or, just call the draw method, and let each instance do what it is does with draw.
Or encapsulate the if inside a function and use that.

Related

Computing the area filled by matplotlib.pyplot.fill(...)

I'd like to compute the area inside of a curve defined by two vectors a and b. For your reference the curve looks something like this (pyplot.plot(a,b)):
I saw matplotlib has a fill functionality that let you fill the area enclosed by the curve:
I'm wondering, there's any way to obtain the area filled using that same function? It would be very useful as the other way I'm thinking of computing that area is through numerical integration, much more cumbersome.
Thank you for your time.
If you really want to find the area that was filled by matplotlib.pyplot.fill(a, b), you can use its output as follows:
def computeArea(pos):
x, y = (zip(*pos))
return 0.5 * numpy.abs(numpy.dot(x, numpy.roll(y, 1)) - numpy.dot(y, numpy.roll(x, 1)))
# pyplot.fill(a, b) will return a list of matplotlib.patches.Polygon.
polygon = matplotlib.pyplot.fill(a, b)
# The area of the polygon can be computed as follows:
# (you could also sum the areas of all polygons in the list).
print(computeArea(polygon[0].xy))
This method is based on this answer,
and it is not the most efficient one.

Bounding Box intersection

To find elements that are intersecting a geometry I am using the example post by Jeremy in his blog http://thebuildingcoder.typepad.com/blog/2010/12/find-intersecting-elements.html. But the bounding box is always paralell to the axis X, Y and Z and this may cause a problem, like return elements that are not really clashing, because sometimes the bounding box it's not always coincident with the geometry because the family instance is rotated. Besides that, there is the problem that the bounding box will consider the geometry of the symbol and not the instance, and will consider the flipped geometry too, it means that the bounding box is bigger than I am looking for. Is there a way to get the real geometry that are in the currently view ? How can I solve this problem ?
There are many way to address this. Generally, when performing clash detection, you will always run a super fast pre-processing step first to determine candidate elements, and then narrow down the search step by step more precisely in following steps. In this case, you can consider the bounding box intersection the first step, and then perform post-processing afterwards to narrow down the result to your exact goal.
One important question is: does the bounding box really give you all the elements you need, plus more? Are you sure there are none missing?
Once that is settled, all you need to do is add post-processing steps applying the detailed considerations that you care about.
A simple one might be: are all the target element geometry vertices contained in the target volume?
A more complex one might involve retrieving the full solid of the target element and the target volume and performing a Boolean intersection between them to determine completely and exactly whether they intersect, are disjunct, or contained in each other.
Many others are conceivable.
I am using another strategy that is acess the geometry of the instance to verify if the face of the family instace are clashing with a closer conduit.
class FindIntersection
{
public Conduit ConduitRun { get; set; }
public FamilyInstance Jbox { get; set; }
public List<Conduit> GetListOfConduits = new List<Conduit>();
public FindIntersection(FamilyInstance jbox, UIDocument uiDoc)
{
XYZ jboxPoint = (jbox.Location as LocationPoint).Point;
FilteredElementCollector filteredCloserConduits = new FilteredElementCollector(uiDoc.Document);
List<Element> listOfCloserConduit = filteredCloserConduits.OfClass(typeof(Conduit)).ToList().Where(x =>
((x as Conduit).Location as LocationCurve).Curve.GetEndPoint(0).DistanceTo(jboxPoint) < 30 ||
((x as Conduit).Location as LocationCurve).Curve.GetEndPoint(1).DistanceTo(jboxPoint) < 30).ToList();
//getting the location of the box and all conduit around.
Options opt = new Options();
opt.View = uiDoc.ActiveView;
GeometryElement geoEle = jbox.get_Geometry(opt);
//getting the geometry of the element to acess the geometry of the instance.
foreach (GeometryObject geomObje1 in geoEle)
{
GeometryElement geoInstance = (geomObje1 as GeometryInstance).GetInstanceGeometry();
//the geometry of the family instance can be acess by this method that returns a GeometryElement type.
//so we must get the GeometryObject again to acess the Face of the family instance.
if (geoInstance != null)
{
foreach (GeometryObject geomObje2 in geoInstance)
{
Solid geoSolid = geomObje2 as Solid;
if (geoSolid != null)
{
foreach (Face face in geoSolid.Faces)
{
foreach (Element cond in listOfCloserConduit)
{
Conduit con = cond as Conduit;
Curve conCurve = (con.Location as LocationCurve).Curve;
SetComparisonResult set = face.Intersect(conCurve);
if (set.ToString() == "Overlap")
{
//getting the conduit the intersect the box.
GetListOfConduits.Add(con);
}
}
}
}
}
}
}
}
}
Can you please provide a complete minimal reproducible case so we can understand the exact context and analyse what can be done? Maybe you could include one axis-aligned junction box and one that is not, so we can see how ell versus how badly your existing algorithm performs. Thank you!
I summarised this discussion and the results to date in a blog post on filtering for intersecting elements and conduits intersecting a junction box.

How to find number of Reference Planes passing through a selected wall.

I need to find out the number of Reference planes and their names which are passing through a selected wall. I can get all the reference planes for a particular document but how shall I do this for a particular wall.
You help would be appreciated!
Thanks.
If the ElementIntersectFilter doesn't work for your needs, you'll have to extract the geometry of the wall and reference plane and work with those directly.
Intersecting the reference planes with the wall solids can work, but there's a simpler answer that will work, if I understand your question correctly. I'm assuming you only want the walls where the green line of the ref plane intersects, rather than treating the reference plane object as an infinite geometric plane. In the screenshot below, I assume you want to find the checkmarks, but not the red X's. I'm also assuming you're looking at this as a plan exercise, and not specifically setting the vertical extents of the reference plane (this is just based on how I've seen most people use Revit). The following function takes as inputs a single wall and a list of ref planes (you mentioned you already have the collection of all ref planes) and will return a list of ref planes which intersect the wall.
public static List<ReferencePlane> getRefPlanesIntersectingWall( Wall wal, List<ReferencePlane> refPlanesIn)
{
//simplify this to a 2D problem, using the location curve of the wall
List<ReferencePlane> refPlanesOut = new List<ReferencePlane>();
LocationCurve wallLocation = wal.Location as LocationCurve;
Curve wallCurve = wallLocation.Curve;
Double wallZ = wallLocation.Curve.GetEndPoint(0).Z;
foreach (ReferencePlane rp in refPlanesIn)
{
XYZ startPt = new XYZ(rp.BubbleEnd.X, rp.BubbleEnd.Y, wallZ);
XYZ endPt = new XYZ(rp.FreeEnd.X, rp.FreeEnd.Y, wallZ);
Line rpLine = Line.CreateBound(startPt, endPt);
SetComparisonResult test = wallCurve.Intersect(rpLine);
if (test == SetComparisonResult.Overlap ||
test == SetComparisonResult.Subset ||
test == SetComparisonResult.Superset ||
test == SetComparisonResult.Equal )
{
refPlanesOut.Add(rp);
}
}
return refPlanesOut;
}
I would start by trying the built-in ElementIntersectFilter. The documentation has a nice example, replace "FamilyInstance" with "referencePlane" and that may do it.
http://www.revitapidocs.com/2017/19276b94-fa39-64bb-bfb8-c16967c83485.htm
If that doesn't work, you'll need to extract the solid of the wall and intersect with the reference plane.

Rotating/Turning Groups of Ellipses

I'm working on a project where I create mini galaxies using ellipses, rotate, radians, etc. on mouseX and mouseY. However, I'd love it if each mini galaxy could rotate left or right, so that it looks like a galaxy turning slowly in space. Not sure how I'd do this, though, and would love some guidance. Do I have to create an array that holds the ellipses for each galaxy, and then somehow rotate that? Can I simply set a rotate() for each individual ellipse as it draws to the screen? Thanks for any help!
var bgimg;
function preload(){
//for (var i = 0; i < planetArray.length; i++) {
bgimg = loadImage('Assets/galaxy_background.jpg');
}
function setup(){
createCanvas(1301, 822);
background(bgimg, 100);
//background(25,25,22);
}
function draw() {
//background(0);
fill(255);
noStroke();
textSize(19);
text("Create mini-galaxies by holding your mouse in a location. Move to create another.", 20, 40);
star()
//function mousepressed(){
}
function star(){
//angle = map(mouseX, 0,width, 0,360);
//rotate(radians(angle*100));
noStroke();
//translate(width/2, height/2);
translate(mouseX,mouseY);
fill(0);
rotate(radians(frameCount%360)); //rotates output of ellipses
rotate(radians(1000*frameCount%360));
for(var i =0; i < 20; i++){
push();
noStroke();
tint(255, 127);
fill(random(230),5,random(210),random(230));
// fill(random(125),random(250),random(100));
ellipse(10*frameCount % (width/20),0,5,5);
rotate(radians(mouseX, mouseY));
//image(stars, 10*frameCount % (width/2),0,10,10)
//image((10*frameCount % (width/2),0,10,10)
//
pop();
}
}
You'll have better luck with your questions if you try to narrow them down to an MCVE instead of posting your full sketch. It's hard to answer general "how do I do this" type questions. It's much easier to answer specific "I tried X, expected Y, but got Z instead" type question. That being said, I'll try to answer in a general sense:
You're having trouble because of the fact that you're letting your drawing accumulate by only calling the background() function once instead of clearing it every frame. There's nothing wrong with this, but it does make it impossible to apply transforms and rotations to stuff you've already drawn.
Like I said in your other question, most Processing sketches do this:
Store everything you need to draw in a data structure.
You might store an array of PVectors. Or you might create a Galaxy class that contains variables and functions that allow it to draw itself, which you call from your draw() function. The data structure you use is entirely up to you.
This page and this page contain discussions on creating objects in p5.js, or you might just try a google search. Here is an example that uses a class that knows how to draw itself, and then creates an instance of that class to create a sketch.
Clear previous frames every time draw() is called.
Most sketches call the background() function every frame. That might seem annoying because then you have to redraw everything, but that's what the data structures are for.
Redraw everything you want to be drawn every frame.
Iterate over those data structures and redraw your scene. This might be as simple as iterating over an array of PVectors, or maybe you'll want to create objects that know how to draw themselves.
Like I said, this is very general, and exactly what you do depends on how you think about all of the above. There isn't a single best way to do this, so it's hard to be more specific.

JTS : distance between two geometries bypassing another one in the middle

Let's say that I want to calculate the distance between two geometries with JTS, but there is another one in the middle that I can't go across (as if it was a wall). It could look like this :
I wonder how I could calculate that.
In this case, these shapes geom1 and geom2 are 38.45 meters away, as I calculate it straight away. But if I don't want go across that line, I should surround it by the Northern sides, and distance would probably be more than 70 meters away.
We can think that we could have a line a polygon or whatever in the middle.
I wonder if there is any built in function in JTS, or some other thing I could you. I guess if there is anything out there, I should check for some other workaround, as trying to solve complex routing problems is beyond my knowledge.
This is the straight away piece of code using JTS for the distance, which would not still take into account the Geometry in the middle.
import org.apache.log4j.Logger;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
public class distanceTest {
private final static Logger logger = Logger.getLogger("distanceTest");
public static void main(String [] args) {
//Projection : EPSG:32631
// We build one of the geometries on one side
String sGeom1="POLYGON ((299621.3240601513 5721036.003245114, 299600.94820609683 5721085.042327096, 299587.7719688322 5721052.9152064435, 299621.3240601513 5721036.003245114))";
Geometry geom1=distanceTest.buildGeometry(sGeom1);
// We build the geometry on the other side
String sGeom2=
"POLYGON ((299668.20990794065 5721092.766132105, 299647.3623194871 5721073.557249224, 299682.8494029705 5721049.148841454, 299668.20990794065 5721092.766132105))";
Geometry geom2=distanceTest.buildGeometry(sGeom2);
// There is a geometry in the middle, as if it was a wall
String split=
"LINESTRING (299633.6804935104 5721103.780167559, 299668.99872434285 5720999.981241705, 299608.8457218057 5721096.601805294)";
Geometry splitGeom=distanceTest.buildGeometry(split);
// We calculate the distance not taking care of the wall in the middle
double distance = geom1.distance(geom2);
logger.error("Distance : " + distance);
}
public static Geometry buildGeometry(final String areaWKT) {
final WKTReader fromText = new WKTReader();
Geometry area;
try {
area = fromText.read(areaWKT);
}
catch (final ParseException e) {
area = null;
}
return area;
}
}
This works for SQL, I hope you have the same or similar methods at your disposal.
In theory, in this instance you could create a ConvexHull containing the two geometries AND your "unpassable" geometry.
Geometry convexHull = sGeom1.STUnion(sGeom2).STUnion(split).STConvexHull();
Next, extract the border of the ConvexHull to a linestring (use STGeometry(1) - I think).
Geometry convexHullBorder = convexHull.STGeometry(1);
EDIT: Actually, with Geometry you can use STExteriorRing().
Geometry convexHullBorder = convexHull.STExteriorRing();
Lastly, pick one of your geometries, and for each shared point with the border of the ConvexHull, walk the border from that point until you reach the first point that is shared with the other geometry, adding the distance between the current and previous point at each point reached. If the second point you hit belongs to the same geometry as you are walking from, exit the loop and move on to the next to reduce time. Repeat for the second geometry.
When you've done this for all possibilities, you can simply take the minimum value (there will be only two - Geom1 to Geom2 and Geom2 to Geom1) and there is your answer.
Of course, there are plenty of scenarios in which this is too simple, but if all scenarios simply have one "wall" in them, it will work.
Some ideas of where it will not work:
The "wall" is a polygon, fully enveloping both geometries - but then how would you ever get there anyway?
There are multiple "walls" which do not intersect each other (gaps between them) - this method will ignore those passes in between "walls". If however multiple "walls" intersect, creating essentially one larger "wall" the theory will still work.
Hope that makes sense?
EDIT: Actually, upon further reflection there are other scenarios where the ConvexHull approach will not work, for instance the shape of your polygon could cause the ConvexHull to not produce the shortest path between geometries and your "walls". This will not get you 100% accuracy.

Resources