Example #1
0
void VolumeRenderable::_notifyCurrentCamera( Camera* cam )
{
	MovableObject::_notifyCurrentCamera(cam);

	// Fake orientation toward camera
	Vector3 zVec = getParentNode()->_getDerivedPosition() - cam->getDerivedPosition();
	zVec.normalise();
	Vector3 fixedAxis = cam->getDerivedOrientation() * Vector3::UNIT_Y ;
	
	Vector3 xVec = fixedAxis.crossProduct( zVec );
	xVec.normalise();

	Vector3 yVec = zVec.crossProduct( xVec );
	yVec.normalise();
	
	Quaternion oriQuat;
	oriQuat.FromAxes( xVec, yVec, zVec );
	
	oriQuat.ToRotationMatrix(mFakeOrientation);
	
	Matrix3 tempMat;
	Quaternion q = getParentNode()->_getDerivedOrientation().UnitInverse() * oriQuat ;
	q.ToRotationMatrix(tempMat);
	
	Matrix4 rotMat = Matrix4::IDENTITY;
	rotMat = tempMat;
	rotMat.setTrans(Vector3(0.5f, 0.5f, 0.5f));
	mUnit->setTextureTransform(rotMat);
}
Matrix44 Matrix44::LookAt(Vector3 camera, Vector3 target, Vector3 up)
{
	Matrix44 modelView, rotation, translation;

	Vector3 forward = target - camera;
	forward.normalize();
	up.normalize();
	Vector3 left = forward.crossProduct(up);
	left.normalize();
	up = left.crossProduct(forward);
	up.normalize();

	rotation(0, 0) = left.x;
	rotation(0, 1) = left.y;
	rotation(0, 2) = left.z;
	rotation(1, 0) = up.x;
	rotation(1, 1) = up.y;
	rotation(1, 2) = up.z;
	rotation(2, 0) = -(forward.x);
	rotation(2, 1) = -(forward.y);
	rotation(2, 2) = -(forward.z);

	translation(0, 3) = -(camera.x);
	translation(1, 3) = -(camera.y);
	translation(2, 3) = -(camera.z);

	modelView = rotation * translation;

	return modelView;
}
Example #3
0
void  CoordinateFrame::lookAt(
    const Vector3&  target,
    Vector3         up) {

    up = up.direction();

    Vector3 look = (target - translation).direction();
    if (look.dotProduct(up) > .99) {
        up = Vector3::UNIT_X;
        if (look.dotProduct(up) > .99) {
            up = Vector3::UNIT_Y;
        }
    }

    up -= look * look.dotProduct(up);
    up.normalize();

    Vector3 z = -look;
    Vector3 x = -z.crossProduct(up);
    x.normalize();

    Vector3 y = z.crossProduct(x);

    rotation.SetColumn(0, x);
    rotation.SetColumn(1, y);
    rotation.SetColumn(2, z);
}
Example #4
0
    //-----------------------------------------------------------------------------
    const Matrix4& AutoParamDataSource::getSpotlightViewProjMatrix(size_t index) const
    {
        if (index < OGRE_MAX_SIMULTANEOUS_LIGHTS)
        {
            const Light& l = getLight(index);

            if (&l != &mBlankLight && 
                l.getType() == Light::LT_SPOTLIGHT &&
                mSpotlightViewProjMatrixDirty[index])
            {
                Frustum frust;
                SceneNode dummyNode(0);
                dummyNode.attachObject(&frust);

                frust.setProjectionType(PT_PERSPECTIVE);
                frust.setFOVy(l.getSpotlightOuterAngle());
                frust.setAspectRatio(1.0f);
                // set near clip the same as main camera, since they are likely
                // to both reflect the nature of the scene
                frust.setNearClipDistance(mCurrentCamera->getNearClipDistance());
                // Calculate position, which same as spotlight position, in camera-relative coords if required
                dummyNode.setPosition(l.getDerivedPosition(true));
                // Calculate direction, which same as spotlight direction
                Vector3 dir = - l.getDerivedDirection(); // backwards since point down -z
                dir.normalise();
                Vector3 up = Vector3::UNIT_Y;
                // Check it's not coincident with dir
                if (Math::Abs(up.dotProduct(dir)) >= 1.0f)
                {
                    // Use camera up
                    up = Vector3::UNIT_Z;
                }
                // cross twice to rederive, only direction is unaltered
                Vector3 left = dir.crossProduct(up);
                left.normalise();
                up = dir.crossProduct(left);
                up.normalise();
                // Derive quaternion from axes
                Quaternion q;
                q.FromAxes(left, up, dir);
                dummyNode.setOrientation(q);

                // The view matrix here already includes camera-relative changes if necessary
                // since they are built into the frustum position
                mSpotlightViewProjMatrix[index] = 
                    PROJECTIONCLIPSPACE2DTOIMAGESPACE_PERSPECTIVE * 
                    frust.getProjectionMatrixWithRSDepth() * 
                    frust.getViewMatrix();

                mSpotlightViewProjMatrixDirty[index] = false;
            }
            return mSpotlightViewProjMatrix[index];
        }
        else
            return Matrix4::IDENTITY;
    }
