/**
* @brief 
*
* @param provider
*/
QueuedVideoFilter::QueuedVideoFilter( AudioVideoProvider &provider ) :
    VideoConsumer( cClass(), provider, FeedLink( FEED_QUEUED, AudioVideoProvider::videoFramesOnly ) ),
    VideoProvider( cClass(), provider.name() ),
    Thread( identity() )
{
}
eMatrix3x3::eMatrix3x3()
{
    identity();
}
Exemple #3
0
int zmq::xrep_t::xrecv (msg_t *msg_, int flags_)
{
    //  if there is a prefetched identity, return it.
    if (prefetched == 2)
    {
        int rc = msg_->init_size (prefetched_id.size ());
        errno_assert (rc == 0);
        memcpy (msg_->data (), prefetched_id.data (), prefetched_id.size ());
        msg_->set_flags (msg_t::more);
        prefetched = 1;
        return 0;
    }

    //  If there is a prefetched message, return it.
    if (prefetched == 1) {
        int rc = msg_->move (prefetched_msg);
        errno_assert (rc == 0);
        more_in = msg_->flags () & msg_t::more ? true : false;
        prefetched = 0;
        return 0;
    }

    pipe_t *pipe = NULL;
    while (true) {

        //  Get next message part.
        int rc = fq.recvpipe (msg_, flags_, &pipe);
        if (rc != 0)
            return -1;

        //  If identity is received, change the key assigned to the pipe.
        if (likely (!(msg_->flags () & msg_t::identity)))
            break;

        zmq_assert (!more_in);

        //  Empty identity means we can preserve the auto-generated identity.
        if (msg_->size () != 0) {

            //  Actual change of the identity.
            outpipes_t::iterator it = outpipes.begin ();
            while (it != outpipes.end ()) {
                if (it->second.pipe == pipe) {
                    blob_t identity ((unsigned char*) msg_->data (),
                        msg_->size ());
                    pipe->set_identity (identity);
                    outpipes.erase (it);
                    outpipe_t outpipe = {pipe, true};
                    outpipes.insert (outpipes_t::value_type (identity,
                        outpipe));
                    break;
                }
                ++it;
            }
            zmq_assert (it != outpipes.end ());
        }
    }

    //  If we are in the middle of reading a message, just return the next part.
    if (more_in) {
        more_in = msg_->flags () & msg_t::more ? true : false;
        return 0;
    }
 
    //  We are at the beginning of a new message. Move the message part we
    //  have to the prefetched and return the ID of the peer instead.
    int rc = prefetched_msg.move (*msg_);
    errno_assert (rc == 0);
    prefetched = 1;
    rc = msg_->close ();
    errno_assert (rc == 0);

    blob_t identity = pipe->get_identity ();
    rc = msg_->init_size (identity.size ());
    errno_assert (rc == 0);
    memcpy (msg_->data (), identity.data (), identity.size ());
    msg_->set_flags (msg_t::more);
    return 0;
}
Exemple #4
0
int gfx_step(  uint32_t *fifo,  uint32_t jmp, int off )
{

	static bool init_particles = false;
	
	if( !init_particles )
	{
	    init_particles = true;
	    
	    for( size_t i = 0; i < INUMBER; ++i )
	    {
		dt[i] = ( rand() & 63 ) + 32;
		rnds[i][0] = 360.0f * i / (float)( INUMBER );//rnd( 0.0f, 360.0f );
		rnds[i][1] = rnd( -0.2f, +0.2f );
		rnds[i][2] = rnd( -0.8f, +0.3f );
		rnds[i][3] = rnd( 0.3f, 1.0f );
		
		
		insts[i].time 	= rand();
		insts[i].col[0] = rnd( 0.8f, 1.0f );
		insts[i].col[1] = rnd( 0.8f, 1.0f );
		insts[i].col[2] = rnd( 0.8f, 1.0f );
		insts[i].col[3] = 1.0f;				
	    }
	}
	
	
	for( size_t i = 0; i < INUMBER; ++i )
	{
	    insts[i].time += dt[i];
	    identity( insts[i].mat );
	
	    rotatef( 80.0f, 1.0f, 0.0f, 0.0f, insts[i].mat );
	    rotatef( off * 0.5f + rnds[i][0], 0.0f, 0.0f, 1.0f, insts[i].mat );
	    translatef( 1.6f, rnds[i][1], rnds[i][2], insts[i].mat );
	    scalef( rnds[i][3], insts[i].mat );
	    
	    float d = insts[i].mat[11];
	    
	    d = ( 1.0f - 0.6f * d );
	    insts[i].scale = rnds[i][3];
	    insts[i].col[0] = d;
	    insts[i].col[1] = 0.5f + d;
	    insts[i].col[2] = d;
	    
	    //translatef( 1.0f * sin( t * rnds[i][0] ), 1.0f * cos( t * rnds[i][0] ), 1.0f * sin( t * rnds[i][2] ), insts[i].mat );
	}
	
	
	
	clear_buffer_t clear;
	clear.clearR = clear.clearG = clear.clearB = clear.clearA = clear.clearD = 1;
	clear.rgba = 50 + ( 10 << 8 ) + ( 5 << 16 );
	clear.depth = 0xffff;

	static job_t job;
	
	static size_t curr = 0x0;

	job.pd.insts = (uint32_t)insts;
	job.pd.isize = INUMBER;
	job.pd.dynamic = (uint32_t)( dynamic ) + curr * 24;
	job.pd.fx = (uint32_t)fx.get_data();
	job.pd.atlas = (uint32_t)atlas.get_data();
	job.pd.asize = atlas.get_size();
	job.kick_job( );
	job.join();

	
	uint32_t *ptr = fifo;
	static float angle = 180.0f;
	ptr += setup_surfaces_with_offset( ptr, off % 3 );
	ptr += clear_buffers( &clear, ptr, Nv3D );
	
	ptr += set_mvp( ptr, angle );
	ptr += set_cnst( ptr );
	//ptr += troll_texture.set( ptr );
	//ptr += troll.set( ptr );
	
	//ptr += custom.set( ptr );
	ptr += particles.set( ptr );
	ptr += particle_texture.set( ptr );
	
	ptr += draw_primitives( 0, QUADS, curr, job.pd.quads * 4, ptr, Nv3D );
	
	curr += job.pd.quads * 4;// + 128;
	curr = ( curr + 16 ) & 2047;
	
	//printf( "%d \n", job.pd.quads );
	ptr += jump_to_address( ptr, jmp );
	return ptr - fifo;
}
Exemple #5
0
void translation(double tx, double ty, LTransform m)
{
    identity(m);
    m[2][0] = tx;
    m[2][1] = ty;
}
Exemple #6
0
GLboolean
invert(GLdouble src[16], GLdouble inverse[16])
{
    double t;
    int i, j, k, swap;
    GLdouble tmp[4][4];
    
    identity(inverse);
    
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            tmp[i][j] = src[i*4+j];
        }
    }
    
    for (i = 0; i < 4; i++) {
        /* look for largest element in column. */
        swap = i;
        for (j = i + 1; j < 4; j++) {
            if (fabs(tmp[j][i]) > fabs(tmp[i][i])) {
                swap = j;
            }
        }
        
        if (swap != i) {
            /* swap rows. */
            for (k = 0; k < 4; k++) {
                t = tmp[i][k];
                tmp[i][k] = tmp[swap][k];
                tmp[swap][k] = t;
                
                t = inverse[i*4+k];
                inverse[i*4+k] = inverse[swap*4+k];
                inverse[swap*4+k] = t;
            }
        }
        
        if (tmp[i][i] == 0) {
        /* no non-zero pivot.  the matrix is singular, which
        shouldn't happen.  This means the user gave us a bad
            matrix. */
            return GL_FALSE;
        }
        
        t = tmp[i][i];
        for (k = 0; k < 4; k++) {
            tmp[i][k] /= t;
            inverse[i*4+k] /= t;
        }
        for (j = 0; j < 4; j++) {
            if (j != i) {
                t = tmp[j][i];
                for (k = 0; k < 4; k++) {
                    tmp[j][k] -= tmp[i][k]*t;
                    inverse[j*4+k] -= inverse[i*4+k]*t;
                }
            }
        }
    }
    return GL_TRUE;
}
Exemple #7
0
Matrix3::Matrix3()
{
    identity();
}
Exemple #8
0
void GetDiagonal( const Matrix<T>& A, Matrix<T>& d, Int offset )
{
    DEBUG_ONLY(CSE cse("GetDiagonal"))
    function<T(T)> identity( []( T alpha ) { return alpha; } ); 
    GetMappedDiagonal( A, d, identity, offset );
}
Exemple #9
0
///////////////////////////////////////////////////////////////////////////
// inline functions for Mat2
///////////////////////////////////////////////////////////////////////////
inline Mat2::Mat2()
{
    // initially identity matrix
    identity();
}
Exemple #10
0
etk::Matrix2::Matrix2() {
	// TODO: Remove this ...
	identity();
}
      virtual double metric(stk::mesh::Entity& element, bool& valid)
      {
        valid = true;
        JacobianUtil jacA, jacW;

        int spatialDim = m_eMesh->get_spatial_dim();
        double A_ = 0.0, W_ = 0.0; // current and reference detJ
        jacA(A_, *m_eMesh, element, m_coord_field_current, m_topology_data);
        jacW(W_, *m_eMesh, element, m_coord_field_original, m_topology_data);
        double val=0.0, val_shape=0.0;
        MsqMatrix<3,3> Ident; 
        identity(Ident);

        MsqMatrix<3,3> WI, T;

        for (int i=0; i < jacA.m_num_nodes; i++)
          {
            double detAi = jacA.m_detJ[i];
            if (detAi < 0)
              {
                valid = false;
              }
            MsqMatrix<3,3>& W = jacW.m_J[i];
            MsqMatrix<3,3>& A = jacA.m_J[i];

            // frob2 = h^2 + h^2 + 1
            // frob21 = 2 h^2
            // f = h sqrt(2)
            // det = h*h
            // met = f*f / (det*2) - 1
            // frob3 = 3 h^2
            // f = h sqrt(3)
            // det = h*h*h
            // met = f*f*f/(3^3/2 *det) - 1 = f*f*f/(3*sqrt(3)*det) - 1
            double shape_metric = 0.0;
            if (std::fabs(detAi) > 1.e-15)
              {
                inverse(W, WI);
                product(A, WI, T);
                double d = det(T);
                double f = my_sqr_Frobenius(T);
                if (spatialDim==2)
                  {
                    // all our jacobians are 3D, with a 1 in the 3,3 slot for 2d, so we subtract it here
                    f = f - 1.0;
                    f = std::sqrt(f);
                    double fac = 2.0;
                    double den = fac * d;
                    shape_metric = (f*f)/den - 1.0;
                  }
                else
                  {
                    f = std::sqrt(f);
                    double fac = 3.0*std::sqrt(3.0);
                    double den = fac * d;
                    shape_metric = (f*f*f)/den - 1.0;
                  }
                //shape_metric = std::fabs(shape_metric);
                //shape_metric = f/std::pow(den,1./3.) - 1.0;
              }
            val_shape += shape_metric;
            //val_shape += std::fabs(shape_metric);
            //val_shape += shape_metric*shape_metric;
          }
        val = val_shape;
        //val = val_shape*val_shape;
        return val;
      }
 Verificator()
 {
   Name identity(IDENTITY_NAME);
   Name keyName = m_keyChain.getDefaultKeyNameForIdentity(identity);
   m_publicKey = m_keyChain.getPublicKey(keyName); 
 };
