PENDING Use grid mesh ? or delaunay triangulation?
777335
function (texture) {
        var pixels = texture.pixels;
        var width = texture.width;
        var height = texture.height;

        function fetchPixel(x, y, rg) {
            x = Math.max(Math.min(x, width - 1), 0);
            y = Math.max(Math.min(y, height - 1), 0);
            var idx = (y * (width - 1) + x) * 4;
            if (pixels[idx + 3] === 0) {
                return false;
            }
            rg[0] = pixels[idx];
            rg[1] = pixels[idx + 1];
            return true;
        }

        function addPixel(a, b, out) {
            out[0] = a[0] + b[0];
            out[1] = a[1] + b[1];
        }

        var center = [], left = [], right = [], top = [], bottom = [];
        var weight = 0;
        for (var y = 0; y < height; y++) {
            for (var x = 0; x < width; x++) {
                var idx = (y * (width - 1) + x) * 4;
                if (pixels[idx + 3] === 0) {
                    weight = center[0] = center[1] = 0;
                    if (fetchPixel(x - 1, y, left)) {
                        weight++; addPixel(left, center, center);
                    }
                    if (fetchPixel(x + 1, y, right)) {
                        weight++; addPixel(right, center, center);
                    }
                    if (fetchPixel(x, y - 1, top)) {
                        weight++; addPixel(top, center, center);
                    }
                    if (fetchPixel(x, y + 1, bottom)) {
                        weight++; addPixel(bottom, center, center);
                    }
                    center[0] /= weight;
                    center[1] /= weight;
                    // PENDING If overwrite. bilinear interpolation.
                    pixels[idx] = center[0];
                    pixels[idx + 1] = center[1];
                }
                pixels[idx + 3] = 1;
            }
        }
    }
147832
function getGridOffsets(directions, grid, opt) {

        var step = opt.step;

        util.toArray(opt.directions).forEach(function(direction) {

            direction.gridOffsetX = (direction.offsetX / step) * grid.x;
            direction.gridOffsetY = (direction.offsetY / step) * grid.y;
        });
    }
478071
def _scale_mesh(self, scale):
        
        pos_ks = ['vertices', 'centers']

        # TODO: scale velocities???

        # handle scale
        self.update_columns_dict({k: self[k]*scale for k in pos_ks})

        self.update_columns(areas=self.areas*(scale**2))
        self._volume *= scale**3
        if self._area is not None:
            # self._area is None for wd meshes
            self._area += scale**2
1107051
private void triangulateFeatures(List<AssociatedTriple> inliers,
									 DMatrixRMaj P1, DMatrixRMaj P2, DMatrixRMaj P3) {
		List<DMatrixRMaj> cameraMatrices = new ArrayList<>();
		cameraMatrices.add(P1);
		cameraMatrices.add(P2);
		cameraMatrices.add(P3);

		// need elements to be non-empty so that it can use set().  probably over optimization
		List<Point2D_F64> triangObs = new ArrayList<>();
		triangObs.add(null);
		triangObs.add(null);
		triangObs.add(null);

		Point4D_F64 X = new Point4D_F64();
		for (int i = 0; i < inliers.size(); i++) {
			AssociatedTriple t = inliers.get(i);

			triangObs.set(0,t.p1);
			triangObs.set(1,t.p2);
			triangObs.set(2,t.p3);

			// triangulation can fail if all 3 views have the same pixel value. This has been observed in
			// simulated 3D scenes
			if( triangulator.triangulate(triangObs,cameraMatrices,X)) {
				structure.points[i].set(X.x,X.y,X.z,X.w);
			} else {
				throw new RuntimeException("Failed to triangulate a point in the inlier set?! Handle if this is common");
			}
		}
	}