Example #5
0
Vector3 Vector3::getNormal5(const Vector3 &posx, const Vector3 &negx, const Vector3 &posy, const Vector3 &negy) const {
    Vector3 dnegx = negx.sub(*this);
    Vector3 dposy = posy.sub(*this);
    Vector3 dposx = posx.sub(*this);
    Vector3 dnegy = negy.sub(*this);

    Vector3 normal = dposy.crossProduct(dnegx);
    normal = normal.add(dposx.crossProduct(dposy));
    normal = normal.add(dnegy.crossProduct(dposx));
    normal = normal.add(dnegx.crossProduct(dnegy));

    return normal.normalize();
}
Example #6
0
void Mesh::calculateNormals(bool generateFaceNormals) {
    
    int polySize = 3;
    if(meshType == Mesh::QUAD_MESH) {
        polySize = 4;
    }
    
    faceNormals.clear();
    for(int i=0; i < vertices.size(); i++) {
        vertices[i]->normal = Vector3();
    }

    if(indexedMesh) {
        for(int i=0; i+polySize-1 < indices.size(); i += polySize) {
            const Vector3 e1 = *(vertices[indices[i]]) - *(vertices[indices[i+1]]);
            const Vector3 e2 = *(vertices[indices[i+2]]) - *(vertices[indices[i+1]]);
            const Vector3 no = e1.crossProduct(e2);
            
            for(int j=0; j < polySize; j++) {
                vertices[indices[i+j]]->normal -= no;
            }
            
            if(generateFaceNormals) {
                faceNormals.push_back(no * -1.0);
            }
        }
    } else {
        for(int i=0; i+polySize-1 < vertices.size(); i += polySize) {
            const Vector3 e1 = *(vertices[i]) - *(vertices[i+1]);
            const Vector3 e2 = *(vertices[i+2]) - *(vertices[i+1]);
            const Vector3 no = e1.crossProduct(e2);
            
            for(int j=0; j < polySize; j++) {
                vertices[i+j]->normal = no * -1.0;
            }
            
            if(generateFaceNormals) {
                faceNormals.push_back(no * -1.0);
            }
        }
    }
    
    for(int i=0; i < vertices.size(); i++) {
        vertices[i]->normal.Normalize();
    }
    for(int i=0; i < faceNormals.size(); i++) {
        faceNormals[i].Normalize();
    }
    
    arrayDirtyMap[RenderDataArray::NORMAL_DATA_ARRAY] = true;		
}
	//-----------------------------------------------------------------------
	Matrix4 FocusedShadowCameraSetup::buildViewMatrix(const Vector3& pos, const Vector3& dir, 
		const Vector3& up) const
	{
		Vector3 xN = dir.crossProduct(up);
		xN.normalise();
		Vector3 upN = xN.crossProduct(dir);
		upN.normalise();

		Matrix4 m(xN.x,		xN.y,		xN.z,		-xN.dotProduct(pos),
			upN.x,		upN.y,		upN.z,		-upN.dotProduct(pos),
			-dir.x,		-dir.y,	-dir.z,	dir.dotProduct(pos),
			0.0,			0.0,		0.0,		1.0
			);

		return m;
	}
