Esempio n. 1
0
File: cube.c Progetto: huoyao/libigl
/* display cube */
void updateCube(pCube cube,pMesh mesh) {
    pScene      sc;
    pTransform  cubetr,view;
    GLfloat     inv[16],axis[4],trans[4];
    int         idw;

    /* default */
    if ( ddebug ) printf("updateCube\n");

    /* retrieve context */
    idw    = currentScene();
    sc     = cv.scene[idw];
    view   = sc->view;
    cubetr = cube->cubetr;

    /* compute cube transform */
    if ( cube->active & C_EDIT ) {
        invertMatrix(view->matrix,inv);
        inv[3] = inv[7] = inv[11] = 0.0f;
        inv[15] = 1.0;

        /* rotation cumulative */
        if ( cubetr->angle != 0.0 ) {
            transformVector(trans,cubetr->axis,inv);
            glPushMatrix();
            glLoadIdentity();
            glRotatef(cubetr->angle,trans[0],trans[1],trans[2]);
            glMultMatrixf(cubetr->rot);
            glGetFloatv(GL_MODELVIEW_MATRIX,cubetr->rot);
            glPopMatrix();
        }

        /* translation cumulative */
        axis[0] = cubetr->panx;
        axis[1] = cubetr->pany;
        axis[2] = 0.0;
        axis[3] = 1.0;
        transformVector(trans,axis,inv);

        cubetr->tra[12] = trans[0];
        cubetr->tra[13] = trans[1];
        cubetr->tra[14] = trans[2];

        /* final transformation */
        glPushMatrix();
        glLoadIdentity();
        glMultMatrixf(cubetr->tra);
        glMultMatrixf(cubetr->rot);
        glGetFloatv(GL_MODELVIEW_MATRIX,cubetr->matrix);
        glPopMatrix();
    }
    if ( !cubetr->manim ) {
        cubetr->angle = 0.0;
        cube->active ^= C_UPDATE;
    }
}
	//----------------------------------------------------------------------
	void SpaceGameActor::applyForwardImpulse()
	{
		vec3f impulseInDirOfShip = transformVector( vec3f( 0.0f, IMPULSE_POWER, 0.0f ), getLocalRotation() );
		
		m_vel += vec2f( impulseInDirOfShip.x, impulseInDirOfShip.y );
		m_forcesAppliedBitFlags |= APPLY_FORWARD_IMPULSE;
	}
	//----------------------------------------------------------------------
	void SpaceGameActor::applyReverseImpulse()
	{
		m_forwardImpulse -= 1.0f;
		vec3f impulseInDirOfShip = transformVector( vec3f( 0.0f, -IMPULSE_POWER, 0.0f ), getLocalRotation() );

		m_vel += vec2f( impulseInDirOfShip.x, impulseInDirOfShip.y );
		m_forcesAppliedBitFlags |= APPLY_REVERSE_IMPULSE;
	}
