Esempio n. 1
0
void HistoryInteraction::build_coefficient_table()
{
  Interpolation::UniformLagrangeSet lagrange(interp_order);

  for(int pair_idx = 0; pair_idx < num_interactions; ++pair_idx) {
    int src, obs;
    std::tie(src, obs) = idx2coord(pair_idx);

    Vec3d dr(separation((*dots)[src], (*dots)[obs]));

    std::pair<int, double> delay(
        split_double(dr.norm() / (config.c0 * config.dt)));

    floor_delays[pair_idx] = delay.first;
    lagrange.calculate_weights(delay.second, config.dt);

    std::vector<Eigen::Matrix3cd> interp_dyads(
        dyadic->coefficients(dr, lagrange));

    for(int i = 0; i <= interp_order; ++i) {
      coefficients[pair_idx][i] =
          (*dots)[obs].dipole().dot(interp_dyads[i] * (*dots)[src].dipole());
    }
  }
}
Esempio n. 2
0
LOCAL	void check_bond_lengths(
	INTERFACE	*intfc)
{
	CURVE		*c;
	BOND		*b;
	double		oldbl, newbl;

	(void) next_bond(intfc,NULL,NULL);
	while (next_bond(intfc,&b,&c))
	{
	    oldbl = bond_length(b);
	    newbl = separation(b->end,b->start,intfc->dim);

	    if (oldbl != newbl)
	    {
	    	(void) printf("WARNING in check_bond_lengths(), "
	    	              "bond lengths not correct at end of "
	    	              "advance\nold %g new %g dlen %g\n",
	    		      oldbl,newbl,oldbl-newbl);
	    	(void) printf("bond - ");
		print_bond(b);
	    	(void) printf("\n");
	    }
	    bond_length(b) = newbl;
	}
}		/*end check_bond_lengths*/
Esempio n. 3
0
/* Do the bulk of the work.  See the paper cited above for code
 * comments.  All I (Scott) did was transcribe the code and make
 * minimal changes for Netpbm.  And some style changes by Bryan to
 * match Netpbm style.
 */
static void
makeStereoRow(const struct pam * const inPamP,
              tuple *            const inRow,
              int *              const same,
              double             const depthOfField,
              double             const eyesep,
              unsigned int       const dpi) {

#define Z(X) (1.0-inRow[X][0]/(double)inPamP->maxval)

    int const width       = inPamP->width;
    int const pixelEyesep = round2int(eyesep * dpi);
    /* Separation in pixels between the viewer's eyes */

    int col;

    for (col = 0; col < width; ++col)
        same[col] = col;

    for (col = 0; col < width; ++col) {
        int const s = separation(Z(col), eyesep, dpi, depthOfField);
        int left, right;

        left  = col - s/2;  /* initial value */
        right = left + s;   /* initial value */

        if (0 <= left && right < width) {
            int visible;
            int t;
            double zt;

            t = 1;  /* initial value */

            do {
                double const dof = depthOfField;
                zt = Z(col) + 2.0*(2.0 - dof*Z(col))*t/(dof*pixelEyesep);
                visible = Z(col-t) < zt && Z(col+t) < zt;
                ++t;
            } while (visible && zt < 1);
            if (visible) {
                int l;

                l = same[left];
                while (l != left && l != right) {
                    if (l < right) {
                        left = l;
                        l = same[left];
                    } else {
                        same[left] = right;
                        left = right;
                        l = same[left];
                        right = l;
                    }
                }
                same[left] = right;
            }
        }
    }
}
Esempio n. 4
0
void Boid::update(std::vector<Boid *> &otherBoids, ofVec3f &min, ofVec3f &max)
{
	velocity += separationWeight*separation(otherBoids);
	velocity += cohesionWeight*cohesion(otherBoids);
	velocity += alignmentWeight*alignment(otherBoids);
	
	walls(min, max);
	position += velocity;
}
Esempio n. 5
0
    // create an instance of the decoder
    //  blocksize is fixed over the lifetime of this object for performance reasons
    decoder_impl(unsigned blocksize=8192): N(blocksize), halfN(blocksize/2) {
#ifdef USE_FFTW3
        // create FFTW buffers
        lt = (float*)fftwf_malloc(sizeof(float)*N);
        rt = (float*)fftwf_malloc(sizeof(float)*N);
        dst = (float*)fftwf_malloc(sizeof(float)*N);
        dftL = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex)*N);
        dftR = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex)*N);
        src = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex)*N);
        loadL = fftwf_plan_dft_r2c_1d(N, lt, dftL,FFTW_MEASURE);
        loadR = fftwf_plan_dft_r2c_1d(N, rt, dftR,FFTW_MEASURE);
        store = fftwf_plan_dft_c2r_1d(N, src, dst,FFTW_MEASURE);    
#else
        // create lavc fft buffers
        lt = (float*)av_malloc(sizeof(FFTSample)*N);
        rt = (float*)av_malloc(sizeof(FFTSample)*N);
        dftL = (FFTComplexArray*)av_malloc(sizeof(FFTComplex)*N*2);
        dftR = (FFTComplexArray*)av_malloc(sizeof(FFTComplex)*N*2);
        src = (FFTComplexArray*)av_malloc(sizeof(FFTComplex)*N*2);
        fftContextForward = (FFTContext*)av_malloc(sizeof(FFTContext));
        memset(fftContextForward, 0, sizeof(FFTContext));
        fftContextReverse = (FFTContext*)av_malloc(sizeof(FFTContext));
        memset(fftContextReverse, 0, sizeof(FFTContext));
        ff_fft_init(fftContextForward, 13, 0);
        ff_fft_init(fftContextReverse, 13, 1);