Example #8
0
/***Matrix for View***/
Matrix4 View(){
    Vector3 u;
    Vector3 v;
    
    Vector3 temp(0,1,0);
    
    
    w=lookUpPoint-c;
    w.normalize();
    
    u=temp.crossProduct(w);
    u.normalize();
    
    v=w.crossProduct(u);
    v.normalize();
    
    Matrix4 rotation;
    rotation.identity();
    
    
    rotation.setColumn(0, u);
    rotation.setColumn(1, v);
    rotation.setColumn(2, w);
    
    
    Matrix4 translation;
    
    
    translation.setRow(3,c1);
    
    Matrix4 view;
    view=rotation*translation;
    
    return view;
}
Example #9
0
	void Camera::move(const int direction){
		if(direction==MOVE_FORWARD || direction==MOVE_BACKWARD){
			Vector3 dir = lookAt - pos;
			dir.normalize();
			if(direction==MOVE_FORWARD){
				pos    += movementIntensity*dir;
				lookAt += movementIntensity*dir;
			}else{//MOVE_BACKWARD
				pos    -= movementIntensity*dir;
				lookAt -= movementIntensity*dir;
			}
		}else if(direction==MOVE_RIGHT || direction==MOVE_LEFT){
			Vector3 viewDir = lookAt - pos;
			viewDir.normalize();
			Vector3 right   = viewDir.crossProduct(up);
			right.normalize();
			if(direction==MOVE_RIGHT){
				pos    += movementIntensity*right;
				lookAt += movementIntensity*right;
			}else{//MOVE_LEFT
				pos    -= movementIntensity*right;
				lookAt -= movementIntensity*right;
			}
		}else if(direction==MOVE_UP || direction==MOVE_DOWN){
			up.normalize();
			if(direction==MOVE_UP){
				pos    += movementIntensity*up;
				lookAt += movementIntensity*up;
			}else{//MOVE_DOWN
				pos    -= movementIntensity*up;
				lookAt -= movementIntensity*up;
			}
		}
	}