Esempio n. 4
0
Ray Matrix4x4::transformRay(const Ray &r) const
{
    Ray transformedRay = r;
    Vector3D transformedOrigin = transformPoint(r.o);
    Vector3D transformedDir    = transformVector(r.d);

    transformedRay.o = transformedOrigin;
    transformedRay.d = transformedDir;

    return transformedRay;
}
Esempio n. 5
0
void matrix4x4f::transform(vector4f *v) {
	//we should save these values because transformVector changes the vector v
	float x = v->vec.x,
		  y = v->vec.y,
		  z = v->vec.z,
		  w = v->w;
//	printf("before:<%f,%f,%f,%f>\n", v->vec.x, v->vec.y, v->vec.z, v->w);

	//3D part
	transformVector(&(v->vec));
	//finish him with w coordinate
	v->vec.x += v->w * m[12];
	v->vec.y += v->w * m[13];
	v->vec.z += v->w * m[14];
//	printf("after:<%f,%f,%f,%f>\n", v->vec.x, v->vec.y, v->vec.z, v->w);

	v->w = m[3]*(x) + m[7]*(y) + m[11]*(z) + m[15]*(w);
//	printf("forgoten w:<%f,%f,%f,%f>\n", v->vec.x, v->vec.y, v->vec.z, v->w);
}
Esempio n. 6
0
geometry_msgs::Pose transformPose(geometry_msgs::Pose pose_in, Eigen::Matrix4f transf){
    geometry_msgs::Pose pose_out;
    // Obtener rotación desde matriz de transformación
    Eigen::Matrix4f rot;
    rot = transf;
    rot.col(3) = Eigen::Vector4f(0, 0, 0, 1);
    // Crear normal desde quaternion
    tf::Quaternion tf_q;
    tf::quaternionMsgToTF(pose_in.orientation, tf_q);
    tf::Vector3 normal(1, 0, 0);
    normal = tf::quatRotate(tf_q, normal);
    normal.normalize();
    // Rotar normal
    Eigen::Vector3f normal_vector (normal.x(), normal.y(), normal.z());
    Eigen::Vector3f normal_rotated = transformVector(normal_vector, transf);
    normal_rotated.normalize();
    // Obtener quaternion desde normal rotada
    pose_out.orientation = coefsToQuaternionMsg(normal_rotated[0], normal_rotated[1], normal_rotated[2]);
    // Transportar posición
    pose_out.position = transformPoint(pose_in.position, transf);
    return pose_out;
}
	//----------------------------------------------------------------------
	void SpaceGameActor::update( double deltaTime )
	{
		Actor::update( deltaTime );
		m_wasSpawnedLastFrame = false;

		float dt = static_cast< float >( deltaTime );

		setRotation( mat3f::createMatrixFromQuaternion( quatf::makeQuaternionFromAxisAngle( MathFuncs<float>::degreesToRadians( m_rotation ), vec3f( 0.0f, 0.0f, 1.0f ) ) ) );

		//vec3f impulseInDirOfShip = transformVector( vec3f( 0.0f, IMPULSE_POWER, 0.0f ), getLocalRotation() );
		//impulseInDirOfShip *= m_forwardImpulse;
		//
		//m_vel += vec2f( impulseInDirOfShip.x, impulseInDirOfShip.y );
		m_frames[ m_currentFrame ].position += m_vel*dt;	
		m_vel -= m_vel * m_drag * dt;
		//m_forwardImpulse = 0.0f;

		m_frames[ m_currentFrame ].position.x = (float)MathFuncs<int>::wrap( (int)m_frames[ m_currentFrame ].position.x, 0, SCREEN_WIDTH );
		m_frames[ m_currentFrame ].position.y = (float)MathFuncs<int>::wrap( (int)m_frames[ m_currentFrame ].position.y, 0, SCREEN_HEIGHT );

		vec3f tempDir = transformVector( vec3f( 0.0f, 1.0f, 0.0f ), getLocalRotation() );
		tempDir.normalize();
		m_dir = vec2f( tempDir.x, tempDir.y );
	}
Esempio n. 8
0
void Matrix::transformVector(const Vector3& vector, Vector3* dst) const
{
    transformVector(vector.x, vector.y, vector.z, 0.0f, dst);
}
Esempio n. 9
0
void Matrix::transformVector(Vector3* vector) const
{
    GP_ASSERT(vector);
    transformVector(vector->x, vector->y, vector->z, 0.0f, vector);
}
Esempio n. 10
0
void Matrix::transformPoint(const Vector3& point, Vector3* dst) const
{
    transformVector(point.x, point.y, point.z, 1.0f, dst);
}
Esempio n. 11
0
void Matrix::transformPoint(Vector3* point) const
{
    GP_ASSERT(point);
    transformVector(point->x, point->y, point->z, 1.0f, point);
}
Esempio n. 12
0
	//-------------------------------------------
	void Camera::update( double deltaTime )
	{	
		Node::update( deltaTime );
		m_dir = transformVector( vec3f( 0.0f, 0.0f, -1.0f ), getLocalRotation() );
	}