1051515
def add_isosurface_grid_data(self, data, origin, extent, resolution,
                                 isolevel=0.3, scale=10,
                                 style="wireframe", color=0xffffff):
        
        spacing = np.array(extent/resolution)/scale
        if isolevel >= 0:
            triangles = marching_cubes(data, isolevel)
        else:
            triangles = marching_cubes(-data, -isolevel)
        faces = []
        verts = []
        for i, t in enumerate(triangles):
            faces.append([i * 3, i * 3 +1, i * 3 + 2])
            verts.extend(t)
        faces = np.array(faces)
        verts = origin + spacing/2 + np.array(verts)*spacing
        rep_id = self.add_representation('surface', {'verts': verts.astype('float32'),
                                                     'faces': faces.astype('int32'),
                                                     'style': style,
                                                     'color': color})

        self.autozoom(verts)
544493
public static void updateTextureCoordinates( Mesh mesh, 
                                                 List<DelaunayTriangle> triangles,
                                                 double scale,
                                                 Point o,
                                                 Point u, 
                                                 Point v )
    {
        FloatBuffer tcBuf;
        float x,y,a,b;        
        final float ox = (float)scale*o.getXf();
        final float oy = (float)scale*o.getYf();
        final float ux = (float)scale*u.getXf();
        final float uy = (float)scale*u.getYf();
        final float vx = (float)scale*v.getXf();
        final float vy = (float)scale*v.getYf();
        final float vCu = (vx*uy-vy*ux);
        final boolean doX = Math.abs( ux ) > Math.abs( uy );
        
        tcBuf = prepareTextureCoordinateBuffer(mesh,0,2*3*triangles.size());
        tcBuf.rewind();

        for( DelaunayTriangle t : triangles )
        {
            for( int i=0; i<3; i++ )
            {
                x = t.points[i].getXf()-ox;
                y = t.points[i].getYf()-oy;

                // Calculate the texture coordinate in the UV plane
                a = (uy*x - ux*y)/vCu;                
                if( doX )
                {
                    b = (x - a*vx)/ux;
                }
                else
                {
                    b = (y - a*vy)/uy;                    
                }                
                tcBuf.put( a );
                tcBuf.put( b );
            }
        }
    }
899246
def run(self, coords=None, debug=False):
        
        #self.grid.precompute()
        self.grid.search(coords=coords)
        return self.grid
907279
def uniquified_mesh(self):
        """"""
        import numpy as np
        from lace.mesh import Mesh
        new_mesh = Mesh(v=self.v[self.f.flatten()], f=np.array(range(len(self.f.flatten()))).reshape(-1, 3))

        if self.vn is None:
            self.reset_normals()
        new_mesh.vn = self.vn[self.f.flatten()]

        if self.vt is not None:
            new_mesh.vt = self.vt[self.ft.flatten()]
            new_mesh.ft = new_mesh.f.copy()
        return new_mesh
291027
def triangulate(dataset):
        
        alg = vtk.vtkDataSetTriangleFilter()
        alg.SetInputData(dataset)
        alg.Update()
        return _get_output(alg)
983860
def mesh_nmasked(self):
        

        return self._make_2d_array(
            np.ma.count_masked(self._data_sigclip, axis=1))
137895
private double computeTriangleArea3D(DelaunayTriangle triangle) {
        TriangulationPoint[] points = triangle.points;       
        TriangulationPoint p1 = points[0];
        TriangulationPoint p2 = points[1];
        TriangulationPoint p3 = points[2];        
        /**
         * Uses the formula 1/2 * | u x v | where u,v are the side vectors of
         * the triangle x is the vector cross-product
         */
        // side vectors u and v
        double ux = p2.getX() - p1.getX();
        double uy = p2.getY() - p1.getY();
        double uz = p2.getZ() - p1.getZ();

        double vx = p3.getX() - p1.getX();
        double vy = p3.getY() - p1.getY();
        double vz = p3.getZ() - p1.getZ();
        
        if (Double.isNaN(uz) || Double.isNaN(vz)) {
            uz=1;
            vz=1;
        }

        // cross-product = u x v
        double crossx = uy * vz - uz * vy;
        double crossy = uz * vx - ux * vz;
        double crossz = ux * vy - uy * vx;

        // tri area = 1/2 * | u x v |
        double absSq = crossx * crossx + crossy * crossy + crossz * crossz;
        return Math.sqrt(absSq) / 2;
    }