/** 2009-01-12 另有用途 */
void mesh::CalculateFn()
{
	assert( vTotal > 0 );
	assert( fTotal > 0 );

	if( fnList != 0 ){
		delete[] fnList;
	}
	if( vAdjFList != 0 ){
		delete[] vAdjFList;
	}
	//if( triCList != 0 ){
	//	delete[] triCList;
	//}
	
	//triCList = new Vector3[ fTotal ];
	fnList = new Vector3[ fTotal ];
	assert( fnList );
	//assert( triCList );
	for( int f = 0; f < fTotal; f++ ){
		
		Vector3 a = vList[ faceList[f][1].v ] - vList[ faceList[f][0].v ];
		Vector3 b = vList[ faceList[f][2].v ] - vList[ faceList[f][0].v ];
		// 注意外積的方向要和平面相同
		Vector3 n = a.crossProduct(  b);
		n.normalise();
		fnList[f] = n;

		//triCList[f] = (vList[ faceList[f][0].v ] + vList[ faceList[f][0].v ] + vList[ faceList[f][0].v ] )/3;
	}
}//close function: calculateFn
Example #11
0
void EntityController_Rotator::onMouseMove(float x, float y)
{
    if (m_pickedEntity != NULL) {
        Vector3 startVec = screenPoint2SpherePoint(m_oldX, m_oldY);
        Vector3 endVec = screenPoint2SpherePoint(x, y);
        assert(startVec.isUnit());
        assert(endVec.isUnit());
        Vector3 axis = startVec.crossProduct(endVec);
        float angle = radian2Degree(asin(axis.length()));
        axis = axis.normalize();

        const Camera *camera = m_sceneMgr->getCamera();
        Matrix4x4 viewMat = camera->getViewMatrix();
        Matrix4x4 mat = m_oldEntWorldMat * viewMat;
        Vector4 trans(mat[3]);
        mat *= 
            Matrix4x4::fromTranslate(-trans.x, -trans.y, -trans.z) *
            Matrix4x4::fromRotateAxis(axis, angle) *
            Matrix4x4::fromTranslate(trans.x, trans.y, trans.z) * 
            camera->getSceneNode()->getWorldMatrix();
        m_pickedEntity->getSceneNode()->setWorldMatrix(mat);

        m_sceneMgr->notifyCameraSpaceChanged();
    }
}
Example #12
0
const MATRIX4X4 & Camera::getViewMat()
{
    Vector3 n = m_target - m_pos;
    n.normalize();
    Vector3 up( 0.0f , 1.0f , 0.0f );
    Vector3 u = up.crossProduct( n );
    Vector3 v = n.crossProduct( u );
    
    u.normalize();
    v.normalize();
    n.normalize();

    MatrixTool::initMatrix4X4( &m_viewMat );
    m_viewMat.a_00 = u.x;
    m_viewMat.a_01 = v.x;
    m_viewMat.a_02 = n.x;
    
    m_viewMat.a_10 = u.y;
    m_viewMat.a_11 = v.y;
    m_viewMat.a_12 = n.y;

    m_viewMat.a_20 = u.z;
    m_viewMat.a_21 = v.z;
    m_viewMat.a_22 = n.z;
    
    //切忌不可直接将pos直接设置在该矩阵的这个部分,因为是先平移后旋转,如果直接设置
    //则变成了先旋转后平移了。
    //需要将平移矩阵与旋转矩阵相乘,但为了提高效率,则手动更新矩阵,不使用矩阵相乘
    m_viewMat.a_30 = -m_pos.x * m_viewMat.a_00 -m_pos.y * m_viewMat.a_10 - m_pos.z * m_viewMat.a_20;
    m_viewMat.a_31 = -m_pos.x * m_viewMat.a_01 -m_pos.y * m_viewMat.a_11 - m_pos.z * m_viewMat.a_21;
    m_viewMat.a_32 = -m_pos.x * m_viewMat.a_02 -m_pos.y * m_viewMat.a_12 - m_pos.z * m_viewMat.a_22;


	return m_viewMat;
}
Example #13
0
static Vector3 _getDetailNormal(Vector3 base_location, Vector3 base_normal, TextureLayerDefinition *layer,
                                double precision, bool normal5) {
    Vector3 result;

    /* Find guiding vectors in the appoximated local plane */
    Vector3 dx, dy;
    Vector3 pivot;
    if (base_normal.y > 0.95) {
        pivot = VECTOR_NORTH;
    } else {
        pivot = VECTOR_UP;
    }
    dx = base_normal.crossProduct(pivot).normalize();
    dy = base_normal.crossProduct(dx).normalize();

    /* Apply detail noise locally */
    Vector3 center, north, east, south, west;
    auto detail_noise = layer->propDetailNoise()->getGenerator();
    double detail = precision;
    double offset = precision * 0.1;

    center = base_location.add(base_normal.scale(detail_noise->getTriplanar(detail, base_location, base_normal)));

    east = base_location.add(dx.scale(offset));
    east = east.add(base_normal.scale(detail_noise->getTriplanar(detail, east, base_normal)));

    south = base_location.add(dy.scale(offset));
    south = south.add(base_normal.scale(detail_noise->getTriplanar(detail, south, base_normal)));

    if (normal5) {
        west = base_location.add(dx.scale(-offset));
        west = west.add(base_normal.scale(detail_noise->getTriplanar(detail, west, base_normal)));

        north = base_location.add(dy.scale(-offset));
        north = north.add(base_normal.scale(detail_noise->getTriplanar(detail, north, base_normal)));

        result = center.getNormal5(south, north, east, west);
    } else {
        result = center.getNormal3(south, east);
    }

    if (result.dotProduct(base_normal) < 0.0) {
        result = result.scale(-1.0);
    }
    return result;
}
Example #14
0
bool FlexMeshWheel::flexitPrepare(Beam* b)
{
	Vector3 center = (nodes[id0].smoothpos + nodes[id1].smoothpos) / 2.0;
	rnode->setPosition(center);

	Vector3 axis = nodes[id0].smoothpos - nodes[id1].smoothpos;
	axis.normalise();

	if (revrim) axis = -axis;
	Vector3 ray = nodes[idstart].smoothpos - nodes[id0].smoothpos;
	Vector3 onormal = axis.crossProduct(ray);
	onormal.normalise();
	ray = axis.crossProduct(onormal);
	rnode->setOrientation(Quaternion(axis, onormal, ray));

	return Flexable::flexitPrepare(b);
}
Example #15
0
///  Pick marker
//---------------------------------------------------------------------------------------------------------------
void SplineRoad::Pick(Camera* mCamera, Real mx, Real my,  bool bRay, bool bAddH, bool bHide)
{
	iSelPoint = -1;
	//if (vMarkNodes.size() != getNumPoints())
	//	return;  // assert
	
	Ray ray = mCamera->getCameraToViewportRay(mx,my);  // 0..1
	const Vector3& pos = mCamera->getDerivedPosition(), dir = ray.getDirection();
	const Plane& pl = mCamera->getFrustumPlane(FRUSTUM_PLANE_NEAR);
	Real plDist = FLT_MAX;
	const Real sphR = 2.4f;  //par

	for (int i=0; i < (int)getNumPoints(); ++i)
	{
		// ray to sphere dist
		const Vector3& posSph = getPos(i);
		const Vector3 ps = pos - posSph;
		Vector3 crs = ps.crossProduct(dir);
		Real dist = crs.length() / dir.length();
		// dist to camera
		Real plD = pl.getDistance(posSph);

		if (dist < sphR &&
			plD > 0 && plD < plDist)
		{
			plDist = plD;
			iSelPoint = i;
		}
	}
	
	SelectMarker(bHide);
	//  hide/show all markers
	int iHide = bHide ? 1 : 0;
	if (iHide != iOldHide)
	{	iOldHide = iHide;
		for (size_t i=0; i < vMarkNodes.size(); ++i)
			vMarkNodes[i]->setVisible(bAddH);
	}
	
	//  ray terrain hit pos
	if (bRay && ndHit && mTerrain)
	{
		std::pair<bool, Vector3> p = mTerrain->rayIntersects(ray);
		bHitTer = p.first;  //ndHit->setVisible(bHitTer);
		posHit = p.second;
		
		if (bHitTer)
		{
			Vector3 pos = posHit;
			//if (iChosen == -1)  // for new
			if (!newP.onTer && bAddH)
				pos.y = newP.pos.y;
			ndHit->setPosition(pos);
		}
	}
}
Example #16
0
    void Camera::computeModelViewMatrix()
    {
        myModelViewMatrix = Matrix4::IDENTITY;

        Vector3 foward = (myFocalPoint - myPosition).normalise();
        Vector3 side = foward.crossProduct(myUpVector);
        side = side.normalise();

        Vector3 up = side.crossProduct(foward);


        myModelViewMatrix(0, 0) =   side.x;  myModelViewMatrix(0, 1) =   side.y;  myModelViewMatrix(0, 2) =   side.z;  myModelViewMatrix(0, 3) = side.dotProduct(myPosition);
        myModelViewMatrix(1, 0) =     up.x;  myModelViewMatrix(1, 1) =     up.y;  myModelViewMatrix(1, 2) =     up.z;  myModelViewMatrix(1, 3) = up.dotProduct(myPosition);
        myModelViewMatrix(2, 0) = -foward.x;  myModelViewMatrix(2, 1) = -foward.y;  myModelViewMatrix(2, 2) = -foward.z;  myModelViewMatrix(2, 3) = foward.dotProduct(myPosition);

        myModelViewMatrix.print("modelview");

        myNeedUpdate = false;
    }
	//---------------------------------------------------------------------
	int TangentSpaceCalc::calculateParity(const Vector3& u, const Vector3& v, const Vector3& n)
	{
		// Note that this parity is the reverse of what you'd expect - this is
		// because the 'V' texture coordinate is actually left handed
		if (u.crossProduct(v).dotProduct(n) >= 0.0f)
			return -1;
		else
			return 1;

	}