#endif
        // resize our own buffers
        frontR.resize(N);
        frontL.resize(N);
        avg.resize(N);
        surR.resize(N);
        surL.resize(N);
        trueavg.resize(N);
        xfs.resize(N);
        yfs.resize(N);
        inbuf[0].resize(N);
        inbuf[1].resize(N);
        for (unsigned c=0;c<6;c++) {
            outbuf[c].resize(N);
            filter[c].resize(N);
        }
        sample_rate(48000);
        // generate the window function (square root of hann, b/c it is applied before and after the transform)
        wnd.resize(N);
        for (unsigned k=0;k<N;k++)
            wnd[k] = sqrt(0.5*(1-cos(2*PI*k/N))/N);
        current_buf = 0;
        memset(inbufs, 0, sizeof(inbufs));
        memset(outbufs, 0, sizeof(outbufs));
        // set the default coefficients
        surround_coefficients(0.8165,0.5774);
        phase_mode(0);
        separation(1,1);
        steering_mode(true);
    }
Esempio n. 6
0
static void
reportParameters(struct cmdlineInfo const cmdline) {

    unsigned int const pixelEyesep = round2int(cmdline.eyesep * cmdline.dpi);

    pm_message("Eye separation: %.4g inch * %d DPI = %u pixels",
               cmdline.eyesep, cmdline.dpi, pixelEyesep);

    if (cmdline.magnifypat > 1)
        pm_message("Background magnification: %uX * %uX",
                   cmdline.magnifypat, cmdline.magnifypat);
    pm_message("\"Optimal\" pattern width: %u / (%u * 2) = %u pixels",
               pixelEyesep, cmdline.magnifypat,
               pixelEyesep/(cmdline.magnifypat * 2));
    pm_message("Unique 3-D depth levels possible: %u",
               separation(0, cmdline.eyesep, cmdline.dpi, cmdline.depth) -
               separation(1, cmdline.eyesep, cmdline.dpi, cmdline.depth) + 1);
    if (cmdline.patFilespec && (cmdline.xshift || cmdline.yshift))
        pm_message("Pattern shift: (%u, %u)", cmdline.xshift, cmdline.yshift);
}
Esempio n. 7
0
void Particle:: update( vector<Particle> &particles ){
    //& pointer notation (ref of the array)
    
    ofPoint v1 = cohesion(particles);
    ofPoint v2 = separation(particles);
    ofPoint v3 = allignment(particles);
    
    vel = vel + v1 + v2 + v3;
    pos = pos + vel;
    
}
Esempio n. 8
0
/* Draw a pair of guide boxes. */
static void
drawguides(int                const guidesize,
           const struct pam * const outPamP,
           double             const eyesep,
           unsigned int       const dpi,
           double             const depthOfField) {

    int const far = separation(0, eyesep, dpi, depthOfField);
    /* Space between the two guide boxes. */
    int const width = outPamP->width;    /* Width of the output image */

    tuple *outrow;             /* One row of output data */
    tuple blackTuple;
    int col;

    pnm_createBlackTuple(outPamP, &blackTuple);

    outrow = pnm_allocpamrow(outPamP);

    /* Leave some blank rows before the guides. */
    makeWhiteRow(outPamP, outrow);
    writeRowCopies(outPamP, outrow, guidesize);

    /* Draw the guides. */
    if ((width - far + guidesize)/2 < 0 ||
            (width + far - guidesize)/2 >= width)
        pm_message("warning: the guide boxes are completely out of bounds "
                   "at %d DPI", dpi);
    else if ((width - far - guidesize)/2 < 0 ||
             (width + far + guidesize)/2 >= width)
        pm_message("warning: the guide boxes are partially out of bounds "
                   "at %d DPI", dpi);

    for (col = (width - far - guidesize)/2;
            col < (width - far + guidesize)/2;
            ++col)
        if (col >= 0 && col < width)
            pnm_assigntuple(outPamP, outrow[col], blackTuple);

    for (col = (width + far - guidesize)/2;
            col < (width + far + guidesize)/2;
            ++col)
        if (col >= 0 && col < width)
            pnm_assigntuple(outPamP, outrow[col], blackTuple);

    writeRowCopies(outPamP,outrow, guidesize);

    /* Leave some blank rows after the guides. */
    makeWhiteRow(outPamP, outrow);
    writeRowCopies(outPamP, outrow, guidesize);

    pnm_freerow(outrow);
}
Esempio n. 9
0
/**
 * インデックスバッファを追加する
 */