628655
function updateGrid(gx, gy, gw, gh, info, item) {
      var occupied = info.occupied;
      var drawMask = settings.drawMask;
      var ctx;
      if (drawMask) {
        ctx = elements[0].getContext('2d');
        ctx.save();
        ctx.fillStyle = settings.maskColor;
      }

      var dimension;
      if (interactive) {
        var bounds = info.bounds;
        dimension = {
          x: (gx + bounds[3]) * g,
          y: (gy + bounds[0]) * g,
          w: (bounds[1] - bounds[3] + 1) * g,
          h: (bounds[2] - bounds[0] + 1) * g
        };
      }

      var i = occupied.length;
      while (i--) {
        var px = gx + occupied[i][0];
        var py = gy + occupied[i][1];

        if (px >= ngx || py >= ngy || px < 0 || py < 0) {
          continue;
        }

        fillGridAt(px, py, drawMask, dimension, item);
      }

      if (drawMask) {
        ctx.restore();
      }
    }
1134750
def export_mesh(vertices, triangles, filename, mesh_name="mcubes_mesh"):
    
    
    import collada
    
    mesh = collada.Collada()
    
    vert_src = collada.source.FloatSource("verts-array", vertices, ('X','Y','Z'))
    geom = collada.geometry.Geometry(mesh, "geometry0", mesh_name, [vert_src])
    
    input_list = collada.source.InputList()
    input_list.addInput(0, 'VERTEX', "#verts-array")
    
    triset = geom.createTriangleSet(np.copy(triangles), input_list, "")
    geom.primitives.append(triset)
    mesh.geometries.append(geom)
    
    geomnode = collada.scene.GeometryNode(geom, [])
    node = collada.scene.Node(mesh_name, children=[geomnode])
    
    myscene = collada.scene.Scene("mcubes_scene", [node])
    mesh.scenes.append(myscene)
    mesh.scene = myscene
    
    mesh.write(filename)
973272
function Mesh(options){
	var self = this;
	EventEmitter.call(this);
	options = options || {};

	if(!options.wire){
		throw new Error('a mesh needs a wire')
	}
	this.wire = options.wire;
	this.router = options.router;
	this.route = options.route;
	this.mode = options.mode;

	this.wiresend = _.bind(this.wire.send, this.wire);
	this.wire.setup();

	this.connected = {};
	this.available = {};

	var initial = this.router.search(this.route || '');

	_.each(initial.workers, function(worker){
		self.addworker(worker);
	})

	
	this.router.on('added.' + this.route, function(route, worker){
		self.addworker(worker);
		self.emit('added', route, worker);
	})

	this.router.on('removed.' + this.route, function(route, worker){
		self.removeworker(worker);
		self.emit('removed', route, worker);
	})
}
286049
def automeshgrid(
        x, y, step=0.02, xstep=None, ystep=None, pad=0.5, xpad=None, ypad=None
):
    """"""
    if xpad is None:
        xpad = pad
    if xstep is None:
        xstep = step
    if ypad is None:
        ypad = pad
    if ystep is None:
        ystep = step
    xmin = x.min() - xpad
    xmax = x.max() + xpad
    ymin = y.min() - ypad
    ymax = y.max() + ypad
    return meshgrid(xmin, xmax, step, ymin, ymax, ystep)