Example #18
0
/** 左右移动摄像机 */
void Camera::yawCamera(float speed)
{
	Vector3 cross = m_View - m_Position;
	cross = cross.crossProduct(m_UpVector);
	Vector3 oldPos,oldView;
	oldPos = m_Position;
	oldView = m_View;

	// Add the strafe vector to our view
	rotateView1(speed, 0, 1, 0);
}
Example #19
0
Matrix4 Entity::getLookAtMatrix(const Vector3 &loc, const Vector3 &upVector) {
    rebuildTransformMatrix();
    Vector3 D;

    D = loc - position;

    Vector3 back = D * -1;
    back.Normalize();

    Vector3 right = back.crossProduct(upVector) ;
    right.Normalize();
    right = right * -1;

    Vector3 up = back.crossProduct(right);

    Matrix4 newMatrix(right.x, right.y, right.z, 0,
                      up.x, up.y, up.z, 0,
                      back.x, back.y, back.z, 0,
                      0, 0 , 0, 1);
    return newMatrix;
}
Example #20
0
//angle is in radian
void computeAngleAndAxis(Vector3 * rotation, float * angle)
{
    if (cur_mx != last_mx || cur_my != last_my)
    {
        Vector3 va = get_arcball_vector(last_mx, last_my);
        Vector3 vb = get_arcball_vector( cur_mx,  cur_my);
        *angle = acos(va.dotProduct(vb))*180.0/PI;
        *rotation = va.crossProduct(vb);

    }

}
Example #21
0
Camera::Camera(Vector3 e1, Vector3 d1, Vector3 up1)
{
	e = e1;
	d = d1;
	up = up1;

	Vector3 zc = e - d;
	zc.normalize();

	Vector3 xc = up;
	xc.crossProduct(zc);
	xc.normalize();

	Vector3 yc = zc;
	yc.crossProduct(xc);

	c = Matrix4(xc[0],yc[0],zc[0],e[0],
				xc[1],yc[1],zc[1],e[1],
				xc[2],yc[2],zc[2],e[2],
				0,0,0,1);
}
    //-----------------------------------------------------------------------
	void MeshParticleVisualData::setDirection( const Vector3 &dir, const Quaternion& parentOrientation )
	{
		Vector3 yAdjustVec = dir;
        yAdjustVec.normalise();
        
        Vector3 xVec = mSceneNode->getOrientation().zAxis().crossProduct( yAdjustVec );
        xVec.normalise();

        Vector3 zVec = xVec.crossProduct( yAdjustVec );
        zVec.normalise();   

		mOrientation = parentOrientation * Quaternion( xVec, yAdjustVec, zVec );
	}