void MeshFragmentConverter::addIndices(const std::vector<FigureVertex> &vertices, const u16 p0, const u16 p1, const u16 p2) {
    int ptr = 0;
    u8 bones[4 * 3] = { 0 };

    // 利用するボーンを列挙する
    {
        const FigureVertex &vertex = vertices[p0];
        for (int i = 0; i < 4; ++i) {
            bones[ptr] = vertex.weight.indices[i];
            ++ptr;
        }
    }
    {
        const FigureVertex &vertex = vertices[p1];
        for (int i = 0; i < 4; ++i) {
            bones[ptr] = vertex.weight.indices[i];
            ++ptr;
        }
    }
    {
        const FigureVertex &vertex = vertices[p2];
        for (int i = 0; i < 4; ++i) {
            bones[ptr] = vertex.weight.indices[i];
            ++ptr;
        }
    }

    // 頂点を登録する
    FragmentContext *pContext = getBoneGroupContext(bones, 12);
    if (!pContext) {
        separation();
        pContext = getCurrentContext();
    }
    {
        const FigureVertex &vertex = vertices[p0];
        pContext->indices.push_back(registerVertex(&pContext->vertices, vertex));
    }
    {
        const FigureVertex &vertex = vertices[p1];
        pContext->indices.push_back(registerVertex(&pContext->vertices, vertex));
    }
    {
        const FigureVertex &vertex = vertices[p2];
        pContext->indices.push_back(registerVertex(&pContext->vertices, vertex));
    }

    for (int i = 0; i < 12; ++i) {
        if (bones[i] != UNUSED_BONE) {
            pContext->useBoneIndices.insert(std::map<u8, u8>::value_type(bones[i], bones[i]));
        }
    }
}
Esempio n. 10
0
cocos2d::Vec2 SteeringBehaviors::calculate()
{
    m_vSteeringForce.setPoint(0, 0);

    /**
    * 要知道每一种驱动力的优先级其实是不同的,比如需要首要保证人物之间不能重叠和
    * 撞墙,然后才是arrive和seek
    */
    if (On(WALL_AVOIDANCE) && !accumulateForce(m_vSteeringForce, wallAvoidance()))
    {
        return m_vSteeringForce;
    }

    if (On(SEPARATION) && !accumulateForce(m_vSteeringForce, separation()))
    {
        return m_vSteeringForce;
    }

    // @_@ 后来加入的外部牵引力,一般是不开放的
    if (On(TRACTION) && !accumulateForce(m_vSteeringForce, m_traction))
    {
        return m_vSteeringForce;
    }

    if (On(SEEK) && !accumulateForce(m_vSteeringForce, seek(m_vTarget)))
    {
        return m_vSteeringForce;
    }

    if (On(ARRIVE) && !accumulateForce(m_vSteeringForce, arrive(m_vTarget)))
    {
        return m_vSteeringForce;
    }

    if (On(PURSUIT) && !accumulateForce(m_vSteeringForce, pursuit(m_targetId)))
    {
        return m_vSteeringForce;
    }

    auto tmpFormation       =   m_pOwner->getTeam()->getTeamFormation();
    auto tmpFormationPosId  =   m_pOwner->getMovingEntity().getFormationPosId();
    if (On(KEEP_FORMATION) && !accumulateForce(m_vSteeringForce, keepFormation(tmpFormation, tmpFormationPosId)))
    {
        return m_vSteeringForce;
    }

    return m_vSteeringForce;
}
Esempio n. 11
0
// Given the actor, return a desired velocity in world coordinates
// If the actor is the leader, move towards the target; otherwise, 
// follow the leader without bunching together
vec3 Leader::CalculateDesiredVelocity(Actor& actor)
{

	Arrival arrival(m_pTarget);

	if (actor.agentID == 0)  // actor is the leader
    {
		return arrival.CalculateDesiredVelocity(actor);
	}
    else
    {
		Separation separation(m_pTarget, m_pAgents);

		return 0.7 * separation.CalculateDesiredVelocity(actor) + 0.3 * arrival.CalculateDesiredVelocity(actor);
	}
}
Esempio n. 12
0
static double find_signed_distance(
	int              px,
	int              py,
	cairo_surface_t* surface,
	int              scan_width,
	int              scan_height
) {
	int            width         = cairo_image_surface_get_width(surface);
	unsigned char* data          = cairo_image_surface_get_data(surface);
	unsigned char  base          = data[(px * width) + py];
	int            base_solid    = base > 0;
	double         closest       = MAX_VALUE;
	int            closest_valid = 0;
	int            start_x       = px - (scan_width / 2);
	int            end_x         = start_x + scan_width;
	int            start_y       = py - (scan_height / 2);
	int            end_y         = start_y + scan_height;

	int x;
	int y;

	for(x = start_x; x < end_x; x++) {
		if(x < 0 || x >= width) continue;

		for(y = start_y; y < end_y; y++) {
			unsigned char c;

			if(y < 0 || y >= width) continue;

			c = data[(x * width) + y];

			if(base_solid) {
				if(c == 0) {
					double dist = separation(px, py, x, y);

					if (dist < closest) {
						closest       = dist;
						closest_valid = 1;
					}
				}
			}

			else {
				if(c > 0) {
					double dist = separation(px, py, x, y);

					if(dist < closest) {
						closest       = dist;
						closest_valid = 1;
					}
				}
			}
		}
	}

	if(base_solid) {
		if(closest_valid) return closest;

		else return MAX_VALUE;
	}

	else {
		if(closest_valid) return -closest;

		else return MIN_VALUE;
	}
}
separation find_wheel_minor(matroid_permuted <MatroidType>& permuted_matroid, matrix_permuted <MatrixType>& permuted_matrix,
                            matroid_element_set& extra_elements)
{
    assert (permuted_matrix.size1() >= 3 && permuted_matroid.size2() >= 3);

    /// Permute 1's in first row to the left.
    matroid_reorder_columns(permuted_matroid, permuted_matrix, 0, 1, 0, permuted_matroid.size2(), std::greater <int>());
    size_t count_first_row_ones = matrix_count_property_column_series(permuted_matrix, 0, 1, 0, permuted_matrix.size2(), is_non_zero());

    /// Trivial 1-separation
    if (count_first_row_ones == 0)
    {
        return separation(std::make_pair(1, 0));
    }

    matroid_reorder_rows(permuted_matroid, permuted_matrix, 1, permuted_matroid.size1(), 0, 1, std::greater <int>());
    size_t count_first_column_ones = matrix_count_property_row_series(permuted_matrix, 0, permuted_matroid.size1(), 0, 1, is_non_zero());

    /// 1- or 2-separation
    if (count_first_row_ones == 1)
    {
        if (count_first_column_ones == 0)
        {
            return separation(std::make_pair(1, 1));
        }
        else
        {
            return separation(std::make_pair(1, 1), std::make_pair(1, 0));
        }
    }
    else if (count_first_column_ones == 1)
    {
        return separation(std::make_pair(1, 1), std::make_pair(0, 1));
    }

    assert ((permuted_matrix(0,0) == 1) && (permuted_matrix(1,0) == 1) && (permuted_matrix(0,1) == 1));

    /// Ensure we have a 2x2 block of ones
    if (permuted_matrix(1, 1) != 1)
    {
        matroid_binary_pivot(permuted_matroid, permuted_matrix, 0, 0);
        extra_elements.insert(permuted_matroid.name1(0));
        extra_elements.insert(permuted_matroid.name2(0));
    }

    assert ((permuted_matrix(0,0) == 1) && (permuted_matrix(1,0) == 1) && (permuted_matrix(0,1) == 1) && (permuted_matrix(1,1) == 1));

    /// Grow the block to a set-maximal one.
    matroid_reorder_columns(permuted_matroid, permuted_matrix, 0, 2, 2, permuted_matroid.size2(), std::greater <int>());
    size_t block_width = 2 + matrix_count_property_column_series(permuted_matrix, 0, 2, 2, permuted_matrix.size2(), is_all_ones());

    matroid_reorder_rows(permuted_matroid, permuted_matrix, 2, permuted_matroid.size1(), 0, block_width, std::greater <int>());

    size_t block_height = 2 + matrix_count_property_row_series(permuted_matrix, 2, permuted_matrix.size1(), 0, block_width, is_all_ones());

    /// Search for a path in BFS graph
    zero_block_matrix_modifier modifier(block_height, block_width);
    matrix_modified <matrix_permuted <MatrixType> , zero_block_matrix_modifier> modified_matrix(permuted_matrix, modifier);
    bipartite_graph_dimensions dim(permuted_matrix.size1(), permuted_matrix.size2());
    std::vector <bipartite_graph_dimensions::index_type> start_nodes(block_height);
    for (size_t i = 0; i < block_height; i++)
        start_nodes[i] = dim.row_to_index(i);
    std::vector <bipartite_graph_dimensions::index_type> end_nodes(block_width);
    for (size_t i = 0; i < block_width; i++)
        end_nodes[i] = dim.column_to_index(i);

    std::vector <bipartite_graph_bfs_node> bfs_result;
    bool found_path = bipartite_graph_bfs(modified_matrix, dim, start_nodes, end_nodes, false, bfs_result);

    /// There must be a 2-separation.
    if (!found_path)
    {
        std::pair <size_t, size_t> split(0, 0);

        /// Swap unreachable rows to top
        std::vector <int> reachable(permuted_matrix.size1());
        for (size_t i = 0; i < permuted_matrix.size1(); ++i)
        {
            const bipartite_graph_bfs_node& node = bfs_result[dim.row_to_index(i)];
            int value = (node.is_reachable() ? (node.distance > 0 ? 2 : 1) : 0);
            reachable[permuted_matrix.perm1()(i)] = value;
            if (value == 0)
                split.first++;
        }
        vector_less <int, std::less <int> > less(reachable, std::less <int>());

        sort(permuted_matrix.perm1(), less);
        permuted_matroid.perm1() = permuted_matrix.perm1();

        /// Swap unreachable columns to left
        reachable.resize(permuted_matrix.size2());
        for (size_t i = 0; i < permuted_matrix.size2(); ++i)
        {
            const bipartite_graph_bfs_node& node = bfs_result[dim.column_to_index(i)];
            int value = (node.is_reachable() ? 2 : (node.distance == -2 ? 1 : 0));
            reachable[permuted_matrix.perm2()(i)] = value;
            if (value < 2)
                split.second++;
        }

        sort(permuted_matrix.perm2(), less);
        permuted_matroid.perm2() = permuted_matrix.perm2();

        return separation(split, std::make_pair(split.first, split.second - 1));
    }

    /// Go back along the path to find the nearest endpoint.
    bipartite_graph_dimensions::index_type nearest_end = 0;
    for (std::vector <bipartite_graph_dimensions::index_type>::const_iterator iter = end_nodes.begin(); iter != end_nodes.end(); ++iter)
    {
        if (bfs_result[*iter].is_reachable())
            nearest_end = *iter;
    }

    assert (bfs_result[nearest_end].is_reachable());

    size_t w3_one_column = dim.index_to_column(nearest_end);
    size_t nearest_distance = bfs_result[nearest_end].distance + 1;

    assert (nearest_distance % 2 == 0);

    size_t last_index = nearest_end;
    size_t current_index = bfs_result[last_index].predecessor;

    /// Find indices for basic W3-parts.
    size_t w3_one_row = 0;
    size_t w3_path_column = 0;
    size_t w3_path_row = dim.index_to_row(current_index);
    size_t w3_zero_column = 0;
    while (permuted_matrix(w3_path_row, w3_zero_column) != 0)
    {
        w3_zero_column++;
        assert (w3_zero_column < block_width);
    }

    /// Apply path shortening technique.
    while (last_index != current_index)
    {
        std::pair <size_t, size_t> coords = dim.indexes_to_coordinates(current_index, last_index);

        if ((bfs_result[current_index].distance % 2 == 0) && (bfs_result[current_index].distance >= 2) && (bfs_result[current_index].distance + 2
                < (int) nearest_distance))
        {
            matroid_binary_pivot(permuted_matroid, permuted_matrix, coords.first, coords.second);
            extra_elements.insert(permuted_matroid.name1(coords.first));
            extra_elements.insert(permuted_matroid.name2(coords.second));
        }

        if (bfs_result[current_index].distance == 1)
        {
            assert (dim.is_column(current_index));

            w3_path_column = dim.index_to_column(current_index);
        }
        else if (bfs_result[current_index].distance == 0)
        {
            assert (dim.is_row(current_index));

            w3_one_row = dim.index_to_row(current_index);
        }

        last_index = current_index;
        current_index = bfs_result[current_index].predecessor;
    }

    /// Collect more W3-indices.
    size_t w3_zero_row = 0;
    while (permuted_matrix(w3_zero_row, w3_path_column) != 0)
    {
        w3_zero_row++;
        assert (w3_zero_row< block_height);
    }

    assert (permuted_matrix (w3_one_row, w3_one_column) == 1);
    assert (permuted_matrix (w3_one_row, w3_zero_column) == 1);
    assert (permuted_matrix (w3_one_row, w3_path_column) == 1);
    assert (permuted_matrix (w3_zero_row, w3_one_column) == 1);
    assert (permuted_matrix (w3_zero_row, w3_zero_column) == 1);
    assert (permuted_matrix (w3_zero_row, w3_path_column) == 0);
    assert (permuted_matrix (w3_path_row, w3_one_column) == 1);
    assert (permuted_matrix (w3_path_row, w3_zero_column) == 0);
    assert (permuted_matrix (w3_path_row, w3_path_column) == 1);

    /// Some normalization
    if (w3_zero_row > w3_one_row)
    {
        matroid_permute1(permuted_matroid, permuted_matrix, w3_one_row, w3_zero_row);
        std::swap(w3_one_row, w3_zero_row);
    }
    if (w3_one_row > w3_path_row)
    {
        matroid_permute1(permuted_matroid, permuted_matrix, w3_path_row, w3_one_row);
        std::swap(w3_path_row, w3_one_row);
    }

    if (w3_zero_column > w3_one_column)
    {
        matroid_permute2(permuted_matroid, permuted_matrix, w3_one_column, w3_zero_column);
        std::swap(w3_one_column, w3_zero_column);
    }
    if (w3_one_column > w3_path_column)
    {
        matroid_permute2(permuted_matroid, permuted_matrix, w3_path_column, w3_one_column);
        std::swap(w3_path_column, w3_one_column);
    }

    matroid_permute1(permuted_matroid, permuted_matrix, 0, w3_zero_row);
    matroid_permute1(permuted_matroid, permuted_matrix, 1, w3_one_row);
    matroid_permute1(permuted_matroid, permuted_matrix, 2, w3_path_row);

    matroid_permute2(permuted_matroid, permuted_matrix, 0, w3_zero_column);
    matroid_permute2(permuted_matroid, permuted_matrix, 1, w3_one_column);
    matroid_permute2(permuted_matroid, permuted_matrix, 2, w3_path_column);

    return separation();
}
Esempio n. 14
0
/* ****************************************************
 * Function   : DrawAutoStereogram
 * Arguments  : IMAGE *target = output image
 * 		IMAGE *Zimage = has (float *) depth map
 * Returns    : 0 for success
 * Description: Draw an AutoStereogram!
 * ***************************************************/