Exemple #13
0
int zmq::xrep_t::xsend (zmq_msg_t *msg_, int flags_)
{
    //  If this is the first part of the message it's the identity of the
    //  peer to send the message to.
    if (!more_out) {
        zmq_assert (!current_out);

        //  If we have malformed message (prefix with no subsequent message)
        //  then just silently ignore it.
        if (msg_->flags & ZMQ_MSG_MORE) {

            more_out = true;

            //  Find the pipe associated with the identity stored in the prefix.
            //  If there's no such pipe just silently ignore the message.
            blob_t identity ((unsigned char*) zmq_msg_data (msg_),
                zmq_msg_size (msg_));
            outpipes_t::iterator it = outpipes.find (identity);

            if (it != outpipes.end ()) {
                current_out = it->second.writer;
                zmq_msg_t empty;
                int rc = zmq_msg_init (&empty);
                zmq_assert (rc == 0);
                if (!current_out->check_write (&empty)) {
                    it->second.active = false;
                    more_out = false;
                    current_out = NULL;
                }
                rc = zmq_msg_close (&empty);
                zmq_assert (rc == 0);
            }
        }

        int rc = zmq_msg_close (msg_);
        zmq_assert (rc == 0);
        rc = zmq_msg_init (msg_);
        zmq_assert (rc == 0);
        return 0;
    }

    //  Check whether this is the last part of the message.
    more_out = msg_->flags & ZMQ_MSG_MORE;

    //  Push the message into the pipe. If there's no out pipe, just drop it.
    if (current_out) {
        bool ok = current_out->write (msg_);
        zmq_assert (ok);
        if (!more_out) {
            current_out->flush ();
            current_out = NULL;
        }
    }
    else {
        int rc = zmq_msg_close (msg_);
        zmq_assert (rc == 0);
    }
    //  Detach the message from the data buffer.
    int rc = zmq_msg_init (msg_);
    zmq_assert (rc == 0);

    return 0;
}
Exemple #14
0
bool PlayPG::doLogin() {
	const auto logger = el::Loggers::getLogger("PlayPG");
	if (!socket.isConnected()) {
		socket.connect();

		if (socket.hasError()) {
			return false;
		}

		if (!socket.waitForActivity(2000)) {
			logger->error("Server didn't respond in time.");
			return false;
		}

		int read = socket.recv();

		const auto opcode = socket.getShort();

		logger->info("Got %v bytes, opcode %v.", read, opcode);

		if (opcode != static_cast<opcode_type_t>(ServerOpcode::LOGIN_AUTHENTICATION_CHALLENGE)) {
			logger->info("Got opcode %v which doesn't match the expected value. Ignoring.");
			socket.clear();
			return false;
		}

		const uint16_t jsonSize = socket.getShort();

		auto json = socket.getStringByLength(jsonSize);

//		logger->info("JSON: %v", json);

		APG::JSONSerializer<AuthenticationChallenge> challengeS11N;
		const auto challenge = challengeS11N.fromJSON(json.c_str());

		logger->info("Got challenge from \"%v\", v%v (%v).", challenge.name, challenge.version, challenge.versionHash);
//		logger->info("Got pubkey: %v", challenge.pubKey);

		serverPubKey = challenge.pubKey;

		crypto = std::make_unique<RSACrypto>(serverPubKey, true);

		socket.clear();

		if (std::strcmp(challenge.version.c_str(), Version::versionString) != 0
		        || std::strcmp(challenge.versionHash.c_str(), Version::gitHash) != 0) {
			logger->info("Version check failed.");

			VersionMismatch mismatchPacket;

			socket.put(&mismatchPacket.buffer);
			socket.send();

			return false;
		}

		logger->info("Version check successful.");
	} else {
		socket.clear();
	}

	const auto encPass = crypto->encryptStringPublic("testa");
	logger->info("Sending %v byte password", encPass.size());

	AuthenticationIdentity identity(username, encPass);

	socket.put(&identity.buffer);
	const auto sentAuthDetailBytes = socket.send();
	logger->info("Sent %v auth detail bytes, opcode %v.", sentAuthDetailBytes, (opcode_type_t) identity.opcode);

	socket.clear();

	socket.waitForActivity(2000);

	socket.recv();

	const auto respOpcode = socket.getShort();

	if (respOpcode != static_cast<opcode_type_t>(ServerOpcode::LOGIN_AUTHENTICATION_RESPONSE)) {
		return false;
	}

	const auto respSize = socket.getShort();
	const auto respJSON = socket.getStringByLength(respSize);
	logger->info("Got authentication response: %v", respJSON);

	APG::JSONSerializer<AuthenticationResponse> responseS11N;
	const auto response = responseS11N.fromJSON(respJSON.c_str());

	if (!response.successful) {
		logger->info("Authentication failed with username %v: %v", username, response.message);

		if (response.attemptsRemaining == 0) {
			socket.disconnect();
		}

		return false;
	}

	return true;
}
// Construct with length.
Foam::searchableSurfaces::searchableSurfaces(const label size)
    :
    PtrList<searchableSurface>(size),
    regionNames_(size),
    allSurfaces_(identity(size))
{}
Exemple #16
0
static void makeProgram( RenderData *renderData) {

    GLint ok;

    const char *vertexShader =  "attribute vec3 position;\n"
                                "attribute vec2 texCoord0;\n"
                                "varying vec2 v_texCoord0;\n"
                                "varying float dist;\n"
                                "uniform mat4 modelView;\n"
                                "uniform mat4 projection;\n"
                                "void main(void)\n"
                                "{\n"
                                "    vec4 p = modelView*vec4(position,1.0);\n"
                                "    gl_Position = projection*p;\n"
                                "    v_texCoord0 = texCoord0;\n"
                                "    dist = gl_Position.z*0.1;\n"
                                "}\n";


    const char *fragmentShader =
                                //"precision mediump float;\n"
                                "varying vec2 v_texCoord0;\n"
                                "varying float dist;\n"
                                "uniform sampler2D texUnit0;\n"
                                "uniform float alpha;\n"
                                "uniform float imgAlpha;\n"
                                "uniform vec4 color;\n"
                                "void main()\n"
                                "{\n"
                                "    vec4 txt = texture2D(texUnit0, v_texCoord0)*imgAlpha;\n"
                                "    gl_FragColor =vec4(1.0,1.0,1.0,1.0)*(1.0-dist);\n"
                                "    gl_FragColor.a =1.0;\n"
                                "}\n";



    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    
    glShaderSource(vs, 1, &vertexShader, NULL);
    glCompileShader(vs);
    glGetShaderiv(vs, GL_COMPILE_STATUS, &ok);
    
    assert(ok);

    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    
    glShaderSource(fs, 1, &fragmentShader, NULL);
    glCompileShader(fs);
    glGetShaderiv(fs, GL_COMPILE_STATUS, &ok);


    assert(ok);

    GLuint program = glCreateProgram();
    renderData->program = program;
    
    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    assert(ok);

    glUseProgram(program);

    identity(renderData->model);
    translate2(renderData->model,-0.2, 0.2, -50.6);

    perspective(renderData->model_view_projection, 90.0, WIDTH/HEIGHT, 1.0, 500.0);

    renderData->mvLocation = glGetUniformLocation(program, "modelView");
    glUniformMatrix4fv(renderData->mvLocation, 1, GL_FALSE, renderData->model); 

    GLint projectionLocation = glGetUniformLocation(program, "projection");
    glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, renderData->model_view_projection); 

    GLint texLocation = glGetUniformLocation(program, "texUnit0");
    glUniform1i(texLocation, 0);

    GLint alphaLocation = glGetUniformLocation(program, "alpha");
    glUniform1f(alphaLocation, 1.0);

    GLint imgAlphaLocation = glGetUniformLocation(program, "imgAlpha");
    glUniform1f(imgAlphaLocation, 1.0);

    GLint colorLocation = glGetUniformLocation(program, "color");
    

    renderData->texCoordLocation = glGetAttribLocation(program, "texCoord0");
    renderData->positionLocation = glGetAttribLocation(program, "position");
    renderData->alphaLocation = alphaLocation;
    renderData->imgAlphaLocation = imgAlphaLocation;
    renderData->colorLocation = colorLocation;

    GLfloat vVertices[] = {1.0, -1.0, 0.0,
                            0.0, -1.0, 0.0,
                           1.0,  0.0, 0.0,
                            0.0,  0.0, 0.0};

    GLfloat vTexCoord[] = {1.0, 1.0,
                           0.0, 1.0,
                           1.0, 0.0,
                           0.0, 0.0};

    GLuint vbo;

    glEnableVertexAttribArray(renderData->positionLocation);
    glEnableVertexAttribArray(renderData->texCoordLocation);

    glGenBuffers(1, &renderData->texBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, renderData->texBufferId);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vTexCoord), vTexCoord, GL_STATIC_DRAW);
    glVertexAttribPointer(renderData->texCoordLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);
    
    glGenBuffers(1, &renderData->vertBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, renderData->vertBufferId);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vVertices), vVertices, GL_STATIC_DRAW);
    glVertexAttribPointer(renderData->positionLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
    
 
}
Exemple #17
0
Matrix::Matrix()
{
	identity();
}
Exemple #18
0
  energy_t last_kinetic_energy;
  energy_t last_energy_of_proximity_to_next;
  velocity_t approx_velocity;
};