void CameraBehaviorVehicleCineCam::update(const CameraManager::CameraContext &ctx)
{
	CameraBehaviorOrbit::update(ctx);

	Vector3 dir = (ctx.mCurrTruck->nodes[ctx.mCurrTruck->cameranodepos[ctx.mCurrTruck->currentcamera]].smoothpos
				 - ctx.mCurrTruck->nodes[ctx.mCurrTruck->cameranodedir[ctx.mCurrTruck->currentcamera]].smoothpos).normalisedCopy();

	Vector3 roll = (ctx.mCurrTruck->nodes[ctx.mCurrTruck->cameranodepos[ctx.mCurrTruck->currentcamera]].smoothpos
				  - ctx.mCurrTruck->nodes[ctx.mCurrTruck->cameranoderoll[ctx.mCurrTruck->currentcamera]].smoothpos).normalisedCopy();

	if ( ctx.mCurrTruck->revroll[ctx.mCurrTruck->currentcamera] )
	{
		roll = -roll;
	}

	Vector3 up = dir.crossProduct(roll);

	roll = up.crossProduct(dir);

	Quaternion orientation = Quaternion(camRotX + camRotXSwivel, up) * Quaternion(Degree(180.0) + camRotY + camRotYSwivel, roll) * Quaternion(roll, up, dir);

	gEnv->mainCamera->setPosition(ctx.mCurrTruck->nodes[ctx.mCurrTruck->cinecameranodepos[ctx.mCurrTruck->currentcamera]].smoothpos);
	gEnv->mainCamera->setOrientation(orientation);
}
bool Renderer::rayTriangleIntersect(Vector3 ray_origin, Vector3 ray_direction, Vector3 vert0, Vector3 vert1, Vector3 vert2, Vector3 *hitPoint)
{

//	printf("TESTING RAY\nORIGIN: %f,%f,%f\nDIR: %f,%f,%f\nVERT0: %f,%f,%f\nnVERT1: %f,%f,%f\nnVERT2: %f,%f,%f\n", ray_origin.x, ray_origin.y, ray_origin.z, ray_direction.x, ray_direction.y, ray_direction.z, vert0.x, vert0.y, vert0.z, vert1.x, vert1.y, vert1.z, vert2.x, vert2.y, vert2.z);	


	Number t,u,v;
	t = 0; u = 0; v = 0;
	
	Vector3 edge1 = vert1 - vert0;
	Vector3 edge2 = vert2 - vert0;
	
	Vector3 tvec, pvec, qvec;
	Number det, inv_det;
	
	
	pvec = ray_direction.crossProduct(edge2);
	det = edge1.dot(pvec);
	
	if (det > -0.00001f)
		return false;
	
	inv_det = 1.0f / det;
	
	tvec = ray_origin - vert0;
	
	u = tvec.dot(pvec) * inv_det;
	if (u < -0.001f || u > 1.001f)
		return false;
	
	qvec = tvec.crossProduct(edge1);
	
	v = ray_direction.dot(qvec) * inv_det;
	if (v < -0.001f || u + v > 1.001f)
		return false;
	
	t = edge2.dot(qvec) * inv_det;
	
	if (t <= 0)
		return false;
	
	hitPoint->x = ray_origin.x+t*ray_direction.x;
	hitPoint->y = ray_origin.y+t*ray_direction.y;
	hitPoint->z = ray_origin.z+t*ray_direction.z;	
	
	return true;	
}
Example #25
0
/** 左右移动摄像机 */
void Camera::yawCamera(float speed)
{
	Vector3 yaw;
	Vector3 cross = m_View - m_Position;
	cross = cross.crossProduct(m_UpVector);

	///归一化向量
	yaw = cross.normalize();
 
	m_Position.x += yaw.x * speed;
	m_Position.z += yaw.z * speed;

	m_View.x += yaw.x * speed;
	m_View.z += yaw.z * speed;


}
	//-----------------------------------------------------------------------
	void BeamRenderer::_processParticle(ParticleTechnique* particleTechnique, 
		Particle* particle, 
		Real timeElapsed, 
		bool firstParticle)
	{
		if (!particle->visualData)
			return;

		BeamRendererVisualData* beamRendererVisualData = static_cast<BeamRendererVisualData*>(particle->visualData);
		beamRendererVisualData->mTimeSinceLastUpdate -= timeElapsed;

		if (beamRendererVisualData->mTimeSinceLastUpdate < 0)
		{
			// Generate deviation
			ParticleSystem* pSys = particleTechnique->getParentSystem();
			if (!pSys)
				return;

			Vector3 end = particle->position - pSys->getDerivedPosition();
			Vector3 perpendicular;
			Real divide = (Real)mNumberOfSegments + 1.0f;
			for (size_t numDev = 0; numDev < mNumberOfSegments; ++numDev)
			{
				perpendicular = end.crossProduct(Vector3(Math::RangeRandom(-1, 1), 
					Math::RangeRandom(-1, 1), 
					Math::RangeRandom(-1, 1)));
				perpendicular.normalise();
				beamRendererVisualData->destinationHalf[numDev] = (((Real)numDev + 1.0f) / divide) * end + _mRendererScale * mDeviation * perpendicular;
			}
			beamRendererVisualData->mTimeSinceLastUpdate += mUpdateInterval;
		}

		Vector3 diff;
		for (size_t numDev = 0; numDev < mNumberOfSegments; ++numDev)
		{
			if (mJump)
			{
				beamRendererVisualData->half[numDev] = beamRendererVisualData->destinationHalf[numDev];
			}
			else
			{
				diff = beamRendererVisualData->destinationHalf[numDev] - beamRendererVisualData->half[numDev];
				beamRendererVisualData->half[numDev] = beamRendererVisualData->half[numDev] + timeElapsed * diff;
			}
		}
	}