1020755
def correctGrid(self, img, grid):
        '''
        
        '''

        self.img = imread(img)
        h = self.homography  # TODO: cleanup only needed to get newBorder attr.

        if self.opts['do_correctIntensity']:
            self.img = self.img / self._getTiltFactor(self.img.shape)

        s0, s1 = grid.shape[:2]
        n0, n1 = s0 - 1, s1 - 1

        snew = self._newBorders
        b = self.opts['border']

        sx, sy = (snew[0] - 2 * b) // n0, (snew[1] - 2 * b) // n1

        out = np.empty(snew[::-1], dtype=self.img.dtype)

        def warp(ix, iy, objP, outcut):
            shape = outcut.shape[::-1]
            quad = grid[ix:ix + 2,
                        iy:iy + 2].reshape(4, 2)[np.array([0, 2, 3, 1])]
            hcell = cv2.getPerspectiveTransform(
                quad.astype(np.float32), objP)
            cv2.warpPerspective(self.img, hcell, shape, outcut,
                                flags=cv2.INTER_LANCZOS4,
                                **self.opts['cv2_opts'])
            return quad

        objP = np.array([[0, 0],
                         [sx, 0],
                         [sx, sy],
                         [0, sy]], dtype=np.float32)
        # INNER CELLS
        for ix in range(1, n0 - 1):
            for iy in range(1, n1 - 1):
                sub = out[iy * sy + b: (iy + 1) * sy + b,
                          ix * sx + b: (ix + 1) * sx + b]
#                 warp(ix, iy, objP, sub)

                shape = sub.shape[::-1]
                quad = grid[ix:ix + 2,
                            iy:iy + 2].reshape(4, 2)[np.array([0, 2, 3, 1])]
#                 print(quad, objP)

                hcell = cv2.getPerspectiveTransform(
                    quad.astype(np.float32), objP)
                cv2.warpPerspective(self.img, hcell, shape, sub,
                                    flags=cv2.INTER_LANCZOS4,
                                    **self.opts['cv2_opts'])

#         return out
        # TOP CELLS
        objP[:, 1] += b
        for ix in range(1, n0 - 1):
            warp(ix, 0, objP, out[: sy + b,
                                  ix * sx + b: (ix + 1) * sx + b])
        # BOTTOM CELLS
        objP[:, 1] -= b
        for ix in range(1, n0 - 1):
            iy = (n1 - 1)
            y = iy * sy + b
            x = ix * sx + b
            warp(ix, iy, objP, out[y: y + sy + b, x: x + sx])
        # LEFT CELLS
        objP[:, 0] += b
        for iy in range(1, n1 - 1):
            y = iy * sy + b
            warp(0, iy, objP, out[y: y + sy, : sx + b])
        # RIGHT CELLS
        objP[:, 0] -= b
        ix = (n0 - 1)
        x = ix * sx + b
        for iy in range(1, n1 - 1):
            y = iy * sy + b
            warp(ix, iy, objP, out[y: y + sy, x: x + sx + b])
        # BOTTOM RIGHT CORNER
        warp(n0 - 1, n1 - 1, objP, out[-sy - b - 1:, x: x + sx + b])
#         #TOP LEFT CORNER
        objP += (b, b)
        warp(0, 0, objP, out[0: sy + b, 0: sx + b])
        # TOP RIGHT CORNER
        objP[:, 0] -= b
#         x = (n0-1)*sx+b
        warp(n0 - 1, 0, objP, out[: sy + b, x: x + sx + b])
#         #BOTTOM LEFT CORNER
        objP += (b, -b)
        warp(0, n1 - 1, objP, out[-sy - b - 1:, : sx + b])
        return out
278933
def grid_from_coordinate_transform(numPix, Mpix2coord, ra_at_xy_0, dec_at_xy_0):
    
    a = np.arange(numPix)
    matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2)
    x_grid = matrix[:, 0]
    y_grid = matrix[:, 1]
    ra_grid = x_grid * Mpix2coord[0, 0] + y_grid * Mpix2coord[0, 1] + ra_at_xy_0
    dec_grid = x_grid * Mpix2coord[1, 0] + y_grid * Mpix2coord[1, 1] + dec_at_xy_0
    return ra_grid, dec_grid