wxThread::ExitCode  HaloRenderingThread::Entry()
{
    wxCommandEvent evt(wxEVT_HALO_RENDERING_THREAD_NOTIFY, wxID_ANY);

    setupStruct.resultValid = false;
    setupStruct.imageBuffer = 0;
    setupStruct.rayPaths = new map<RayPathId, RayPathDescriptor>;

    if (setupStruct.crystals.size() == 0)
    {
        evt.SetString(wxT("No crystal population set up."));
        evt.SetInt(1);
        setupStruct.notifee->AddPendingEvent(evt);
        return 0;
    }

    // Cast rays on crystals and refracted rays will form a pixel.

    int crystalTypeIndex = 0;
    CrystalDescriptor *currentDescriptor = &setupStruct.crystals[0];
    const int N_CRYSTAL_TYPES = setupStruct.crystals.size();
    int crystalsRemaining = currentDescriptor->populationWeight;
    Mesh currentMesh;
    size_t percentStep = setupStruct.crystalCount / 100;
    if (percentStep < 1) percentStep = 1;
    Vector3 sunPos(0, 0, -100000);
    rotate2d(sunPos.y, sunPos.z, setupStruct.solarAltitude * 3.14159265636 / 180.0);
    // Two prependicular vector
    Vector3 prepX = sunPos % Vector3(0, 1, 0); // FIXME: Sun on the zenith
    Vector3 prepY = sunPos % prepX;
    prepX /= ~prepX;
    prepY /= ~prepY;
    setupStruct.deleteBuffer = freeBuffer;
    setupStruct.deleteMap = freeMap;
    size_t size = setupStruct.imageSize;
    setupStruct.imageBuffer = new uint32_t[size * size * 6];
    memset(setupStruct.imageBuffer, 0, size * size * 6 * sizeof(uint32_t));
    uint32_t *leftPlane = setupStruct.imageBuffer; // 0th plane
    uint32_t *rightPlane = setupStruct.imageBuffer + size * size; // 1st plane
    uint32_t *topPlane = setupStruct.imageBuffer + 2 * size * size; // 2nd plane
    uint32_t *bottomPlane = setupStruct.imageBuffer + 3 * size * size; // 3rd plane
    uint32_t *backPlane = setupStruct.imageBuffer + 4 * size * size; // 4th plane
    uint32_t *frontPlane = setupStruct.imageBuffer + 5 * size * size; // 5th plane
    double halfImageSize = size * 0.5;
    int maxRays = (setupStruct.maxRayCastInfoSize * 1000000) / (sizeof(RayPathDescriptor) + sizeof(RayPathId));
    if (maxRays == 0) maxRays = 1;
    int recordRayModulus = setupStruct.crystalCount / maxRays;
    if (!recordRayModulus) recordRayModulus = 1;

    struct RefractionColor
    {
        int rgb;
        double refractionIndex;
    };

    RefractionColor colors[] =
    {
        { 0x0000FF, 1.3072 },
        { 0x0080FF, 1.3094 },
        { 0x00FFFF, 1.31 },
        { 0x00FF80, 1.3107 },
        { 0x00FF00, 1.3114 },
        { 0x80FF00, 1.3125 },
        { 0xFFFF00, 1.3136 },
        { 0xFF8000, 1.3147 },
        { 0xFF0000, 1.3158 },
        { 0xFF0040, 1.3172 },
        { 0xFF0080, 1.32 },
    };

    const int N_COLORS = sizeof(colors) / sizeof(colors[0]);

    // Cast many rays.
    for (size_t i = 0; i < setupStruct.crystalCount; i++)
    {
        if (setupStruct.cancelled)
        {
            // If the user shut the rendering down...
            delete[] setupStruct.imageBuffer;
            setupStruct.imageBuffer = 0;
            return 0;
        }
        if (!crystalsRemaining)
        {
            // We iterate through the crystals based on their population weights.
            crystalTypeIndex++;
            if (crystalTypeIndex >= N_CRYSTAL_TYPES) crystalTypeIndex = 0;
            currentDescriptor = &setupStruct.crystals[crystalTypeIndex];
            crystalsRemaining = currentDescriptor->populationWeight;
        }
        // Get the raw mesh
        currentMesh = currentDescriptor->mesh;
        // Rotate it according to the orientation.
        Matrix orientationMatrix = getOrientationMatrix(currentDescriptor->orientation);
        // Apply wobbliness
        Vector3 wobbleRotationAxis(1, 0, 0);
        rotate2d(wobbleRotationAxis.x, wobbleRotationAxis.z, randFloat(0, 3.1415));
        double wobblinessLimit = currentDescriptor->wobbliness * 3.1415 / 180.0;
        Matrix wobbleMatrix = createRotationMatrix(
            wobbleRotationAxis,
            randFloatNormal(
                0,
                wobblinessLimit
            )
        );
        Matrix transformation = orientationMatrix % wobbleMatrix;
        transformMesh(currentMesh, transformation);

        // Crystal created, now cast a ray on it.
        Vector3 offset = prepX * randFloat(-1, 1) + prepY * randFloat(-1, 1);
        vector<RayPath> rayPaths;
        // Compute color here
        double colorCode = randFloat(0, N_COLORS - 1);
        RefractionColor prev = colors[(int)(floor(colorCode))];
        RefractionColor next = colors[(int)(ceil(colorCode))];
        double kColor = colorCode - floor(colorCode);
        RefractionColor currentColor;
        currentColor.rgb = prev.rgb;
        currentColor.refractionIndex = (1 - kColor) * prev.refractionIndex + kColor * next.refractionIndex;
        // Compute real poisition of the ray (Sun is a disk)
        Vector3 realSunPos = sunPos;
        Vector3 rayRotVector;
        double rayRotVectorLength;
        do
        {
            rayRotVector = realSunPos % getRandomVector();
            rayRotVectorLength = ~rayRotVector;
        }
        while (rayRotVectorLength == 0);
        rayRotVector /= rayRotVectorLength;
        realSunPos = transformVector(
            createRotationMatrix(
                rayRotVector,
                randFloat(
                    0,
                    setupStruct.solarDiskRadius * 3.1415926536 / 180.0
                )
            ),
            realSunPos
        );
        computeRayPathInGlassMesh(currentMesh, currentColor.refractionIndex, realSunPos + offset, -realSunPos, 0.01, rayPaths);
        /* Project rays on the six planes. */
        for (size_t j = 0; j < rayPaths.size(); j++)
        {
            RayPath &current = rayPaths[j];
            size_t pathLength = current.size();

            Vector3 exitDir = current[pathLength - 1].first - current[pathLength - 2].first;
            Vector3 projectionDir = -exitDir;

            double xPos, yPos;
            // select the plane to project on.
            uint32_t *plane;
            double xm = 1, ym = 1;
            int planeId;
            if ((fabs(projectionDir.x) > fabs(projectionDir.y)) && (fabs(projectionDir.x) > fabs(projectionDir.z)))
            {
                if (projectionDir.x < 0)
                {
                    plane = leftPlane;
                    planeId = 0;
                    xm = -1;
                }
                else
                {
                    plane = rightPlane;
                    planeId = 1;
                }
                xPos = xm * projectionDir.z / fabs(projectionDir.x) * halfImageSize + halfImageSize;
                yPos = -ym * projectionDir.y / fabs(projectionDir.x) * halfImageSize + halfImageSize;
            }
            if ((fabs(projectionDir.y) > fabs(projectionDir.x)) && (fabs(projectionDir.y) > fabs(projectionDir.z)))
            {
                if (projectionDir.y < 0)
                {
                    plane = bottomPlane;
                    planeId = 3;
                    ym = -1;
                }
                else
                {
                    plane = topPlane;
                    planeId = 2;
                }
                xPos = xm * projectionDir.x / fabs(projectionDir.y) * halfImageSize + halfImageSize;
                yPos = -ym * projectionDir.z / fabs(projectionDir.y) * halfImageSize + halfImageSize;
            }
            if ((fabs(projectionDir.z) > fabs(projectionDir.x)) && (fabs(projectionDir.z) > fabs(projectionDir.y)))
            {
                if (projectionDir.z < 0)
                {
                    plane = frontPlane;
                    planeId = 5;
                }
                else
                {
                    plane = backPlane;
                    planeId = 4;
                    xm = -1;
                }
                xPos = xm * projectionDir.x / fabs(projectionDir.z) * halfImageSize + halfImageSize;
                yPos = -ym * projectionDir.y / fabs(projectionDir.z) * halfImageSize + halfImageSize;
            }
            // Calculate the new intensity of the pixel.
            xPos = clampInInt(xPos, 0, size - 1);
            yPos = clampInInt(yPos, 0, size - 1);
            int prevPixel = plane[(int)(yPos) * size + (int)(xPos)];
            int nextPixel = 0;
            double intensity = current[pathLength - 2].second * 20;
            for (int j = 0; j < 3; j++)
            {
                int currentSaturation = (prevPixel >> (8 * j)) & 0xFF;
                int toAdd = (int)(((currentColor.rgb >> (8 * j)) & 0xFF) * intensity) >> 8;
                int nextSaturation;
                if (currentSaturation + toAdd > 255) nextSaturation = 255;
                else nextSaturation = currentSaturation + toAdd;
                nextPixel += (1 << (8 * j)) * nextSaturation * setupStruct.pixelIntensity;
            }
            plane[(int)(yPos) * size + (int)(xPos)] = nextPixel;
            // Record the ray if needed
            if (!(i % recordRayModulus))
            {
                RayPathId pixelId(planeId, (int)xPos, (int)yPos);
                RayPathDescriptor theDescriptor(
                    &currentDescriptor->mesh,
                    transformation,
                    realSunPos + offset,
                    -realSunPos,
                    intensity
                );
                map<RayPathId, RayPathDescriptor>::iterator it = setupStruct.rayPaths->find(pixelId);
                if (it == setupStruct.rayPaths->end())
                {
                    // If not found, insert it as new
                    setupStruct.rayPaths->insert(
                        make_pair(
                            pixelId,
                            theDescriptor
                        )
                    );
                }
                else if (it->second.intensity < intensity)
                {
                    // If found, update it if the current ray is more intense
                    it->second = theDescriptor;
                }
            }
        }

        if (i % percentStep == 0)
        {
            sendNotifyString(wxString::Format(wxT("Casting rays: %d%%"), i / percentStep));
        }

        crystalsRemaining--;
    }


    evt.SetString(wxT("Completed."));
    evt.SetInt(1); //< 1 means the operation is finished.
    setupStruct.resultValid = true;
    setupStruct.notifee->AddPendingEvent(evt);
    return 0;
}
Esempio n. 14
0
File: Matrix.cpp Progetto: cn00/MJ
void Matrix::transformVector(Vector4* vector) const
{
    transformVector(*vector, vector);
}
Esempio n. 15
0
void Matrix::transformVector(Vector4* vector) const
{
    GP_ASSERT(vector);
    transformVector(*vector, vector);
}
void RSPVertexManager::_processVertex( unsigned int v )
{
//    float intensity;
//    float r, g, b;

    transformVertex( m_matrixMgr->getViewProjectionMatrix(), &m_vertices[v].x, &m_vertices[v].x);
    //TransformVertex( &m_vertices[v].x, m_worldProject );


    if ( m_billboard )
    {
        m_vertices[v].x += m_vertices[0].x;
        m_vertices[v].y += m_vertices[0].y;
        m_vertices[v].z += m_vertices[0].z;
        m_vertices[v].w += m_vertices[0].w;
    }


    if ( !OpenGLManager::getSingleton().getZBufferEnabled() )
    {
        m_vertices[v].z = -m_vertices[v].w;
    }

    //Temporary variables
    float intensity;
    float r, g, b;

    if ( m_lightMgr->getLightEnabled() )
    {
        //Transform normal
        transformVector( m_matrixMgr->getModelViewMatrix(), &m_vertices[v].nx, &m_vertices[v].nx );
        Vec3Normalize( &m_vertices[v].nx );

        //Get Ambient Color
        const float* ambientColor = m_lightMgr->getAmbientLight();
        r = ambientColor[0];
        g = ambientColor[1];
        b = ambientColor[2];

        for (int i=0; i<m_lightMgr->getNumLights(); ++i)
        {
            intensity = DotProduct( (float*)&m_vertices[v].nx, (float*)m_lightMgr->getLightDirection(i) );

            if (intensity < 0.0f) intensity = 0.0f;

            const float* lightColor = m_lightMgr->getLightColor(i);
            r += lightColor[0] * intensity;
            g += lightColor[1] * intensity;
            b += lightColor[2] * intensity;
        }

        //Set Color
        m_vertices[v].r = r;
        m_vertices[v].g = g;
        m_vertices[v].b = b;    
    }

    //Texture Generation
    if ( m_texCoordGenType != TCGT_NONE )
    {
        transformVector( m_matrixMgr->getProjectionMatrix(), &m_vertices[v].nx, &m_vertices[v].nx );

        Vec3Normalize( &m_vertices[v].nx );

        if ( m_texCoordGenType == TCGT_LINEAR )
        {   
            m_vertices[v].s = acosf(m_vertices[v].nx) * 325.94931f;
            m_vertices[v].t = acosf(m_vertices[v].ny) * 325.94931f;
        }
        else // TGT_GEN
        {
            m_vertices[v].s = (m_vertices[v].nx + 1.0f) * 512.0f;
            m_vertices[v].t = (m_vertices[v].ny + 1.0f) * 512.0f;
        }
    }

    //Clipping
    if (m_vertices[v].x < -m_vertices[v].w)  
        m_vertices[v].xClip = -1.0f;
    else if (m_vertices[v].x > m_vertices[v].w)
        m_vertices[v].xClip = 1.0f;
    else
        m_vertices[v].xClip = 0.0f;

    if (m_vertices[v].y < -m_vertices[v].w)
        m_vertices[v].yClip = -1.0f;
    else if (m_vertices[v].y > m_vertices[v].w)
        m_vertices[v].yClip = 1.0f;
    else
        m_vertices[v].yClip = 0.0f;

    if (m_vertices[v].w <= 0.0f)
        m_vertices[v].zClip = -1.0f;
    else if (m_vertices[v].z < -m_vertices[v].w)
        m_vertices[v].zClip = -0.1f;
    else if (m_vertices[v].z > m_vertices[v].w)
        m_vertices[v].zClip = 1.0f;
    else
        m_vertices[v].zClip = 0.0f;

}
void CrystalEditorFrame::OnMouseMove(wxMouseEvent& event)
{
    if (!dragging) return;

    // Turn mouse movement to a movement of a virtual trackball (which is as big as the window).
    Vector3 currentMousePos(event.GetX(), event.GetY(), 0);
    int width, height;
    GetSize(&width, &height);
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, width);
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, height);
    double windowSize = std::min(width, height);
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, windowSize);
    Vector3 center(0.5 * width, 0.5 * height, 0);
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, center);
    Vector3 normPrevPos = (prevMousePos - center) / windowSize;
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, normPrevPos);
    Vector3 normPos = (currentMousePos - center) / windowSize;
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, normPos);
    // Invert vertical axis, because in camera space Y grow upward.
    normPrevPos.y = -normPrevPos.y;
    normPos.y = -normPos.y;
    // Calculate the Z position on the trackball
    normPrevPos.z = normPrevPos * normPrevPos <= 1 ? sqrt(1.0 - normPrevPos * normPrevPos) : 0;
    normPos.z = normPos * normPos <= 1 ? sqrt(1.0 - normPos * normPos) : 0;
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, normPrevPos);
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, normPos);
    // Calculate the rotation axis
    Vector3 rotAxis = normPrevPos % normPos;
    double rotAxisLength = ~rotAxis;
    if (rotAxisLength == 0)
    {
        // No rotation.
        return;
    }
    rotAxis /= rotAxisLength;
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, rotAxis);
    // Calculate the real rotation axis and the angle.
    double rotAngle = acos((normPrevPos * normPos)/(~normPrevPos * ~normPos));
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, rotAngle);
    Vector3 realRotAxis = rotAxis.x * right + rotAxis.y * upward + rotAxis.z * backward; // Create the true rotation axis (in camera space).
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, realRotAxis);

    Matrix rotation = createRotationMatrix(realRotAxis, -rotAngle); // Negative as we rotate the view, not the object
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, rotation);

    backward = transformVector(rotation, backward);
    right = transformVector(rotation, right);
    upward = transformVector(rotation, upward);
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, backward);
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, right);
    log_var(CRYSTAL_EDITOR_MOUSE_MOVE, upward);

    fix3VectorSystem(right, upward, backward);

    prevMousePos.x = event.GetX();
    prevMousePos.y = event.GetY();
    prevMousePos.z = 0;

    // Calculate ray path

    updateRayPaths();

    mainPanel->Refresh();
    log_printf(CRYSTAL_EDITOR_MOUSE_MOVE, "========================\n");
}
Esempio n. 18
0
bool ModelMd2::load(const char* filename, TextureDirectory& textureDirectory, const bool justData)
{
	std::ifstream file(filename, std::ios::in | std::ios::binary);

	if (file.fail())
	{
		return false;
	}

	int fileSize;
	file.seekg(0, std::ios::end);
	fileSize = file.tellg();
	file.seekg(0, std::ios::beg);

	char* buffer = new char[fileSize];
	file.read((char*) buffer, fileSize);
	file.close();

	// header
	Header* header = reinterpret_cast<Header*>(buffer);
	if ((header->magic != MD2_MAGIC_NUM) && (header->version != 8))
	{
		file.close();
		return false;
	}

	m_numTexCoords = header->numTexCoords;
	m_numVertices  = header->numVertices;
	m_numTriangles = header->numTriangles;

	int numFrames = header->numFrames;

	// texcoords
	TexcoordMd2* tmptex = new TexcoordMd2[m_numTexCoords];
	memcpy(tmptex, &buffer[header->offsetTexCoords], m_numTexCoords * sizeof(TexcoordMd2));

	m_pTexcoords = new texCoord[m_numTexCoords];
	for (int i = 0; i < m_numTexCoords; i++)
	{
		m_pTexcoords[i].u = (float) tmptex[i].s / header->skinWidth;
		m_pTexcoords[i].v = -(float) tmptex[i].t / header->skinHeight;
	}
	delete[] tmptex;
	m_pTexcoordArray = new texCoord[m_numTriangles * 3];							// one vertex can have more texture coordinates (eg. a corner of a cube)

	// triangles
	m_pTriangles = new TriangleMd2[m_numTriangles];
	memcpy(m_pTriangles, &buffer[header->offsetTriangles], m_numTriangles * sizeof(TriangleMd2));

	// vertices
	m_pVertices = new vec3[numFrames * m_numVertices];
	m_pVertexArray = new vec3[m_numTriangles * 3];

	// normal vectors
	m_pNormals = new vec3[numFrames * m_numVertices];
	m_pNormalArray = new vec3[m_numTriangles * 3];

	// tangent vectors
	m_pTangents = new vec3[numFrames * m_numVertices];
	m_pTangentArray = new vec3[m_numTriangles * 3];

	// precalculated normal vectors
	float anorms[162][3] =
	{
#include "anorms.h"
	};

	FrameMd2* frame;
	std::string lastname;
	std::string filteredLastname;

	// animációk, vertexek kiolvasása, beállítása
	for (int i = 0; i < numFrames; i++)
	{
		frame = (FrameMd2*) &buffer[ header->offsetFrames + i * header->frameSize ];

		// az azonos nevű frameket egy animációba pakoljuk (pl. stand_1, stand_2 ...)
		if (lastname == "" || strncmp(lastname.c_str(), frame->name, lastname.size()) > 0)
		{
			lastname = frame->name;

			if (lastname[lastname.size() - 2] == '0')			// eg. stand01
			{
				lastname.resize(lastname.size() - 2);
			}
			else
			{
				lastname.resize(lastname.size() - 1);
			}

			filteredLastname = lastname;
			filteredLastname.resize( std::remove_if(filteredLastname.begin(), filteredLastname.end(), filter) - filteredLastname.begin() );

			m_numAnims++;
			m_animations[filteredLastname].start = i;
			m_animations[filteredLastname].end   = -1;
		}
		m_animations[filteredLastname].end++;

		for (int j = 0; j < m_numVertices; j++)
		{
			m_pVertices[ i * m_numVertices + j ].x = (frame->verts[j].v[0] * frame->scale[0]) + frame->translate[0];
			m_pVertices[ i * m_numVertices + j ].y = (frame->verts[j].v[1] * frame->scale[1]) + frame->translate[1];
			m_pVertices[ i * m_numVertices + j ].z = (frame->verts[j].v[2] * frame->scale[2]) + frame->translate[2];

			m_pVertices[ i * m_numVertices + j ] = transformVector(m_pVertices[ i * m_numVertices + j ], vec3(0.0f), vec3(90, 90, 0));

			const float* normals = anorms[frame->verts[j].normalIndex];
			m_pNormals[ i * m_numVertices + j ] = vec3(normals[0], normals[1], normals[2]);
		}


		// calculate tangent vectors
		vec3 tangent, bitangent;
		for (int j = 0; j < m_numTriangles; j++)
		{
			calculateTangent(m_pVertices[ i * m_numVertices + m_pTriangles[j].vertIdx[2] ], m_pVertices[ i * m_numVertices + m_pTriangles[j].vertIdx[1] ], m_pVertices[ i * m_numVertices + m_pTriangles[j].vertIdx[0] ],
			                 m_pTexcoords[ m_pTriangles[j].texIdx[2] ], m_pTexcoords[ m_pTriangles[j].texIdx[1] ], m_pTexcoords[ m_pTriangles[j].texIdx[0] ],
			                 tangent, bitangent);

			m_pTangents[ i * m_numVertices + m_pTriangles[j].vertIdx[0] ] = m_pTangents[ i * m_numVertices + m_pTriangles[j].vertIdx[1] ] = m_pTangents[ i * m_numVertices + m_pTriangles[j].vertIdx[2] ] = tangent;
		}
	}

	int v_i = 0;
	for (int j = 0; j < m_numTriangles; j++)
	{
		m_pNormalArray[v_i] = m_pNormals[ m_pTriangles[j].vertIdx[2] ];
		m_pNormalArray[v_i + 1] = m_pNormals[ m_pTriangles[j].vertIdx[1] ];
		m_pNormalArray[v_i + 2] = m_pNormals[ m_pTriangles[j].vertIdx[0] ];

		m_pTexcoordArray[v_i] = m_pTexcoords[ m_pTriangles[j].texIdx[2] ];
		m_pTexcoordArray[v_i + 1] = m_pTexcoords[ m_pTriangles[j].texIdx[1] ];
		m_pTexcoordArray[v_i + 2] = m_pTexcoords[ m_pTriangles[j].texIdx[0] ];

		v_i += 3;
	}

	// load textures
	if (!justData)
	{
		// the name of the texture is usually not stored n the file
		char textureNameTmp[64];
		memcpy(textureNameTmp, &buffer[header->offsetSkins], 64 * sizeof(char));


		std::string locationtemp = utils::file::getDir(std::string(filename));
		std::string textureName(textureNameTmp);
		utils::toLowerCase(textureName);

		std::string textemp = locationtemp + textureName;

		if (textemp.length() > locationtemp.length())
		{
			// texture map
			loadTexture((char*) textemp.c_str(), m_decalMap, textureDirectory);

			// normalheight map
			std::string nhtemp = locationtemp + utils::file::getFileName(textemp) + "_nh.png";

			if (!loadTexture((char*) nhtemp.c_str(), m_normalHeightMap, textureDirectory))
			{
				// no nh texture -> use the blank texture
				m_normalHeightMap = 0;
			}
		}
	}

	delete[] buffer;

	return true;
}
Esempio n. 19
0
File: Matrix.cpp Progetto: cn00/MJ
void Matrix::transformVector(Vector3* vector) const
{
    transformVector(vector->x, vector->y, vector->z, vector);
}