Example #27
0
bool Math::intersected(const Ray& ray, const Sphere& sphere)
{
   Vector3 t = ray.getOrien();
   Vector3 origin = ray.getOrigin();
   Vector3 center = sphere.getCenter();
   Vector3 s = center - origin;
   Real d = (s.crossProduct(t)).length();

   if(d <= sphere.getRadius())
   {
      return true;
   }
   else
   {
      return false;

   }
}
Example #28
0
    template<class T> Quaternion<T>::Quaternion(const Vector3<T> &normalizedLookAt, const Vector3<T> &normalizedUp)
    {
		#ifdef _DEBUG
			assert(MathAlgorithm::isOne(normalizedLookAt.length(), 0.001));
			assert(MathAlgorithm::isOne(normalizedUp.length(), 0.001));
        #endif

        Vector3<T> right = normalizedUp.crossProduct(normalizedLookAt);
        T det = right.X + normalizedUp.Y + normalizedLookAt.Z;

        if(det > 0.0)
		{
        	T sqrtValue = sqrtf(1.0 + det);
			T halfOverSqrt = 0.5 / sqrtValue;
			X = (normalizedUp.Z - normalizedLookAt.Y) * halfOverSqrt;
			Y = (normalizedLookAt.X - right.Z) * halfOverSqrt;
			Z = (right.Y - normalizedUp.X) * halfOverSqrt;
            W = sqrtValue * 0.5;
		}else if ((right.X >= normalizedUp.Y) && (right.X >= normalizedLookAt.Z))
        {
            T sqrtValue = sqrtf(((1.0 + right.X) - normalizedUp.Y) - normalizedLookAt.Z);
            T halfOverSqrt = 0.5 / sqrtValue;
            X = 0.5 * sqrtValue;
            Y = (right.Y + normalizedUp.X) * halfOverSqrt;
            Z = (right.Z + normalizedLookAt.X) * halfOverSqrt;
            W = (normalizedUp.Z - normalizedLookAt.Y) * halfOverSqrt;
        }else if (normalizedUp.Y > normalizedLookAt.Z)
        {
            T sqrtValue = sqrtf(((1.0 + normalizedUp.Y) - right.X) - normalizedLookAt.Z);
            T halfOverSqrt = 0.5 / sqrtValue;
            X = (normalizedUp.X+ right.Y) * halfOverSqrt;
            Y = 0.5 * sqrtValue;
            Z = (normalizedLookAt.Y + normalizedUp.Z) * halfOverSqrt;
            W = (normalizedLookAt.X - right.Z) * halfOverSqrt;
        }else
        {
            T sqrtValue = sqrtf(((1.0 + normalizedLookAt.Z) - right.X) - normalizedUp.Y);
            T halfOverSqrt = 0.5 / sqrtValue;
            X = (normalizedLookAt.X + right.Z) * halfOverSqrt;
            Y = (normalizedLookAt.Y + normalizedUp.Z) * halfOverSqrt;
            Z = 0.5 * sqrtValue;
            W = (right.Y - normalizedUp.X) * halfOverSqrt;
        }
    }