void supernaturally_set_velocity(particle& p, velocity_t v) {
  p.approx_velocity = v;
  p.last_kinetic_energy = v*v*p.mass;
}

void adjust_velocity(particle& p) {
  p.approx_velocity = velocity_t(isqrt(p.last_kinetic_energy/p.mass))*sign(p.approx_velocity);
}

const auto energy_of_proximity_constant_spec_units = grams*meters*meters*meters/seconds/seconds;
const auto energy_of_proximity_constant = 10 * energy_of_proximity_constant_spec_units * identity(energy_units*position_units/energy_of_proximity_constant_spec_units);
energy_t energy_of_proximity(position_t const& p0, position_t const& p1) {
  return divide(energy_of_proximity_constant, p1-p0, rounding_strategy<round_down, negative_is_forbidden>());
}
// force_t force_of_proximity(position_t const& p0, position_t const& p1) {
//   return divide(-energy_of_proximity_constant, (p1-p0)*(p1-p0), rounding_strategy<round_down, negative_is_forbidden>());
// }

energy_t invariant_kinetic_energy(particle const& p0, particle const& p1) {
}

struct interaction_info {
  interaction_info(particle const& p0, particle const& p1, time_t new_time) {
    new_pos0 = p0.last_position + p0.approx_velocity*(new_time-p0.last_time);
    
    const energy_t old_eop = p0.last_energy_of_proximity_to_next;
Exemple #19
0
Quat::Quat()
{
 identity();
}
Exemple #20
0
void interact(particle& p0, particle& p1, time_t new_time) {
{
  interaction_info info(p0, p1, new_time);
  assert (info.discriminant_quarter >= 0);
  
  p0.last_time = new_time;
  p0.last_position = info.new_pos0;
  p0.last_kinetic_energy = divide(info.total_momentum_sq*p0.mass - info.total_momentum*isqrt(info.discriminant_quarter*4) + p1.mass*(info.new_kinetic_energy*(p0.mass+p1.mass) - info.total_momentum_sq),
    (p0.mass+p1.mass)*(p0.mass+p1.mass),
    rounding_strategy<round_down, negative_continuous_with_positive>());
  p0.last_energy_of_proximity_to_next = info.new_eop;
  p1.last_time = new_time;
  p1.last_position = info.new_pos1;
  p1.last_kinetic_energy = info.new_kinetic_energy - p0.last_kinetic_energy;
  
  adjust_velocity(p0);
  adjust_velocity(p1);
}

class particles_interact : public event {
public:
  particles_interact(entity_id id0, entity_id id0) : id0(id0),id1(id1) {}
  entity_id id0;
  entity_id id1;

  void operator()(time_steward::accessor* accessor)const override {
    particle& p0 = accessor->get_mut<particle>(accessor->get(id0));
    particle& p1 = accessor->get_mut<particle>(accessor->get(id1));
    interact(p0, p1);
  }
};

class particle_repulsion_preparer : public trigger {
public:
  player_moves_around(entity_id id0, entity_id id0) : id0(id0),id1(id1) {}
  entity_id id0;
  entity_id id1;

  void operator()(time_steward::accessor* accessor)const override {
    particle const& p0 = accessor->get<particle>(accessor->get(id0));
    particle const& p1 = accessor->get<particle>(accessor->get(id1));
    const time_t t = max(p0.last_time, p1.last_time);
    const position_t pos0 = p0.last_position + p0.approx_velocity*(t-p0.last_time);
    const position_t dp = pos1 - pos0;
    const velocity_t dv = p1.approx_velocity - p0.approx_velocity;
    
    time_t t2 = t-1;
    if (dv > 0) {
      t2 = t + divide(dp, dv*10, rounding_strategy<round_down, negative_is_forbidden>());
    }
    if (dv < 0) {
      t2 = t + divide(dp, -dv*12, rounding_strategy<round_down, negative_is_forbidden>());
      while (!can_interact(p0, p1, t2)) {
        t2 = divide(t2+t, 2, rounding_strategy<round_down, negative_continuous_with_positive>());
      }
    }
    
    if (t2 >= t) {
      accessor->anticipate_event(t2, std::shared_ptr<event>(new particles_interact(id0, id1)));
    }
  }
};

class initialize_world : public event {
public:
  void operator()(time_steward::accessor* accessor)const override {
    std::vector<particle> particles;
    const uint32_t num_particles = 4;
    for (uint32_t i = 0; i < num_particles; ++i) {
      particle p;
      p.last_time = 0;
      particles.push_back(p);
    }
    particles[0].mass = 1200 * grams * identity(mass_units/grams);
    particles[0].last_position = 0 * meters * identity(position_units/meters);
    supernaturally_set_velocity(particles[0], 10 * milli*meters/seconds * identity(velocity_units/(milli*meters/seconds)));
    particles[1].mass = 1200 * grams * identity(mass_units/grams);
    particles[1].last_position = 1 * meters * identity(position_units/meters);
    supernaturally_set_velocity(particles[1], -10 * milli*meters/seconds * identity(velocity_units/(milli*meters/seconds)));
    particles[2].mass = 1 * grams * identity(mass_units/grams);
    particles[2].last_position = 2 * meters * identity(position_units/meters);
    supernaturally_set_velocity(particles[2], 0 * milli*meters/seconds * identity(velocity_units/(milli*meters/seconds)));
    particles[3].mass = 8000 * grams * identity(mass_units/grams);
    particles[3].last_position = 20 * meters * identity(position_units/meters);
    supernaturally_set_velocity(particles[3], -10000 * milli*meters/seconds * identity(velocity_units/(milli*meters/seconds)));
    
    for (uint32_t i = 0; i < num_particles; ++i) {
      entity_id id = siphash_id::combining(i);
      entity_ref e = accessor->get(id);
      particle& p = particles[i];
      if (i+1 < num_particles) {
        p.last_energy_of_proximity_to_next = energy_of_proximity(p.last_position, particles[i+1].last_kinetic_energy);
        accessor->set_trigger(id, std::shared_ptr<trigger>(new player_could_hit_walls(id, siphash_id::combining(i+1))));
      }
      accessor->set<particle>(e, p);
    }7
  }
};
void Foam::meshRefinement::findNearest
(
    const labelList& meshFaces,
    List<pointIndexHit>& nearestInfo,
    labelList& nearestSurface,
    labelList& nearestRegion,
    vectorField& nearestNormal
) const
{
    pointField fc(meshFaces.size());
    forAll(meshFaces, i)
    {
        fc[i] = mesh_.faceCentres()[meshFaces[i]];
    }

    const labelList allSurfaces(identity(surfaces_.surfaces().size()));

    surfaces_.findNearest
    (
        allSurfaces,
        fc,
        scalarField(fc.size(), sqr(GREAT)),    // sqr of attraction
        nearestSurface,
        nearestInfo
    );

    // Do normal testing per surface.
    nearestNormal.setSize(nearestInfo.size());
    nearestRegion.setSize(nearestInfo.size());

    forAll(allSurfaces, surfI)
    {
        DynamicList<pointIndexHit> localHits;

        forAll(nearestSurface, i)
        {
            if (nearestSurface[i] == surfI)
            {
                localHits.append(nearestInfo[i]);
            }
        }

        label geomI = surfaces_.surfaces()[surfI];

        pointField localNormals;
        surfaces_.geometry()[geomI].getNormal(localHits, localNormals);

        labelList localRegion;
        surfaces_.geometry()[geomI].getRegion(localHits, localRegion);

        label localI = 0;
        forAll(nearestSurface, i)
        {
            if (nearestSurface[i] == surfI)
            {
                nearestNormal[i] = localNormals[localI];
                nearestRegion[i] = localRegion[localI];
                localI++;
            }
        }
    }
Exemple #22
0
//------------------------------------------------------------------------------
static void
display() {

    // set effect
    g_effect.displayStyle = g_displayStyle;
    g_effect.screenSpaceTess = (g_screenSpaceTess != 0);
    g_effect.displayPatchColor = (g_displayPatchColor != 0);

    // prepare view matrix
    float aspect = g_width/(float)g_height;
    float modelview[16], projection[16];
    identity(modelview);
    translate(modelview, -g_pan[0], -g_pan[1], -g_dolly);
    rotate(modelview, g_rotate[1], 1, 0, 0);
    rotate(modelview, g_rotate[0], 0, 1, 0);
    rotate(modelview, -90, 1, 0, 0);
    translate(modelview, -g_center[0], -g_center[1], -g_center[2]);
    perspective(projection, 45.0f, aspect, 0.01f, 500.0f);

    g_effect.SetMatrix(modelview, projection);
    g_effect.SetTessLevel((float)(1 << g_tessLevel));
    g_effect.SetLighting();

    // -----------------------------------------------------------------------
    // prepare draw items

    Stopwatch s;
    s.Start();

    OpenSubdiv::OsdUtilDrawItem<MyDrawDelegate::EffectHandle, MyDrawContext>::Collection items;
    OpenSubdiv::OsdUtilDrawItem<MyDrawDelegate::EffectHandle, MyDrawContext>::Collection cachedDrawItems;

    int numModels = g_modelCount*g_modelCount;
    items.reserve(numModels);

    for (int i = 0; i < numModels; ++i) {
        // Here, client can pack arbitrary mesh and effect into drawItems.

        items.push_back(OpenSubdiv::OsdUtilDrawItem<MyDrawDelegate::EffectHandle, MyDrawContext>(
                            g_batch, &g_effect, g_batch->GetPatchArrays(i)));
    }

    if (g_batching) {
        // create cached draw items
        OpenSubdiv::OsdUtil::OptimizeDrawItem(items, cachedDrawItems, &g_drawDelegate);
    }

    s.Stop();
    float prepCpuTime = float(s.GetElapsed() * 1000.0f);

    // -----------------------------------------------------------------------
    // draw items
    s.Start();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glViewport(0, 0, g_width, g_height);

    // primitive counting
    glBeginQuery(GL_PRIMITIVES_GENERATED, g_queries[0]);
#if defined(GL_VERSION_3_3)
    glBeginQuery(GL_TIME_ELAPSED, g_queries[1]);
#endif
    g_drawDelegate.ResetNumDrawCalls();

    if (g_displayStyle == kWire) glDisable(GL_CULL_FACE);

    if (g_batching) {
        OpenSubdiv::OsdUtil::DrawCollection(cachedDrawItems, &g_drawDelegate);
    } else {
        OpenSubdiv::OsdUtil::DrawCollection(items, &g_drawDelegate);
    }

    if (g_displayStyle == kWire) glEnable(GL_CULL_FACE);

    glEndQuery(GL_PRIMITIVES_GENERATED);
#if defined(GL_VERSION_3_3)
    glEndQuery(GL_TIME_ELAPSED);
#endif

    s.Stop();
    float drawCpuTime = float(s.GetElapsed() * 1000.0f);

    // -----------------------------------------------------------------------

    GLuint numPrimsGenerated = 0;
    GLuint timeElapsed = 0;
    glGetQueryObjectuiv(g_queries[0], GL_QUERY_RESULT, &numPrimsGenerated);
#if defined(GL_VERSION_3_3)
    glGetQueryObjectuiv(g_queries[1], GL_QUERY_RESULT, &timeElapsed);
#endif
    float drawGpuTime = timeElapsed / 1000.0f / 1000.0f;

    if (g_hud.IsVisible()) {
        g_fpsTimer.Stop();
        g_totalTime += g_fpsTimer.GetElapsed();
        double fps = 1.0/g_fpsTimer.GetElapsed();
        g_fpsTimer.Start();
        g_hud.DrawString(10, -200, "Draw Calls : %d", g_drawDelegate.GetNumDrawCalls());
        g_hud.DrawString(10, -180, "Tess level : %d", g_tessLevel);
        g_hud.DrawString(10, -160, "Primitives : %d", numPrimsGenerated);
        g_hud.DrawString(10, -120, "GPU Kernel : %.3f ms", g_gpuTime);
        g_hud.DrawString(10, -100, "CPU Kernel : %.3f ms", g_cpuTime);
        g_hud.DrawString(10, -80,  "GPU Draw   : %.3f ms", drawGpuTime);
        g_hud.DrawString(10, -60,  "CPU Draw   : %.3f ms", drawCpuTime);
        g_hud.DrawString(10, -40,  "CPU Prep   : %.3f ms", prepCpuTime);
        g_hud.DrawString(10, -20,  "FPS        : %3.1f", fps);

        g_hud.Flush();
    }

    checkGLErrors("display leave");
    glFinish();
}
//------------------------------------------------------------------------------
static void
display() {

    g_hud.GetFrameBuffer()->Bind();

    Stopwatch s;
    s.Start();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glViewport(0, 0, g_width, g_height);

    // prepare view matrix
    double aspect = g_width/(double)g_height;
    identity(g_transformData.ModelViewMatrix);
    translate(g_transformData.ModelViewMatrix, -g_pan[0], -g_pan[1], -g_dolly);
    rotate(g_transformData.ModelViewMatrix, g_rotate[1], 1, 0, 0);
    rotate(g_transformData.ModelViewMatrix, g_rotate[0], 0, 1, 0);
    rotate(g_transformData.ModelViewMatrix, -90, 1, 0, 0);
    translate(g_transformData.ModelViewMatrix,
              -g_center[0], -g_center[1], -g_center[2]);
    perspective(g_transformData.ProjectionMatrix,
                45.0f, (float)aspect, 0.1f, 500.0f);
    multMatrix(g_transformData.ModelViewProjectionMatrix,
               g_transformData.ModelViewMatrix,
               g_transformData.ProjectionMatrix);

    glEnable(GL_DEPTH_TEST);

    s.Stop();
    float drawCpuTime = float(s.GetElapsed() * 1000.0f);

    glBindVertexArray(0);

    glUseProgram(0);

    // primitive counting

    glBeginQuery(GL_PRIMITIVES_GENERATED, g_queries[0]);
#if defined(GL_VERSION_3_3)
    glBeginQuery(GL_TIME_ELAPSED, g_queries[1]);
#endif

    // Update and bind transform state ---------------------
    if (! g_transformUB) {
        glGenBuffers(1, &g_transformUB);
        glBindBuffer(GL_UNIFORM_BUFFER, g_transformUB);
        glBufferData(GL_UNIFORM_BUFFER, sizeof(g_transformData), NULL, GL_STATIC_DRAW);
    };
    glBindBuffer(GL_UNIFORM_BUFFER, g_transformUB);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(g_transformData), &g_transformData);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    // Update and bind lighting state ----------------------
    struct Lighting {
        struct Light {
            float position[4];
            float ambient[4];
            float diffuse[4];
            float specular[4];
        } lightSource[2];
    } lightingData = {
       {{  { 0.5,  0.2f, 1.0f, 0.0f },
           { 0.1f, 0.1f, 0.1f, 1.0f },
           { 0.7f, 0.7f, 0.7f, 1.0f },
           { 0.8f, 0.8f, 0.8f, 1.0f } },

         { { -0.8f, 0.4f, -1.0f, 0.0f },
           {  0.0f, 0.0f,  0.0f, 1.0f },
           {  0.5f, 0.5f,  0.5f, 1.0f },
           {  0.8f, 0.8f,  0.8f, 1.0f } }}
    };
    if (! g_lightingUB) {
        glGenBuffers(1, &g_lightingUB);
        glBindBuffer(GL_UNIFORM_BUFFER, g_lightingUB);
        glBufferData(GL_UNIFORM_BUFFER, sizeof(lightingData), NULL, GL_STATIC_DRAW);
    };
    glBindBuffer(GL_UNIFORM_BUFFER, g_lightingUB);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(lightingData), &lightingData);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    // Draw stuff ------------------------------------------

    // control cage edges & verts
    if (g_drawCageVertices) {
        g_base_glmesh.Draw(GLMesh::COMP_VERT, g_transformUB, g_lightingUB);
    }

    if (g_drawCageEdges) {
        g_base_glmesh.Draw(GLMesh::COMP_EDGE, g_transformUB, g_lightingUB);
    }

    // Hbr mesh
    if (g_HbrDrawMode!=kDRAW_NONE) {

        GLMesh::Component comp=GLMesh::COMP_VERT;
        switch (g_HbrDrawMode) {
            case kDRAW_VERTICES  : comp=GLMesh::COMP_VERT; break;
            case kDRAW_WIREFRAME : comp=GLMesh::COMP_EDGE; break;
            case kDRAW_FACES     : comp=GLMesh::COMP_FACE; break;
            default:
                assert(0);
        }
        g_hbr_glmesh.Draw(comp, g_transformUB, g_lightingUB);
    }

    // Vtr mesh
    if (g_VtrDrawMode!=kDRAW_NONE) {

        GLMesh::Component comp=GLMesh::COMP_VERT;
        switch (g_VtrDrawMode) {
            case kDRAW_VERTICES  : comp=GLMesh::COMP_VERT; break;
            case kDRAW_WIREFRAME : comp=GLMesh::COMP_EDGE; break;
            case kDRAW_FACES     : comp=GLMesh::COMP_FACE; break;
            default:
                assert(0);
        }
        g_vtr_glmesh.Draw(comp, g_transformUB, g_lightingUB);
    }

    assert(g_font);
    g_font->Draw(g_transformUB);

    // -----------------------------------------------------

    g_hud.GetFrameBuffer()->ApplyImageShader();

    GLuint numPrimsGenerated = 0;
    GLuint timeElapsed = 0;
    glGetQueryObjectuiv(g_queries[0], GL_QUERY_RESULT, &numPrimsGenerated);
#if defined(GL_VERSION_3_3)
    glGetQueryObjectuiv(g_queries[1], GL_QUERY_RESULT, &timeElapsed);
#endif

    float drawGpuTime = timeElapsed / 1000.0f / 1000.0f;

    if (g_hud.IsVisible()) {
        g_fpsTimer.Stop();
        double fps = 1.0/g_fpsTimer.GetElapsed();
        g_fpsTimer.Start();

        { // display selectde patch info
            static char const * patchTypes[11] = { "undefined", "points", "lines",
                "quads", "tris", "loop", "regular", "boundary", "corner",
                    "gregory", "gregory-boundary" };

            if (g_Adaptive and g_currentPatch) {
                g_hud.DrawString(g_width/2-100, 100, "Current Patch : %d/%d (%s - %d CVs)",
                    g_currentPatch-1, g_numPatches,
                        patchTypes[g_currentPatchDesc.GetType()],
                            g_currentPatchDesc.GetNumControlVertices());
            }
        }

        static char const * schemeNames[3] = { "BILINEAR", "CATMARK", "LOOP" };

        g_hud.DrawString(10, -140, "Primitives : %d", numPrimsGenerated);
        g_hud.DrawString(10, -120, "Scheme     : %s", schemeNames[ g_shapes[g_currentShape].scheme ]);
        g_hud.DrawString(10, -100, "GPU Kernel : %.3f ms", g_gpuTime);
        g_hud.DrawString(10, -80,  "CPU Kernel : %.3f ms", g_cpuTime);
        g_hud.DrawString(10, -60,  "GPU Draw   : %.3f ms", drawGpuTime);
        g_hud.DrawString(10, -40,  "CPU Draw   : %.3f ms", drawCpuTime);
        g_hud.DrawString(10, -20,  "FPS        : %3.1f", fps);

        g_hud.Flush();
    }
    glFinish();

    //checkGLErrors("display leave");
}
Exemple #24
0
/* The idea is to produce a transformation for this viewport which
 * will take any location in INCHES and turn it into a location on the 
 * Device in INCHES.
 * The reason for working in INCHES is because we want to be able to
 * do rotations as part of the transformation.
 * If "incremental" is true, then we just work from the "current"
 * values of the parent.  Otherwise, we have to recurse and recalculate
 * everything from scratch.
 */
void calcViewportTransform(SEXP vp, SEXP parent, Rboolean incremental,
			   pGEDevDesc dd)
{
    int i, j;
    double vpWidthCM, vpHeightCM, rotationAngle;
    double parentWidthCM, parentHeightCM;
    double xINCHES, yINCHES;
    double xadj, yadj;
    double parentAngle;
    LViewportLocation vpl;
    LViewportContext vpc, parentContext;
    R_GE_gcontext gc, parentgc;
    LTransform thisLocation, thisRotation, thisJustification, thisTransform;
    LTransform tempTransform, parentTransform, transform;
    SEXP currentWidthCM, currentHeightCM, currentRotation;
    SEXP currentTransform;
    /* This should never be true when we are doing an incremental
     * calculation
     */
    if (isNull(parent)) {
	/* We have a top-level viewport; the parent is the device
	 */
	getDeviceSize(dd, &parentWidthCM, &parentHeightCM);
	/* For a device the transform is the identity transform
	 */
	identity(parentTransform);
	/* For a device, xmin=0, ymin=0, xmax=1, ymax=1, and
	 */
	parentContext.xscalemin = 0;
	parentContext.yscalemin = 0;
	parentContext.xscalemax = 1;
	parentContext.yscalemax = 1;
	/* FIXME:  How do I figure out the device fontsize ?
	 * From ps.options etc, ... ?
	 * FIXME:  How do I figure out the device lineheight ??
	 * FIXME:  How do I figure out the device cex ??
	 * FIXME:  How do I figure out the device font ??
	 * FIXME:  How do I figure out the device fontfamily ??
	 */
	parentgc.ps = 10;
	parentgc.lineheight = 1.2;
	parentgc.cex = 1;
	parentgc.fontface = 1;
	parentgc.fontfamily[0] = '\0';
	/* The device is not rotated
	 */
	parentAngle = 0;
	fillViewportLocationFromViewport(vp, &vpl);
    } else {
	/* Get parent transform (etc ...)
	 * If necessary, recalculate the parent transform (etc ...)
	 */
	if (!incremental)
	    calcViewportTransform(parent, viewportParent(parent), 0, dd);
	/* Get information required to transform viewport location
	 */
	parentWidthCM = REAL(viewportWidthCM(parent))[0];
	parentHeightCM = REAL(viewportHeightCM(parent))[0];
	parentAngle = REAL(viewportRotation(parent))[0];
	for (i=0; i<3; i++)
	    for (j=0; j<3; j++)
		parentTransform[i][j] = 
		    REAL(viewportTransform(parent))[i +3*j];
	fillViewportContextFromViewport(parent, &parentContext);
	/* 
	 * Don't get gcontext from parent because the most recent
	 * previous gpar setting may have come from a gTree
	 * So we look at this viewport's parentgpar slot instead
	 * 
	 * WAS gcontextFromViewport(parent, &parentgc);
	 */
	gcontextFromgpar(viewportParentGPar(vp), 0, &parentgc, dd);
	/* In order for the vp to get its vpl from a layout
	 * it must have specified a layout.pos and the parent
	 * must have a layout
	 * FIXME:  Actually, in addition, layout.pos.row and
	 * layout.pos.col must be valid for the layout
	 */
	if ((isNull(viewportLayoutPosRow(vp)) && 
	     isNull(viewportLayoutPosCol(vp))) ||
	    isNull(viewportLayout(parent)))
	    fillViewportLocationFromViewport(vp, &vpl);
	else if (checkPosRowPosCol(vp, parent))
	    calcViewportLocationFromLayout(viewportLayoutPosRow(vp),
					   viewportLayoutPosCol(vp),
					   parent,
					   &vpl);
    }
    /* NOTE that we are not doing a transformLocn here because
     * we just want locations and dimensions (in INCHES) relative to 
     * the parent, NOT relative to the device.
     */
    /* First, convert the location of the viewport into CM
     */
    xINCHES = transformXtoINCHES(vpl.x, 0, parentContext, &parentgc,
				 parentWidthCM, parentHeightCM, 
				 dd);
    yINCHES = transformYtoINCHES(vpl.y, 0, parentContext, &parentgc,
				 parentWidthCM, parentHeightCM, 
				 dd);
    /* Calculate the width and height of the viewport in CM too
     * so that any viewports within this one can do transformations
     */
    vpWidthCM = transformWidthtoINCHES(vpl.width, 0, parentContext, &parentgc,
				       parentWidthCM, parentHeightCM,
				       dd)*2.54;
    vpHeightCM = transformHeighttoINCHES(vpl.height, 0, parentContext, 
					 &parentgc,
					 parentWidthCM, 
					 parentHeightCM, 
					 dd)*2.54;
    /* Fall out if location or size are non-finite
     */
    if (!R_FINITE(xINCHES) || 
	!R_FINITE(yINCHES) || 
	!R_FINITE(vpWidthCM) || 
	!R_FINITE(vpHeightCM))
	error(_("Non-finite location and/or size for viewport"));
    /* Determine justification required
     */
    justification(vpWidthCM, vpHeightCM, vpl.hjust, vpl.vjust,
		  &xadj, &yadj);
    /* Next, produce the transformation to add the location of
     * the viewport to the location.
     */
    /* Produce transform for this viewport
     */
    translation(xINCHES, yINCHES, thisLocation);
    if (viewportAngle(vp) != 0)
	rotation(viewportAngle(vp), thisRotation);
    else
	identity(thisRotation);
    translation(xadj/2.54, yadj/2.54, thisJustification);
    /* Position relative to origin of rotation THEN rotate.
     */
    multiply(thisJustification, thisRotation, tempTransform);
    /* Translate to bottom-left corner.
     */
    multiply(tempTransform, thisLocation, thisTransform);
    /* Combine with parent's transform
     */
    multiply(thisTransform, parentTransform, transform);
    /* Sum up the rotation angles
     */
    rotationAngle = parentAngle + viewportAngle(vp);
    /* Finally, allocate the rows and columns for this viewport's
     * layout if it has one
     */
    if (!isNull(viewportLayout(vp))) {
	fillViewportContextFromViewport(vp, &vpc);
	gcontextFromViewport(vp, &gc, dd);
	calcViewportLayout(vp, vpWidthCM, vpHeightCM, vpc, &gc, dd);
    }
    /* Record all of the answers in the viewport
     * (the layout calculations are done within calcViewportLayout)
     */
    PROTECT(currentWidthCM = ScalarReal(vpWidthCM));
    PROTECT(currentHeightCM = ScalarReal(vpHeightCM));
    PROTECT(currentRotation = ScalarReal(rotationAngle));
    PROTECT(currentTransform = allocMatrix(REALSXP, 3, 3));
    for (i=0; i<3; i++)
	for (j=0; j<3; j++)
	    REAL(currentTransform)[i + 3*j] = transform[i][j];
    SET_VECTOR_ELT(vp, PVP_WIDTHCM, currentWidthCM);
    SET_VECTOR_ELT(vp, PVP_HEIGHTCM, currentHeightCM);
    SET_VECTOR_ELT(vp, PVP_ROTATION, currentRotation);
    SET_VECTOR_ELT(vp, PVP_TRANS, currentTransform);
    UNPROTECT(4);
}
Exemple #25
0
void scaling(double sx, double sy, LTransform m)
{
    identity(m);
    m[0][0] = sx;
    m[1][1] = sy;
}
Exemple #26
0
int zmq::router_t::xsend (msg_t *msg_)
{
    //  If this is the first part of the message it's the ID of the
    //  peer to send the message to.
    if (!more_out) {
        zmq_assert (!current_out);

        //  If we have malformed message (prefix with no subsequent message)
        //  then just silently ignore it.
        //  TODO: The connections should be killed instead.
        if (msg_->flags () & msg_t::more) {

            more_out = true;

            //  Find the pipe associated with the identity stored in the prefix.
            //  If there's no such pipe just silently ignore the message, unless
            //  router_mandatory is set.
            blob_t identity ((unsigned char*) msg_->data (), msg_->size ());
            outpipes_t::iterator it = outpipes.find (identity);

            if (it != outpipes.end ()) {
                current_out = it->second.pipe;
                if (!current_out->check_write ()) {
                    it->second.active = false;
                    current_out = NULL;
                    if (mandatory) {
                        more_out = false;
                        errno = EAGAIN;
                        return -1;
                    }
                }
            }
            else
            if (mandatory) {
                more_out = false;
                errno = EHOSTUNREACH;
                return -1;
            }
        }

        int rc = msg_->close ();
        errno_assert (rc == 0);
        rc = msg_->init ();
        errno_assert (rc == 0);
        return 0;
    }

    //  Ignore the MORE flag for raw-sock or assert?
    if (options.raw_sock)
        msg_->reset_flags (msg_t::more);

    //  Check whether this is the last part of the message.
    more_out = msg_->flags () & msg_t::more ? true : false;

    //  Push the message into the pipe. If there's no out pipe, just drop it.
    if (current_out) {

        // Close the remote connection if user has asked to do so
        // by sending zero length message.
        // Pending messages in the pipe will be dropped (on receiving term- ack)
        if (raw_sock && msg_->size() == 0) {
            current_out->terminate (false);
            int rc = msg_->close ();
            errno_assert (rc == 0);
            rc = msg_->init ();
            errno_assert (rc == 0);
            current_out = NULL;
            return 0;
        }

        bool ok = current_out->write (msg_);
        if (unlikely (!ok))
            current_out = NULL;
        else
        if (!more_out) {
            current_out->flush ();
            current_out = NULL;
        }
    }
    else {
        int rc = msg_->close ();
        errno_assert (rc == 0);
    }

    //  Detach the message from the data buffer.
    int rc = msg_->init ();
    errno_assert (rc == 0);

    return 0;
}
Exemple #27
0
int zmq::xrep_t::xsend (msg_t *msg_, int flags_)
{
    //  If this is the first part of the message it's the ID of the
    //  peer to send the message to.
    if (!more_out) {
        zmq_assert (!current_out);

        //  If we have malformed message (prefix with no subsequent message)
        //  then just silently ignore it.
        //  TODO: The connections should be killed instead.
        if (msg_->flags () & msg_t::more) {

            more_out = true;

            //  Find the pipe associated with the identity stored in the prefix.
            //  If there's no such pipe just silently ignore the message.
            blob_t identity ((unsigned char*) msg_->data (), msg_->size ());
            outpipes_t::iterator it = outpipes.find (identity);

            if (it != outpipes.end ()) {
                current_out = it->second.pipe;
                msg_t empty;
                int rc = empty.init ();
                errno_assert (rc == 0);
                if (!current_out->check_write (&empty)) {
                    it->second.active = false;
                    more_out = false;
                    current_out = NULL;
                }
                rc = empty.close ();
                errno_assert (rc == 0);
            }

        }

        int rc = msg_->close ();
        errno_assert (rc == 0);
        rc = msg_->init ();
        errno_assert (rc == 0);
        return 0;
    }

    //  Check whether this is the last part of the message.
    more_out = msg_->flags () & msg_t::more ? true : false;

    //  Push the message into the pipe. If there's no out pipe, just drop it.
    if (current_out) {
        bool ok = current_out->write (msg_);
        if (unlikely (!ok))
            current_out = NULL;
        else if (!more_out) {
            current_out->flush ();
            current_out = NULL;
        }
    }
    else {
        int rc = msg_->close ();
        errno_assert (rc == 0);
    }

    //  Detach the message from the data buffer.
    int rc = msg_->init ();
    errno_assert (rc == 0);

    return 0;
}
Foam::searchableSurfaces::searchableSurfaces
(
    const IOobject& io,
    const dictionary& topDict
)
    :
    PtrList<searchableSurface>(topDict.size()),
    names_(topDict.size()),
    regionNames_(topDict.size()),
    allSurfaces_(identity(topDict.size()))
{
    label surfI = 0;
    forAllConstIter(dictionary, topDict, iter)
    {
        const word& key = iter().keyword();

        if (!topDict.isDict(key))
        {
            FatalErrorIn
            (
                "searchableSurfaces::searchableSurfaces"
                "( const IOobject&, const dictionary&)"
            )   << "Found non-dictionary entry " << iter()
                << " in top-level dictionary " << topDict
                << exit(FatalError);
        }

        const dictionary& dict = topDict.subDict(key);

        names_[surfI] = key;
        dict.readIfPresent("name", names_[surfI]);

        // Make IOobject with correct name
        autoPtr<IOobject> namedIO(io.clone());
        // Note: we would like to e.g. register triSurface 'sphere.stl' as
        // 'sphere'. Unfortunately
        // no support for having object read from different location than
        // their object name. Maybe have stlTriSurfaceMesh which appends .stl
        // when reading/writing?
        namedIO().rename(key);  // names_[surfI]

        // Create and hook surface
        set
        (
            surfI,
            searchableSurface::New
            (
                dict.lookup("type"),
                namedIO(),
                dict
            )
        );
        const searchableSurface& s = operator[](surfI);

        // Construct default region names by prepending surface name
        // to region name.
        const wordList& localNames = s.regions();

        wordList& rNames = regionNames_[surfI];
        rNames.setSize(localNames.size());

        forAll(localNames, regionI)
        {
            rNames[regionI] = names_[surfI] + '_' + localNames[regionI];
        }

        // See if dictionary provides any global region names.
        if (dict.found("regions"))
        {
            const dictionary& regionsDict = dict.subDict("regions");

            forAllConstIter(dictionary, regionsDict, iter)
            {
                const word& key = iter().keyword();

                if (regionsDict.isDict(key))
                {
                    // Get the dictionary for region iter.keyword()
                    const dictionary& regionDict = regionsDict.subDict(key);

                    label index = findIndex(localNames, key);

                    if (index == -1)
                    {
                        FatalErrorIn
                        (
                            "searchableSurfaces::searchableSurfaces"
                            "( const IOobject&, const dictionary&)"
                        )   << "Unknown region name " << key
                            << " for surface " << s.name() << endl
                            << "Valid region names are " << localNames
                            << exit(FatalError);
                    }

                    rNames[index] = word(regionDict.lookup("name"));
                }
            }
        }

        surfI++;
    }
Exemple #29
0
 eMatrix4x4()
 {
     identity();
 }
Exemple #30
0
void rotate(Vec rot, Matrix mat)
{
	identity(mat);
	//Move rotation into our new matrix
	//This code is not optimized.
	if (rot[0] != 0.0) {
		//
		//rotate on x-axis
		//
		//      x     y     z
		//   |-----|-----|-----|-----|
		// x |  1  |     |     |     |
		//   |-----|-----|-----|-----|
		// y |     | cos | sin |     |
		//   |-----|-----|-----|-----|
		// z |     |-sin | cos |     |
		//   |-----|-----|-----|-----|
		//   |     |     |     |  1  |
		//   |-----|-----|-----|-----|
		//
		mat[1][1] =  cos(rot[0]);
		mat[1][2] =  sin(rot[0]);
		mat[2][1] = -sin(rot[0]);
		mat[2][2] =  cos(rot[0]);
	}
	if (rot[1] != 0.0) {
		//
		//rotate on y-axis
		//
		//      x     y     z
		//   |-----|-----|-----|-----|
		// x | cos |     |-sin |     |
		//   |-----|-----|-----|-----|
		// y |     |  1  |     |     |
		//   |-----|-----|-----|-----|
		// z | sin |     | cos |     |
		//   |-----|-----|-----|-----|
		//   |     |     |     |  1  |
		//   |-----|-----|-----|-----|
		//
		mat[0][0] =  cos(rot[1]);
		mat[0][2] = -sin(rot[1]);
		mat[2][0] =  sin(rot[1]);
		mat[2][2] =  cos(rot[1]);
	}
	if (rot[2] != 0.0) {
		//
		//rotate on z-axis
		//
		//      x     y     z
		//   |-----|-----|-----|-----|
		// x | cos | sin |     |     |
		//   |-----|-----|-----|-----|
		// y |-sin | cos |     |     |
		//   |-----|-----|-----|-----|
		// z |     |     |  1  |     |
		//   |-----|-----|-----|-----|
		//   |     |     |     |  1  |
		//   |-----|-----|-----|-----|
		//
		mat[0][0] =  cos(rot[2]);
		mat[0][1] =  sin(rot[2]);
		mat[1][0] = -sin(rot[2]);
		mat[1][1] =  cos(rot[2]);
	}
}