int DrawAutoStereogram(IMAGE *target, IMAGE *Zimage)
{
  /* Object's depth is Z(x,y) (between 0 and 1) */
  int x,y;		/* Coordinates of the current point */

  int maxX = Zimage->xmax;
  int maxY = Zimage->ymax;

  int *pix;		/* Color of this pixel */
  int *same;		/* Points to a pixel to the right ... */
    			/* ... that is constrained to be this color */
  int s;		/* Stereo separation at this (x,y) point */
  int left, right;	/* X-values corresponding to left and right eyes */

  int visible;		/* First, perform hidden-surface removal */
  int t=1;		/* We will check the points (x-t,y) and (x+t,y) */
  float zt;		/* Z-coord of ray at these two points */

  int l;		// temp var for left/right adjustments
  PIXEL Zval;		// temp var for *(Zimage->img) pixels
  
  pix  = malloc(maxX * sizeof(int));
  same = malloc(maxX * sizeof(int));

  for(y=0; y < maxY; y++)  /* Convert each scan line independently */
  {
    for(x=0; x < maxX; x++)
      same[x] = x;	/* Each pixel is initially linked with itself */

    for(x=0; x < maxX ; x++)
    {
      // Originally indexed Z[x][y]
      Zval = *((Zimage->img) + (x + (Zimage->xmax)*y));
      s = separation( Zval );
      left = x - s/2;			/* Pixels at left and right ... */
      right = left + s;			/* ... must be the same ... */
      if(0 <= left && right < maxX)	/* ... or must they? */
      {
	t=1;				/* grrr... haha... RESET t */
        do
        {
          zt = Zval + 2*(2 - mu*Zval)*t/(mu*E);
          visible = ( *((Zimage->img) + (x-t + (Zimage->xmax)*y)) < zt) && \
		    ( *((Zimage->img) + (x+t + (Zimage->xmax)*y)) < zt);  /* False if obscured */
          t++;
        } while(visible && zt < 1); /* Done - hidden-surface removal */
      
        if(visible)		/* So record the fact that pixels at */
        {
          l = same[left];	/* ... left and right are the same */
        
	  while(l != left && l != right)
            if(l < right)	/* But first, juggle the pointers ... */
	    {
              left = l; 	/* ... until either same[left]=left */
              l = same[left]; 	/* ... or same[left]=right */
            }
            else
	    {
              same[left] = right;
              left = right;
              l = same[left];
              right = l;
            }

          same[left] = right;  /* This is where we actually record it */
        }
      }
    }

    for(x=maxX-1 ; x>=0 ; x--) 	/* Now set the pixels on this scan line */
    {
      if(same[x] == x)
	      pix[x] = random()&1;	/* Free choice; do it randomly */
      else
	      pix[x] = pix[same[x]];	/* Constrained choice; obey constraint */
      *((target->img) + (x + (target->xmax)*y)) = pix[x];	// Record Pixval 
    }
  }

  //DrawCircle(maxX/2-far/2, maxY*19/20);  // Draw convergence dots at far plane,
  //DrawCircle(maxX/2+far/2, maxY*19/20);  // near the bottom of the screen.

  return 0;

}	// end drawautostereogram
Esempio n. 15
0
void Boid::update(std::vector<Boid *> *boids, ofVec2f * people, int numPeople) {
    // track positions
    if (tailLen > 0) {
        for (int i = tailLen - 1; i > 0; i--)
            lastPos[i] = lastPos[i-1];
        lastPos[0] = pos;
    }
    
    neighbors.clear();
    
    for (int i = 0; i < boids->size(); i++) {
        Boid *other = (*boids)[i];
        if (other != this && pos.squareDistance(other->pos) < maxDist*maxDist) {
            neighbors.push_back(other);
        }
    }
    int neighborCount = neighbors.size();

    if (neighborCount > 0) {
        ofVec2f v1, v2, v3;
        if (neighborCount < 4) {
            if (!personNearby && stayOn)
                v1 = cohesion(cohesionScalar);
            else
                v1 = cohesion(-cohesionScalar*2);
            v2 = alignment(alignmentScalar);
        }
        v3 = separation(separationScalar, minDist);
        
        vel += v1 + v2 + v3;
    }
    
    if (numPeople > 0) {
        if (!personNearby && stayOn) {
            runAwayVec = people[0];
            //cout << "run away vec " << runAwayVec.x << ", " << runAwayVec << "\n\n\n";
            personNearby = true;
        }
        
        ofVec2f v4 = fear(fearScalar, runAwayVec);
        vel += v4;
    }
    else
        personNearby = false;
    
    if (!stayOn) {
        ofVec2f v5 = stayOff(tableCenter);
        vel += v5;
    }
    
    strutVel = strut(strutScalar * vel.length(), strutFreq);
    //ofLog(OF_LOG_NOTICE, "%f %f is strutvel", strutVel.x, strutVel.y);
    if (!personNearby && stayOn) {
        if (pos.x > maxX - 1.1 * radius)
            vel.x -= (pos.x - (maxX - 1.1 * radius)) * 0.09;
        if (pos.x < minX + 1.1 * radius)
            vel.x += ((minX + 1.1 * radius) - pos.x) * 0.09;
        
        if (pos.y > maxY - 1.1 * radius)
            vel.y -= (pos.y - (maxY - 1.1 * radius)) * 0.09;
        if (pos.y < minY + 1.1 * radius)
            vel.y += ((minY + 1.1 * radius) - pos.y) * 0.09;
        
        // maintain a max speed
        vel.limit(0.8f);
    }
    else
        vel.limit(2.5f);
    
    if (pos.distanceSquared(tableCenter) > maxDistFromTable*maxDistFromTable) {
        ofVec2f difference = pos - tableCenter;
        difference.rescale(maxDistFromTable);
        pos = tableCenter + difference;
    }
}
Esempio n. 16
0
int main(int number_arguments, char** arguments)
{
    int integral_parameter_length, integral_results_length, likelihood_parameter_length, likelihood_results_length, i, number_parameters;
    double* point;
    char outfile[512];

    printf("init data...\n");
    mpi_evaluator__init(&number_arguments, &arguments);

    sprintf(star_points_file, "stars.txt");
    sprintf(astronomy_parameters_file, "parameters.txt");
    for (i = 0; i < number_arguments; i++)
    {
        if (!strcmp(arguments[i], "-stars"))
        {
            sprintf(star_points_file, "%s", arguments[++i]);
        }
        else if (!strcmp(arguments[i], "-parameters"))
        {
            sprintf(astronomy_parameters_file, "%s", arguments[++i]);
        }
        else if (!strcmp(arguments[i], "-outfile"))
        {
            sprintf(outfile, "%s", arguments[++i]);
        }
    }

    mpi_evaluator__read_data(read_data);

    number_parameters = get_optimized_parameter_count(ap);
    integral_parameter_length = number_parameters;
    integral_results_length = 1 + ap->number_streams;
    likelihood_parameter_length = 1 + ap->number_streams;
    likelihood_results_length = 2;
    printf("number_parameters: %d\n", number_parameters);
    printf("integral_parameter_length: %d, integral_results_length: %d\n",
           integral_parameter_length,
           integral_results_length);
    printf("likelihood_parameter_length: %d, likelihood_results_length: %d\n",
           likelihood_parameter_length,
           likelihood_results_length);

    printf("init integral...\n");
    evaluator__init_integral(integral_f,
                             integral_parameter_length,
                             integral_compose,
                             integral_results_length);
    printf("init likelihood...\n");
    evaluator__init_likelihood(likelihood_f,
                               likelihood_parameter_length,
                               likelihood_compose,
                               likelihood_results_length);

    printf("starting...\n");
    mpi_evaluator__start();

    printf("getting parameters...\n");
    get_search_parameters(ap, &point);

    printf("evaluating point...\n");
    evaluate(point);

    printf("performing separation...\n");
    separation(outfile, es->background_integral, es->stream_integrals);

    return 0;
}
int main(int argc, char **argv) {
	
	long num_agents;
	long num_steps;
	int thread_count;
	char* filename;
	long timestep;

	if (argc != 5) {
        printf("Usage: num_agents num_steps filename\n");
        exit(1);
        }
        
        thread_count = atoi(argv[1]);
        num_agents = atol(argv[2]);
        num_steps = atol(argv[3]);
        filename = argv[4];
        
        
        
        printf("Running a simulation with %lu agents for %lu steps and saving the data to the file %s...\n", 
        	num_agents, num_steps, filename);
        
        // here's the simulation skeleton
        
        
        // create the agents, with random headings, maybe random locations or all in a bunch
        unsigned int i = 1;
        int j;
        
        Agent **agent_lists_at_timesteps;
        
        agent_lists_at_timesteps = malloc(num_steps * sizeof(Agent*));
        
	int a;
	for(a=0; a<num_steps; a++)
	{
		agent_lists_at_timesteps[a] = malloc(num_agents * sizeof(Agent));	
	}
        
      //  Agent *agent_list = malloc(num_agents * sizeof(Agent));
        
        
        struct timeval tv;
        gettimeofday(&tv, NULL);
        
        
        srand(tv.tv_usec);
        for(j = 0; j < num_agents - 1; j++){
        	//printf("Creating agent %d\n", j);
        	Vector2D heading = init_vector(-(rand_r(&i) % 5), -(rand_r(&i) % 5));
        	//printf("Done vector creation\n");
        	Point2D start_loc = init_point((rand_r(&i) % WINDOWSIZE), (rand_r(&i) % WINDOWSIZE));
        	double speed = 5;
        	Agent_Type prey_type = prey;
        	//printf("initing agent\n");
        	Agent new_agent = init_agent(&heading, &start_loc, speed, prey_type);
        	//printf("Adding to list\n");	
        	agent_lists_at_timesteps[0][j] = new_agent;
        	
        	//printf("Done creating agent %d\n", j);
        }
        Vector2D heading = init_vector((rand_r(&i) % 5), (rand_r(&i) % 5));
        Point2D start_loc = init_point((rand_r(&i) % WINDOWSIZE), (rand_r(&i) % WINDOWSIZE));
        double speed = 5;
        Agent_Type predator_type = predator;
        agent_lists_at_timesteps[0][j] = init_agent(&heading, &start_loc, speed, predator_type);
        int agent_close;
        double ts, te;
        
        
        // for each numstep
        ts = omp_get_wtime();
        
        for(timestep = 1; timestep < num_steps; timestep++){
        
        	int k;
        	Vector2D s,c,a, combo, seek_vector;
        	
# 		pragma omp parallel for num_threads(thread_count) \
        		private(s, c, a, combo, k)
        	for(k = 0; k< num_agents; k++){
        		if(agent_lists_at_timesteps[timestep-1][k].type == prey) {
        			
				s = separation(&agent_lists_at_timesteps[timestep-1][k], k, agent_lists_at_timesteps[timestep-1], num_agents);
				c = cohesion(&agent_lists_at_timesteps[timestep-1][k], k, agent_lists_at_timesteps[timestep-1], num_agents);
				a = alignment(&agent_lists_at_timesteps[timestep-1][k], k, agent_lists_at_timesteps[timestep-1], num_agents);
						
				
	
				combo = plus(&agent_lists_at_timesteps[timestep-1][k].heading, &s);
				plus_equals(&combo, &c);
				plus_equals(&combo, &a);
				divide_equals(&combo, 1.1);
				
				agent_lists_at_timesteps[timestep][k].heading.x = combo.x;
				agent_lists_at_timesteps[timestep][k].heading.y = combo.y;
				
				agent_lists_at_timesteps[timestep][k].position.x = agent_lists_at_timesteps[timestep-1][k].position.x;
				agent_lists_at_timesteps[timestep][k].position.y = agent_lists_at_timesteps[timestep-1][k].position.y;
				
				agent_lists_at_timesteps[timestep][k].speed = agent_lists_at_timesteps[timestep-1][k].speed;
				agent_lists_at_timesteps[timestep][k].type = agent_lists_at_timesteps[timestep-1][k].type;
        		}
        		
        		else {
        			/*
        			if(((timestep - 1) % 50) == 0) {
        				
        				agent_close = find_closest(&agent_lists_at_timesteps[timestep-1][k], k, agent_lists_at_timesteps[timestep-1], num_agents);	
        			}
        			*/
        			
        			//seek_vector = seek(&agent_lists_at_timesteps[timestep-1][k], &agent_lists_at_timesteps[timestep-1][agent_close]);
        			seek_vector = init_vector(5.0, 0.0);
        			
        			agent_lists_at_timesteps[timestep][k].heading.x = seek_vector.x;
				agent_lists_at_timesteps[timestep][k].heading.y = seek_vector.y;
					
				agent_lists_at_timesteps[timestep][k].position.x = agent_lists_at_timesteps[timestep-1][k].position.x;
				agent_lists_at_timesteps[timestep][k].position.y = agent_lists_at_timesteps[timestep-1][k].position.y;
					
				agent_lists_at_timesteps[timestep][k].speed = agent_lists_at_timesteps[timestep-1][k].speed;
				agent_lists_at_timesteps[timestep][k].type = agent_lists_at_timesteps[timestep-1][k].type;
        				
        			}
        			
        			
        	}
        				
        			
        			
        		
        		
        	
        	printf("just changed headings\n");
# 		pragma omp parallel for num_threads(thread_count)
        	for(k = 0; k< num_agents; k++){
        		agent_update(&agent_lists_at_timesteps[timestep][k], 1);
        		//printf("TRYING TO MOD %f \n", agent_list[k].position.x);
        		agent_lists_at_timesteps[timestep][k].position.x = ((int)agent_lists_at_timesteps[timestep][k].position.x % WINDOWSIZE);
        		agent_lists_at_timesteps[timestep][k].position.y = ((int)agent_lists_at_timesteps[timestep][k].position.y % WINDOWSIZE);
        		//printf("AND I GOT %f \n", agent_list[k].position.x);
        		
        	}
        	
        	/* for(k = 0; k < num_agents; k++){
        		add_point_to_file(agent_lists_at_timesteps[timestep][k].position.x, agent_lists_at_timesteps[timestep][k].position.y, 0, filename);	
        	}
        	
        	if(timestep != num_steps -1)
        		add_terminator_to_file(-2, filename); */
        	
        	//printf("timestep is %d\n", timestep);
        	
        }
 /*        add_terminator_to_file(-1, filename); */
        
        te = omp_get_wtime();
        
        
        printf("Time to do all computation and updating %f\n", te-ts);
        	
        		
        //	for each agent
        //		do cohesion, alignment, and seperation
        //		update new heading
        // 	
        // 	for each agent
        //		update the agent location
        //		check their position within boundaries, fix it with mod	
        //		update old heading by setting it = to new heading
        //		write position of agent to file
        //
        //	(if it's not the last step)
        //	write -2 to file
        
        
        //
        // write -1 to file
        
        
        
        create_window(WINDOWSIZE, WINDOWSIZE, "Test");
      //  run_file(filename);
      run_sim(agent_lists_at_timesteps, num_steps, num_agents);
        
        
        
        
        
        
        
        
        
        
        return 0;
        
}
Esempio n. 18
0
IDL_LONG spherematch
  (int      argc,
   void *   argv[])
{
   IDL_LONG    npoints1;
   double    *  ra1;
   double    *  dec1;
   IDL_LONG    npoints2;
   double    *  ra2;
   double    *  dec2;
   double    matchlength;
   double    minchunksize;
	 IDL_LONG *match1;
	 IDL_LONG *match2;
   double    *  distance12;
	 IDL_LONG *nmatch;

	 double myx1,myy1,myz1;
	 IDL_LONG maxmatch, jmax;
	 double currra,sep;
	 IDL_LONG i,j,k,rachunk,decchunk;
	 IDL_LONG retval=1;

   /* 0. allocate pointers from IDL */
   npoints1 = *((IDL_LONG *)argv[0]);
   ra1 = (double *)argv[1];
   dec1 = (double *)argv[2];
   npoints2 = *((IDL_LONG *)argv[3]);
   ra2 = (double *)argv[4];
   dec2 = (double *)argv[5];
   matchlength = *(double *)argv[6];
   minchunksize = *(double *)argv[7];
   match1 = (IDL_LONG *)argv[8];
   match2 = (IDL_LONG *)argv[9];
   distance12 = (double *)argv[10];
   nmatch = (IDL_LONG *)argv[11];

	 /* 1. define chunks */
	 setchunks(ra1,dec1,npoints1,minchunksize,&rabounds,
						 &decbounds,&nra,&ndec,&raoffset);
	 
	 /* 2. assign targets to chunks, with minFibreSpacing of leeway */
	 assignchunks(ra2,dec2,npoints2,raoffset,matchlength,minchunksize,&nchunk2,
								&chunklist2,rabounds,decbounds,nra,ndec);

	 /* 3. make x, y, z coords -- compute (x,y,z)1 on the fly - DPF */
	 xx2=(double *) IDL_GetScratch(&vxx2,npoints2,sizeof(double));
	 yy2=(double *) IDL_GetScratch(&vyy2,npoints2,sizeof(double));
	 zz2=(double *) IDL_GetScratch(&vzz2,npoints2,sizeof(double));
	 for(i=0;i<npoints2;i++) {
		 xx2[i]=cos(DEG2RAD*ra2[i])*cos(DEG2RAD*dec2[i]);
		 yy2[i]=sin(DEG2RAD*ra2[i])*cos(DEG2RAD*dec2[i]);
		 zz2[i]=sin(DEG2RAD*dec2[i]);
	 } /* end for i */

	 /* 4. run matching */
	 maxmatch = (*nmatch);  /* if nmatch != 0 then fill arrays up to maxmatch */
	 (*nmatch)=0;
	 for(i=0;i<npoints1;i++) {
	   currra=fmod(ra1[i]+raoffset,360.);
	   getchunk(currra,dec1[i],&rachunk,&decchunk,rabounds,decbounds,nra,ndec);
	   jmax=nchunk2[decchunk][rachunk];
	   if(jmax>0) {
	     myx1=cos(DEG2RAD*ra1[i])*cos(DEG2RAD*dec1[i]);
	     myy1=sin(DEG2RAD*ra1[i])*cos(DEG2RAD*dec1[i]);
	     myz1=sin(DEG2RAD*dec1[i]);
	     for(j=0;j<jmax;j++) {
	       k=chunklist2[decchunk][rachunk][j];
	       sep=separation(myx1,myy1,myz1,xx2[k],yy2[k],zz2[k]);
	       if(sep<matchlength) {
					 if(maxmatch>(*nmatch)) {
						 match1[(*nmatch)]=i;
						 match2[(*nmatch)]=k;
						 distance12[(*nmatch)]=sep;
					 } /* end if */
					 (*nmatch)++;
	       } /* end if */
	     } /* end for j */
	   } /* end if jmax>0 */
	 } /* end for i */
	 
	 /* 4. clean up after chunks */
	 unassignchunks(&nchunk2,&chunklist2,nra,ndec);
	 unsetchunks(&rabounds,&decbounds,&nra,&ndec);
	 
	 /* 6. free memory */
	 free_memory();

   return retval;
}