Example #29
0
bool Renderer::rayTriangleIntersect(Vector3 ray_origin, Vector3 ray_direction, Vector3 vert0, Vector3 vert1, Vector3 vert2, Vector3 *hitPoint)
{
	Number t,u,v;
	t = 0; u = 0; v = 0;
	
	Vector3 edge1 = vert1 - vert0;
	Vector3 edge2 = vert2 - vert0;
	
	Vector3 tvec, pvec, qvec;
	Number det, inv_det;
	
	
	pvec = ray_direction.crossProduct(edge2);
	det = edge1.dot(pvec);
	
	if (det > -0.00001f)
		return false;
	
	inv_det = 1.0f / det;
	
	tvec = ray_origin - vert0;
	
	u = tvec.dot(pvec) * inv_det;
	if (u < -0.001f || u > 1.001f)
		return false;
	
	qvec = tvec.crossProduct(edge1);
	
	v = ray_direction.dot(qvec) * inv_det;
	if (v < -0.001f || u + v > 1.001f)
		return false;
	
	t = edge2.dot(qvec) * inv_det;
	
	if (t <= 0)
		return false;
	
	hitPoint->x = ray_origin.x+t*ray_direction.x;
	hitPoint->y = ray_origin.y+t*ray_direction.y;
	hitPoint->z = ray_origin.z+t*ray_direction.z;	
	
	return true;	
}
Example #30
0
void TestSceneManager3::populate() {
    // Build the vertex array using the lowest toplevel voxel per corner. Note, we're
    // leaving in vertex duplication so each voxel can have its own normals and tex-coords.
    // This will increase our sene complexity, but give us more control, as well.
    std::vector<Vector3> vertsArray;
    std::vector<Vector2> coordsArray;
    for (int x = 0; x < _world->getWidth(); x++) {
        for (int y = 0; y < _world->getHeight(); y++) {
            #define ADD_VECTOR(xOff, yOff) do { \
                vertsArray.push_back(getVectorForCorner(x + xOff, y + yOff)); \
                coordsArray.push_back(Vector2(xOff, yOff)); \
            } while (0)

            // Bottom left triangle.
            ADD_VECTOR(0, 0); ADD_VECTOR(1, 0); ADD_VECTOR(0, 1);

            // Top right triangle.
            ADD_VECTOR(0, 1); ADD_VECTOR(1, 0); ADD_VECTOR(1, 1);
            #undef ADD_VECTOR
        }    
    }

    // Calculate normals for each of the vertices.
    Vector3 *verts = new Vector3[vertsArray.size()];
    Vector3 *norms = new Vector3[vertsArray.size()];
    for (int i = 0; i < vertsArray.size(); i+=3) {
		Vector3 one = vertsArray[i+1] - vertsArray[i+0];
		Vector3 two = vertsArray[i+2] - vertsArray[i+1];
		Vector3 normal = one.crossProduct(two);
        normal.normalize();

        for (int j = 0; j < 3; j++) {
            verts[i+j] = vertsArray[i+j];
            norms[i+j] = normal;
        }
    }

    Entity *entity = createEntity(new WorldEntity(verts, norms, vector_to_array(coordsArray), vertsArray.size()), "world");
    entity->setMaterial(_materialManager->getOrLoadResource("grass"));
    getRootNode()->attach(entity);
}