Exemple #1
0
void zad1() {
    IVector *v1 = (Vector::parseSimple("2 3 -4"))->add(Vector::parseSimple("-1 4 -3"));
    printf("v1 = %s\n", v1->toString().c_str());
    
    IVector *s = v1->nAdd(Vector::parseSimple("-1 4 -3"));
    printf("s = %s\n", s->toString().c_str());
    
    IVector *v2 = v1->nVectorProduct(Vector::parseSimple("2 2 4"));
    printf("v2 = %s\n", v2->toString().c_str());
    
    IVector *v3 = v2->normalize();
    printf("v3 = %s\n", v3->toString().c_str());
    
    IVector *v4 = v2->scalarMultiply(-1);
    printf("v4 = %s\n", v4->toString().c_str());
    
    IMatrix *m1 = (Matrix::parseSimple("1 2 3 | 2 1 3 | 4 5 1"))
    ->add(Matrix::parseSimple("-1 2 -3 | 5 -2 7 | -4 -1 3"));
    printf("m1 = %s\n", m1->toString().c_str());
    
    IMatrix *m2 = (Matrix::parseSimple("1 2 3 | 2 1 3 | 4 5 1"))
    ->nMultiply(Matrix::parseSimple("-1 2 -3 | 5 -2 7 | -4 -1 3")->nTranspose(false));
    printf("m2 = %s\n", m2->toString().c_str());
    
    IMatrix *m3 = (Matrix::parseSimple("-24 18 5 | 20 -15 -4 | -5 4 1")->nInvert())
    ->nMultiply(Matrix::parseSimple("1 2 3 | 0 1 4 | 5 6 0")->nInvert());
    printf("m3 = %s\n", m3->toString().c_str());
}
int ReferenceFrame2D::GetNode(Vector2D p_loc) const
{
	double tol = 1e-8*GetMBS()->CharacteristicLength();
/*
	for (int i = 1; i <=nodes.Length(); i++)
	{
		if (Dist(p_loc,nodes(i)->Pos2D()) <= tol) return i;
	}
	GetMBS()->UO() << "ERROR: node not found:" << p_loc << " !!!\n";
	return 0;
*/

	IVector items;
	Vector3D p(p_loc.X(),p_loc.Y(),0.);

	Box3D box(p, p);
	box.Increase(tol);
	searchtree.GetItemsInBox(box,items);
	for (int i = 1; i <= items.Length(); i++)
	{
		Vector3D p2(nodes(items(i))->Pos().X(), nodes(items(i))->Pos().Y(), 0.);
		if (Dist(p,p2) <= tol) return items(i);
	}
	GetMBS()->UO() << "ERROR: node not found:" << p_loc << " !!!\n";
	return 0;
}
//The function recursively builds up the transformation of the pThing 
//until it's in room-space coordinates
HRESULT C2DThingCoordTransformer::BuildTransformation(IThing * pThing, IThing * pParentThing)
{
	IVector * pVector = NULL;
	HRESULT hr = S_OK;
	IThing* pTmpParentThing = NULL;
	D3DRMMATRIX4D tmpMatrix;
	float flScaleX, flScaleY, flScaleZ;
	float flThingX, flThingY, flThingZ, // Position of current Thing having cells edited
	      flThingDirX, flThingDirY, flThingDirZ; // Orientation of current Thing having cells edited

	if (!pThing || !pParentThing)
		goto EXIT_FAIL;

	// Store the position Vector of the Thing
	hr = pThing->get_ObjectProperty(bstrPosition, (IObjectProperty **) &pVector);
	if( FAILED(hr) || !pVector) goto EXIT_FAIL;
	hr = pVector->get(&flThingX, &flThingY, &flThingZ);
	if( FAILED(hr) ) goto EXIT_FAIL;
	SAFERELEASE(pVector);

	// Get the Scale Vector of the Thing
	hr = pThing->get_ObjectProperty(bstrScale, (IObjectProperty **) &pVector);
	if( FAILED(hr) || !pVector) goto EXIT_FAIL;
	hr = pVector->get(&flScaleX, &flScaleY, &flScaleZ);
	if( FAILED(hr) ) goto EXIT_FAIL;
	SAFERELEASE(pVector);

	// Store the Direction Vector of the Thing
	hr = pThing->get_ObjectProperty(bstrDirection, (IObjectProperty **) &pVector);
	if( FAILED(hr) ) goto EXIT_FAIL;
	hr = pVector->get(&flThingDirX, &flThingDirY, &flThingDirZ);
	if( FAILED(hr) ) goto EXIT_FAIL;
	SAFERELEASE(pVector);

	IdentityMatrix(&tmpMatrix);
	ScaleMatrix(&tmpMatrix, flScaleX, flScaleY, flScaleZ);
	RotateMatrix(&tmpMatrix, flThingDirX, flThingDirY, flThingDirZ);
	TranslateMatrix(&tmpMatrix, flThingX, flThingY, flThingZ);
	PostMultiplyMatrix(&m_d3dMatrix, &tmpMatrix);

	IdentityMatrix(&tmpMatrix);
	TranslateMatrix(&tmpMatrix, -flThingX, -flThingY, -flThingZ);
	InverseRotateMatrix(&tmpMatrix, flThingDirX, flThingDirY, flThingDirZ);
	ScaleMatrix(&tmpMatrix, 1.0f / flScaleX, 1.0f / flScaleY, 1.0f / flScaleZ);
	PostMultiplyMatrix(&m_d3dInverseMatrix, &tmpMatrix);

	hr = pParentThing->get_Container(&pTmpParentThing);
	if ( SUCCEEDED(hr) && pTmpParentThing)
	{
		BuildTransformation(pParentThing, pTmpParentThing);
	}


EXIT_FAIL:
	SAFERELEASE(pTmpParentThing);
	SAFERELEASE(pVector);
	return hr;
}
void verifyExistenceOfPeriodicOrbit(IPoincareMap& pm, IVector X, int period)
{
  IVector center = midVector(X);
  interval returnTime;

  // Center is 2-dimensional. Embed it into Poincare section, i.e. add first coordinate x=0.
  // Define a tripleton representation of the center of X.
  C0HOTripletonSet s1({interval(0.),center[0],center[1]});

  // Compute iteration of Poincare map at the center (3-dim object is returned).
  IVector y = pm(s1,returnTime,period);

  // Project it onto 2-dim Poincare section, first coordinate is ignored.
  IVector imCenter(2,y.begin()+1);


  // Derivative of PM on the set X.
  // Define doubleton representation of the first order variational equations.
  C1HORect2Set s2({interval(0.),X[0],X[1]});

  // The matrix monodromyMatrix will store derivatives of the FLOW not Poincare map.
  IMatrix monodromyMatrix(3,3);
  y = pm(s2,monodromyMatrix,returnTime,period);

  // This member function recomputes derivatives of the flow into derivatives of Poincare map
  IMatrix DP = pm.computeDP(y,monodromyMatrix);

  // We extract a 2x2 slice from 3x3 DP matrix and subtract identity.
  IMatrix DP_Minus_Id(2,2);
  DP_Minus_Id[0][0] = DP[1][1] - 1.;
  DP_Minus_Id[0][1] = DP[1][2];
  DP_Minus_Id[1][0] = DP[2][1];
  DP_Minus_Id[1][1] = DP[2][2] - 1.;

  // Compute interval Newton operator.
  IVector N = center - capd::matrixAlgorithms::gauss(DP_Minus_Id,imCenter-center);

  // Verification if N is a subset of X
  cout << "\n---------------------------------------------------\n\nN = " << N << endl;
  cout << "X = " << X << endl;
  cout << "Return time: " << returnTime << endl;
  if(subsetInterior(N,X))
    cout << "the existence of period " << period << " orbit verified\n";
  else
  {
    cout << "N is not a subset of X\n\n";
    cout << "diam(N)=" << diam(N) << endl;
    cout << "diam(X)=" << diam(X) << endl;
    cout << "N-X" << N-X << endl;
  }
}
Exemple #5
0
 void izracunajKoeficijente() {
     for(int i = 0; i < (int)faces.size(); ++i) {
         int i0 = faces[i].indexes[0];
         int i1 = faces[i].indexes[1];
         int i2 = faces[i].indexes[2];
         IVector *v1 = new Vector(new double[3]{vertices[i1].x - vertices[i0].x, vertices[i1].y - vertices[i0].y, vertices[i1].z - vertices[i0].z }, 3);
         IVector *v2 = new Vector(new double[3]{vertices[i2].x - vertices[i0].x, vertices[i2].y - vertices[i0].y, vertices[i2].z - vertices[i0].z }, 3);
         IVector *n = v1->nVectorProduct(v2);
         faces[i].a = n->get(0);
         faces[i].b = n->get(1);
         faces[i].c = n->get(2);
         faces[i].d = -faces[i].a * vertices[i1].x - faces[i].b * vertices[i1].y - faces[i].c * vertices[i1].z;
     }
 }
Exemple #6
0
    static auto prepare_it(IIterator ifirst, IIterator ilast, EIterator efirst, EIterator elast, IVector& ivec, EVector& evec) {
        std::copy(ifirst, ilast, std::back_inserter(ivec));

        auto input_first = ivec.begin();
        auto input_last  = ivec.end();

        if (Denoising) {
            std::copy(efirst, elast, std::back_inserter(evec));

            auto expected_first = evec.begin();
            auto expected_last = evec.end();
            return std::make_tuple(input_first, input_last, expected_first, expected_last);
        } else {
            return std::make_tuple(input_first, input_last, input_first, input_last);
        }
    }
Exemple #7
0
ode_solver::ODE_result ode_solver::simple_ODE_backward(IVector & X_0, IVector const & X_t, interval const & T,
                                                       IVector const & inv, vector<IFunction> & funcs) {
    // X_0 = X_0 \cup (X_t - + (d/dt Inv) * T)
    for (int i = 0; i < X_0.dimension(); i++) {
        interval & x_0 = X_0[i];
        interval const & x_t = X_t[i];
        IFunction & dxdt = funcs[i];
        for (Enode * par : m_pars) {
            double lb = get_lb(par);
            double ub = get_ub(par);
            string name = par->getCar()->getName();
            dxdt.setParameter(name, interval(lb, ub));
        }
        try {
            interval const new_x_0 = x_t - dxdt(inv) * T;
            if (!intersection(new_x_0, x_0, x_0)) {
                DREAL_LOG_INFO << "Simple_ODE: no intersection for X_0";
                return ODE_result::UNSAT;
            }
        } catch (exception& e) {
            DREAL_LOG_INFO << "Exception in Simple_ODE: " << e.what();
        }
    }
    // update
    IVector_to_varlist(X_0, m_0_vars);
    return ODE_result::SAT;
}
Exemple #8
0
void ode_solver::IVector_to_varlist(IVector const & v, vector<Enode*> & vars) {
    for (auto i = 0; i < v.dimension(); i++) {
        double lb = get_lb(vars[i]);
        double ub = get_ub(vars[i]);
        if (lb < v[i].leftBound())
            set_lb(vars[i], v[i].leftBound());
        if (ub > v[i].rightBound())
            set_ub(vars[i], v[i].rightBound());
    }
}
Exemple #9
0
void printSample(const double &t, const IVector &x)
{
	cout.setf(ios::scientific);
  cout.setf(ios::showpos);
  cout.precision(10);
  cout << t << " ";
  for(int i=0; i<x.dimension(); ++i)
    cout << x[i].leftBound() << " " << x[i].rightBound() << " ";
  cout << endl; 
}
Exemple #10
0
// Take an intersection of v and inv.
// If there is no intersection, return false.
bool ode_solver::check_invariant(IVector & v, IVector const & inv) {
    if (!intersection(v, inv, v)) {
        DREAL_LOG_INFO << "invariant violated!";
        for (auto i = 0; i < v.dimension(); i++) {
            if (v[i].leftBound() < inv[i].leftBound() || v[i].rightBound() > inv[i].rightBound()) {
                DREAL_LOG_INFO << "inv[" << i << "] = " << inv[i];
                DREAL_LOG_INFO << "  v[" << i << "] = " <<   v[i];
            }
        }
        return false;
    }
    return true;
}
int ReferenceFrame2D::AddNode(Node* n)
{
	n->SetAuxNode();

	double tol = 1e-8*GetMBS()->CharacteristicLength();

	//standard:
	/*
	for (int i = 1; i <=nodes.Length(); i++)
	{
		if (Dist(n->Pos(),nodes(i)->Pos()) <= tol) return i;
	}
	Node* nc = n->GetCopy();
	return nodes.Add(nc);
	*/

	//optimized:

	IVector items;

	Box3D box(n->Pos(),n->Pos());
	box.Increase(tol); //disabled in example for witteven adams comparison Milano conference 2007

	searchtree.GetItemsInBox(box,items);
	for (int i = 1; i <= items.Length(); i++)
	{
		//if (Dist(n->Pos(),nodes(items(i))->Pos()) <= tol) return items(i);
		if (Dist(n->Pos(),nodes(items(i))->Pos()) <= tol && (n->GetBodyInd() == nodes(items(i))->GetBodyInd()) ) return items(i); //$ AD FENodes have domain
	}
	Node* nc = n->GetCopy();
	int index = nodes.Add(nc);
	nc->NodeNum() = index; //store node number in reference configuration (local == global) for const int& access of virtual function nodenum in referenceframe2D

	searchtree.AddItem(Box3D(n->Pos(),n->Pos()), index);

	return index;
	
}
//Transform a vector from world to thing coords
HRESULT C2DThingCoordTransformer::TransformToThingCoordsNoTranslation(float * pflX, float * pflY, float * pflZ)
{
	HRESULT hr = S_OK;
	D3DVECTOR d3dVDst, d3dVSrc;
	IVector * pVector = NULL;


	if(NULL == pflX || NULL == pflY	|| NULL == pflZ)
	{
		hr = E_POINTER;
		goto EXIT_FAIL;
	}

	if (m_bDoTransform)
	{
		hr = m_pThing->get_ObjectProperty(bstrPosition, (IObjectProperty **) &pVector);
		if( FAILED(hr) ) goto EXIT_FAIL;

		hr = pVector->get(&d3dVSrc.x, &d3dVSrc.y, &d3dVSrc.z);
		if( FAILED(hr) ) goto EXIT_FAIL;

		d3dVSrc.x = *pflX + d3dVSrc.x;
		d3dVSrc.y = *pflY + d3dVSrc.y;
		d3dVSrc.z = *pflZ + d3dVSrc.z;

		InverseTransform(&d3dVDst, &d3dVSrc);

		*pflX = d3dVDst.x;
		*pflY = d3dVDst.y;
		*pflZ = d3dVDst.z;
	}

EXIT_FAIL:
	SAFERELEASE(pVector);

	return hr;
}
HRESULT CVWScale3DTool::OnDoneScaling()
{
	HRESULT hr = S_OK;
	POSITION pos;
	CTranslate3DObject * pCTrans = NULL;
	IVector			*pvPos = NULL;

	for( pos = m_TransformList.GetHeadPosition(); pos != NULL; )
	{
		pCTrans = m_TransformList.GetNext( pos );
		if(NULL != pCTrans)
		{
			pvPos = NULL;
			if (FAILED(hr = pCTrans->m_pThing->get_ObjectProperty(bstrScale, (IObjectProperty**)&pvPos)))
				goto FAIL_EXIT;

			pvPos->set(pCTrans->currentLocation.x, pCTrans->currentLocation.y, pCTrans->currentLocation.z);
		}
	}

FAIL_EXIT:
	SAFERELEASE(pvPos);
	return hr;
}
Exemple #14
0
void SequenceToBatch::sequence2BatchCopy(Matrix &batch,
                                         Matrix &sequence,
                                         IVector &seq2BatchIdx,
                                         bool seq2batch) {
  int seqWidth = sequence.getWidth();
  int batchCount = batch.getHeight();
  real *batchData = batch.getData();
  real *seqData = sequence.getData();
  int *idxData = seq2BatchIdx.getData();

  if (useGpu_) {
    hl_sequence2batch_copy(
        batchData, seqData, idxData, seqWidth, batchCount, seq2batch);
  } else {
    if (seq2batch) {
#ifdef PADDLE_USE_MKLML
      const int blockMemSize = 8 * 1024;
      const int blockSize = blockMemSize / sizeof(real);
#pragma omp parallel for collapse(2)
      for (int i = 0; i < batchCount; ++i) {
        for (int j = 0; j < seqWidth; j += blockSize) {
          memcpy(batch.rowBuf(i) + j,
                 sequence.rowBuf(idxData[i]) + j,
                 (j + blockSize > seqWidth) ? (seqWidth - j) * sizeof(real)
                                            : blockMemSize);
        }
      }
#else
      for (int i = 0; i < batchCount; ++i) {
        memcpy(batch.rowBuf(i),
               sequence.rowBuf(idxData[i]),
               seqWidth * sizeof(real));
      }
#endif
    } else {
#ifdef PADDLE_USE_MKLML
#pragma omp parallel for
#endif
      for (int i = 0; i < batchCount; ++i) {
        memcpy(sequence.rowBuf(idxData[i]),
               batch.rowBuf(i),
               seqWidth * sizeof(real));
      }
    }
  }
}
Exemple #15
0
void SequenceToBatch::sequence2BatchAdd(Matrix &batch,
                                        Matrix &sequence,
                                        IVector &seq2BatchIdx,
                                        bool seq2batch) {
  int seqWidth = sequence.getWidth();
  int batchCount = batch.getHeight();
  real *batchData = batch.getData();
  real *seqData = sequence.getData();
  int *idxData = seq2BatchIdx.getData();

  if (useGpu_) {
    hl_sequence2batch_add(
        batchData, seqData, idxData, seqWidth, batchCount, seq2batch);
  } else {
    for (int i = 0; i < batchCount; ++i) {
      if (seq2batch) {
        batch.subMatrix(i, 1)->add(*sequence.subMatrix(idxData[i], 1));
      } else {
        sequence.subMatrix(idxData[i], 1)->add(*batch.subMatrix(i, 1));
      }
    }
  }
}
boolean CAlgorithmClassifierBliffCFIS::classify(const IFeatureVector& rFeatureVector, float64& rf64Class, IVector& rClassificationValues)
{
	bliff::FeatureVector l_oFeatureVector(rFeatureVector.getSize(), 0);
	for(uint32 j=0; j<rFeatureVector.getSize(); j++)
	{
		l_oFeatureVector[j]=rFeatureVector[j];
	}

	FILE* l_pFile=::fopen(_ParameterFile_, "wb");
	::fwrite(m_oConfiguration.getDirectPointer(), m_oConfiguration.getSize(), 1, l_pFile);
	::fclose(l_pFile);

	itpp::Vec<double> l_vResult;
	double l_dResult;
	bliff::CFIS l_oBliffCFISClassifier;

	l_oBliffCFISClassifier.readParams(_ParameterFile_);
	l_vResult=l_oBliffCFISClassifier.classify(l_oFeatureVector);
	l_dResult=l_oBliffCFISClassifier.assign(l_oFeatureVector);

	if(ip_ui64OutputMode == OVP_TypeId_CFISOutputMode_ClassMembership.toUInteger())
	{
		itpp::Vec<double> l_vTmpVec(l_oBliffCFISClassifier.getNbClasses());
		l_vTmpVec.zeros();
		std::vector<double> l_oClassLabels = l_oBliffCFISClassifier.getClassLabels();

		//finding the maximal degree of fulfillment for each class
		for(uint32 j=0; j < l_oBliffCFISClassifier.getNbRules(); j++)
		{
			for(uint32 i=0; i < l_oClassLabels.size(); i++)
			{
				if((l_oBliffCFISClassifier.getRule(j)->getClass() == l_oClassLabels[i]) && (l_vResult[j]>l_vTmpVec[i]))
				{
					l_vTmpVec[i]=l_vResult[j];
				}
			}
		}

		//switching from rule fulfillment to class membership
		l_vResult=l_vTmpVec;
	}

	//converting from BLiFF++ output to OpenViBE output (classification state)
	rf64Class=l_dResult;
	rClassificationValues.setSize(l_vResult.size());
	for(size_t i=0; i<rClassificationValues.getSize(); i++)
	{
		rClassificationValues[i]=l_vResult[i];
	}

	//labelling the element of the output vector
	if(ip_ui64OutputMode == OVP_TypeId_CFISOutputMode_ClassMembership.toUInteger())
	{
		char l_sBuffer[1024];
		std::vector<double> l_vClassLabels = l_oBliffCFISClassifier.getClassLabels();
		for(uint32 i=0; i < rClassificationValues.getSize(); i++)
		{
			sprintf(l_sBuffer, "Class %d membership degree", (uint32)l_vClassLabels[i]);
			rClassificationValues.setElementLabel(i, l_sBuffer);
		}
	}
	else if(ip_ui64OutputMode == OVP_TypeId_CFISOutputMode_RuleFulfillment.toUInteger())
	{
		char l_sBuffer[1024];
		for(uint32 i=0; i < rClassificationValues.getSize(); i++)
		{
			sprintf(l_sBuffer, "Rule %d degree of fulfillment", (uint32)i+1);
			rClassificationValues.setElementLabel(i, l_sBuffer);
		}
	}
	else
	{
		this->getLogManager() << LogLevel_Warning << "Unhandled CFIS output mode " << ip_ui64OutputMode << " (" << this->getTypeManager().getEnumerationEntryNameFromValue(OVP_TypeId_CFISOutputMode, ip_ui64OutputMode) << "\n";
	}

	return true;
}
Exemple #17
0
void SparseRowCpuMatrix::sgdUpdate(BaseMatrix& value,
                                   IVector& t0,
                                   real learningRate,
                                   int currentTime,
                                   real decayRate,
                                   bool useL1,
                                   bool fini) {
  std::vector<unsigned int>& localIndices = indexDictHandle_->localIndices;

  // t0 and value are vectors
  CHECK_EQ(t0.getSize(), this->height_);
  CHECK_EQ(value.width_, this->height_ * this->width_);

  if (decayRate == 0.0f) {
    if (fini) {
      return;
    }

    for (size_t i = 0; i < localIndices.size(); ++i) {
      real* g = getLocalRow(i);
      real* v = value.rowBuf(localIndices[i]);
      for (size_t j = 0; j < this->width_; ++j) {
        v[j] -= learningRate * g[j];
      }
    }
    return;
  }  // else

  if (useL1) {  // L1 decay
    if (fini) {
      for (size_t i = 0; i < this->height_; ++i) {
        real* v = value.rowBuf(i);
        int* t = t0.getData() + i;
        if (t[0] < currentTime) {
          // W(t0) -> W(t+1)
          int tDiff = currentTime - t[0];
          real delta = tDiff * learningRate * decayRate;
          simd::decayL1(v, v, delta, this->width_);
        }
      }
      return;
    }  // else

    for (size_t i = 0; i < localIndices.size(); ++i) {
      real* g = getLocalRow(i);
      real* v = value.rowBuf(localIndices[i]);
      int* t = t0.getData() + localIndices[i];
      if (t[0] < currentTime) {
        // W(t0) -> W(t)
        int tDiff = currentTime - t[0];
        real delta = tDiff * learningRate * decayRate;
        simd::decayL1(v, v, delta, this->width_);
      }

      // W(t) -> W(t+1)
      for (size_t j = 0; j < this->width_; ++j) {
        v[j] -= learningRate * g[j];
      }
      simd::decayL1(v, v, learningRate * decayRate, this->width_);

      // state update to t+1
      t[0] = currentTime + 1;
    }

  } else {  // L2 decay
    if (fini) {
      for (size_t i = 0; i < this->height_; ++i) {
        real* v = value.rowBuf(i);
        int* t = t0.getData() + i;
        if (t[0] < currentTime) {
          // W(t0) -> W(t+1)
          int tDiff = currentTime - t[0];
          real recip = 1.0f / (1.0f + tDiff * learningRate * decayRate);
          for (size_t j = 0; j < this->width_; ++j) {
            v[j] *= recip;
          }
        }
      }
      return;
    }  // else

    real recipDecay = 1.0f / (1.0f + learningRate * decayRate);

    for (size_t i = 0; i < localIndices.size(); ++i) {
      real* g = getLocalRow(i);
      real* v = value.rowBuf(localIndices[i]);
      int* t = t0.getData() + localIndices[i];
      if (t[0] < currentTime) {
        // W(t0) -> W(t)
        int tDiff = currentTime - t[0];
        real recip = 1.0f / (1.0f + tDiff * learningRate * decayRate);
        for (size_t j = 0; j < this->width_; ++j) {
          v[j] *= recip;
        }
      }

      // W(t) -> W(t+1)
      for (size_t j = 0; j < this->width_; ++j) {
        v[j] = recipDecay * (v[j] - learningRate * g[j]);
      }

      // state update to t+1
      t[0] = currentTime + 1;
    }
  }
}
Exemple #18
0
void Application::DrawGLScene ()
{
	int TimeDelta = GetTickCount () - gTime;
	gTime = GetTickCount ();

	// Do shaders
	static float wave_movement = 0.0f;
	wave_movement += 0.03f; // Increment our wave movement
	if (wave_movement > 6.2831853071) // Prevent crashing
		wave_movement = 0.0f;
	cgGLSetParameter3f(mWave, wave_movement, 1.0f, 1.0f);

	IVector SunDirection = mpEngine->GetSunlightVector ();
	cgGLSetParameter3f (mSunVector, SunDirection.GetX (), SunDirection.GetY (),
											SunDirection.GetZ ());

    mpFog->Draw ();

    mpEngine->Draw ();
		mpEngine->GetParticleManager ()->UpdateAndDrawAll ();
    mpSun->Draw ();

	// Press 'F' for cloud dissipation or 'G' for cloud formation
    if (Keys::FPressed == true)
    {
        mpCloudManager->Form (0.0f, 6000, 10000);
    }
    if (Keys::GPressed == true)
    {
        mpCloudManager->Form (100.0f, 6000, 10000);
    }
		
	// Turn wind on or off
    static bool MovedL = false;
    if (Keys::LeftPressed == true && MovedL == false)
    {
        mpSceneManager->mWind.MoveX (-2.0f);
        MovedL = true;
    }
    static bool MovedR = false;
    if (Keys::RightPressed == true && MovedR == false)
    {
        mpSceneManager->mWind.SetXYZ (0.0f, 0.0f, 0.0f);
        MovedR = true;
    }

	// Make our two boxes crash into each other
	if (mpPolyObj0->Collision (mpPolyObj1) == false)
    {
        mpPolyObj0->Translate (0.0f, 0.0f, -0.1f);
        mpPolyObj1->Translate (0.0f, 0.0f,  0.5f);
    }
	// Experimental - move some vertices around after the collision
	else
		mpPolyObj0->MoveVerticesByBoneId(static_cast<char> (0), 0.0f, 0.0f, 0.001f);

	IVector FountainPos = mpEngine->GetTerrain ()->GetWorldPositionAtCoord (134, 190);
	mpFountain->SetOrigin (FountainPos);
	
	// Watch the terrain rise like yeast!
	static float MaxTerrainHeight = -1.5f;
	static bool CloudsAdded = false;
	MaxTerrainHeight += 0.05f;

	if (MaxTerrainHeight < 20.0f)
    {
			mpEngine->GetTerrain ()->SetMaxHeight
				((MaxTerrainHeight >= 1.0f) ? MaxTerrainHeight : 1.0f);
    }
	else
		{
			mpEngine->GetLightManager ()->Translate (gLightNumber, 0.0f, 0.0f, 0.5f);
			if (!CloudsAdded)
				{
					mpCloudManager->AddCloudPuff (50, FountainPos, 1.0f);
					CloudsAdded = true;
				}
		}
	
    mpCloudManager->Draw (mpEngine->GetCamera ());

		// Make our pixmap fade away
    static unsigned char c = 255;
    if (c > 0) c--;
    mpPixmap->SetOpaqueness (c);
    //mpPixmap->Draw ();

		mpFpsCounter->Draw ();
		mpTimeOfDay->Update (TimeDelta);
		mpTimeOfDay->Draw ();
		mpEngine->UpdateProceduralSkybox (mpTimeOfDay);
		mpEngine->Update (TimeDelta);

		// Draw a frames per second counter
		mpFpsCounter->Update (TimeDelta);
		mpFpsCounter->Draw ();
}
Exemple #19
0
void Skybox::Draw (Camera* rpCamera)
{
    glPushMatrix ();
    glDisable (GL_FOG);
    glEnable (GL_TEXTURE_2D);
    IVector v = rpCamera->GetPosition ();
    glTranslatef (v.GetX (), v.GetY (), v.GetZ ());
		glColor3f (1.0f, 1.0f, 1.0f);
		
    unsigned char LightingOn = glIsEnabled (GL_LIGHTING);
    if (LightingOn == GL_TRUE)
    {
        glDisable (GL_LIGHTING);
    }

    mpTextureManager->LoadTexture (mTextureU);
    glBegin (GL_QUADS);
        glTexCoord2f (1.0f, 0.0f);
        glVertex3f ( 100.0f,  100.0f, -100.0f);
        glTexCoord2f (1.0f, 1.0f);
        glVertex3f ( 100.0f,  100.0f,  100.0f);
        glTexCoord2f (0.0f, 1.0f);
        glVertex3f (-100.0f,  100.0f,  100.0f);
        glTexCoord2f (0.0f, 0.0f);
        glVertex3f (-100.0f,  100.0f, -100.0f);
    glEnd ();

    mpTextureManager->LoadTexture (mTextureD);
    glBegin (GL_QUADS);
        glTexCoord2f (1.0f, 1.0f);
        glVertex3f (-100.0f, -100.0f,  100.0f);
        glTexCoord2f (0.0f, 1.0f);
        glVertex3f ( 100.0f, -100.0f,  100.0f);
        glTexCoord2f (0.0f, 0.0f);
        glVertex3f ( 100.0f, -100.0f, -100.0f);
        glTexCoord2f (1.0f, 0.0f);
        glVertex3f (-100.0f, -100.0f, -100.0f);
    glEnd ();

    mpTextureManager->LoadTexture (mTextureL);
    glBegin (GL_QUADS);
        glTexCoord2f (1.0f, 1.0f);
        glVertex3f (-100.0f,  100.0f, -100.0f);
        glTexCoord2f (0.0f, 1.0f);
        glVertex3f (-100.0f,  100.0f,  100.0f);
        glTexCoord2f (0.0f, 0.0f);
        glVertex3f (-100.0f, -100.0f,  100.0f);
        glTexCoord2f (1.0f, 0.0f);
        glVertex3f (-100.0f, -100.0f, -100.0f);
    glEnd ();

    mpTextureManager->LoadTexture (mTextureR);
    glBegin (GL_QUADS);
        glTexCoord2f (0.0f, 0.0f);
        glVertex3f ( 100.0f, -100.0f, -100.0f);
        glTexCoord2f (1.0f, 0.0f);
        glVertex3f ( 100.0f, -100.0f,  100.0f);
        glTexCoord2f (1.0f, 1.0f);
        glVertex3f ( 100.0f,  100.0f,  100.0f);
        glTexCoord2f (0.0f, 1.0f);
        glVertex3f ( 100.0f,  100.0f, -100.0f);
    glEnd ();

    mpTextureManager->LoadTexture (mTextureF);
    glBegin (GL_QUADS);
        glTexCoord2f (0.0f, 0.0f);
        glVertex3f (-100.0f, -100.0f, -100.0f);
        glTexCoord2f (1.0f, 0.0f);
        glVertex3f ( 100.0f, -100.0f, -100.0f);
        glTexCoord2f (1.0f, 1.0f);
        glVertex3f ( 100.0f,  100.0f, -100.0f);
        glTexCoord2f (0.0f, 1.0f);
        glVertex3f (-100.0f,  100.0f, -100.0f);
    glEnd ();

    mpTextureManager->LoadTexture (mTextureB);
    glBegin (GL_QUADS);
        glTexCoord2f (1.0f, 1.0f);
        glVertex3f (-100.0f,  100.0f,  100.0f);
        glTexCoord2f (0.0f, 1.0f);
        glVertex3f ( 100.0f,  100.0f,  100.0f);
        glTexCoord2f (0.0f, 0.0f);
        glVertex3f ( 100.0f, -100.0f,  100.0f);
        glTexCoord2f (1.0f, 0.0f);
        glVertex3f (-100.0f, -100.0f,  100.0f);
    glEnd ();

    glDisable (GL_TEXTURE_2D);
    glEnable (GL_FOG);
    if (LightingOn == GL_TRUE)
    {
        glEnable (GL_LIGHTING);
    }
    glPopMatrix ();
}
Exemple #20
0
void ConvergenceAnaly::doAnalysisConvergence(
		DVector& prices , DVector& conv,
		DVector& norm_L2 , DVector& norm_Inf,
		DVector& rate_L2 , DVector& rate_Linf, DVector& rate_pointw ){

	// resize the result vectors
	prices.resize(highLevel_-lowLevel_+1);
	conv.resize(highLevel_-lowLevel_+1);
	norm_L2.resize(highLevel_-lowLevel_+1);
	norm_Inf.resize(highLevel_-lowLevel_+1);
	rate_pointw.resize(highLevel_-lowLevel_+1);
	rate_L2.resize(highLevel_-lowLevel_+1);
	rate_Linf.resize(highLevel_-lowLevel_+1);

	std::vector< boost::shared_ptr<FullGrid> > fullgridarray( highLevel_-lowLevel_+1 );

	XMLConfiguration conf(confXMLFile_);

	for (int run = 0 ; run <= highLevel_-lowLevel_ ; run++){
		// create the calculator with the prescribed level
    	FitobCalculator calc( confXMLFile_ , sciprtFile_ , lowLevel_ + run , run);
    	// get the pice and the standard mesh
    	FITOB_OUT_LEVEL3( verb() , "ConvergenceAnaly::doAnalysisConvergence() , start calculating level:" << lowLevel_ + run );
    	fullgridarray[run] = calc.evaluateScript_FG( prices[run] );
    	FITOB_OUT_LEVEL3( verb() , "ConvergenceAnaly::doAnalysisConvergence() , calc level:" << lowLevel_ + run <<::std::setprecision( 12 ) << " , Price:" << prices[run]);


//    in case of MPI only rank 0 should do this
#if defined(FITOB_MPI)
	// evaluate the grid on the evaluation point
	if ( FITOB_MPI_Comm_rank() == 0 ) {
#endif
    	// calculate the convergence values
    	FITOB_OUT( " ====== ConvergenceAnaly::doAnalysisConvergence , printing results ====== " );
    	// for new output
    	FITOB_OUT( "  ");
		FITOB_OUT( "level, price, L-inf err, L2 err, L-inf rate, L2 rate, pointw. err, pointw. rate");
		FITOB_OUT( "-------------------------------------------------------------------------------");
    	for (int ii = 0 ; ii <= run ; ii++){
    		norm_L2[ii] = fitob::l2_norm( &(fullgridarray[ii]->unknVect()) , &(fullgridarray[run]->unknVect()) );
    		norm_Inf[ii] = fitob::inf_norm( &(fullgridarray[ii]->unknVect()) , &(fullgridarray[run]->unknVect()) );
    		conv[ii] = (prices[ii] - prices[run]) / prices[run];

    		rate_L2[ii] = log(norm_L2[0]/norm_L2[ii])/log(2.0)/ii;
    		rate_Linf[ii] = log(norm_Inf[0]/norm_Inf[ii])/log(2.0)/ii;
    		rate_pointw[ii] = log(fabs(conv[0]/conv[ii]))/log(2.0)/ii;


    		if (dimensionAdaptive_){
    			// todo: print the level vector
    			IVector dimensionAdaptiveLevels;
    			conf.getIntVectorConfiguration("thetaconfigurations.gridproperties.convergence-tool.CONV_DIM_ADAPT",
            	        ii , "<xmlattr>.level_vect" , ',' , dimensionAdaptiveLevels);
            	std::cout << "(";
            	for (int jj = 0 ; jj < (int)dimensionAdaptiveLevels.size() ; jj++){
            		std::cout << dimensionAdaptiveLevels[jj] << ",";
            	}
            	std::cout << ")";
    		}
    		// old output
    		//FITOB_OUT( "L"<<lowLevel_+ii<<" Price: " << prices[ii] << " , conv(rel):" << conv[ii] << " , L2:" << norm_L2[ii] << " , Inf:" << norm_Inf[ii] );
    		// new output
    		FITOB_OUT( (lowLevel_+ii) << ", " << prices[ii] << ", " << norm_Inf[ii] << ", " << norm_L2[ii] << ", " << rate_Linf[ii] << ", " << rate_L2[ii] << ", " << conv[ii] << ", " << rate_pointw[ii] );


    		// ===== plott the error of the grid ====
    		/*
    		FullGrid* fg = (fullgridarray[ii].get());
    		DVector copyVect;
    		copyVect.resize(fg->unknVect().size());
    		for (int tmp_ii = 0 ; tmp_ii < (int)fg->unknVect().size() ; tmp_ii++ ) { copyVect[tmp_ii] = fg->unknVect()[tmp_ii]; }

    		GridPlotter* plotter = calc.getPlotter().get();
    		Domain dom = Domain(calc.getNormEvalDomain());
    		MeshContext meshcontex = MeshContext( dom , 0.0 );
    		IVector specialLevels = dom.getLevelVector();
    		boost::shared_ptr<MeshBase> fgnew = boost::shared_ptr<MeshBase>(new FullGrid( &dom , specialLevels , &copyVect ));
    		meshcontex.setMesh( fgnew );
    		fitob::vect_diff( &copyVect , &(fullgridarray[run]->unknVect()));
    		string filename = "convergence_" + boost::lexical_cast<std::string>(ii) + "_";
    		// plot the error mesh
    		plotter->plot( &meshcontex , filename );*/
    	}
#if defined(FITOB_MPI)
	  } // the condition from the MPI so that this section is executed only by the 0-th rank
#endif
	}
	FITOB_OUT( " ====== ConvergenceAnaly::doAnalysisConvergence , END ====== " );
}
//This function builds a list of scalable objects from the selection list.
//pfValid is FALSE if there's nothing to scale.
STDMETHODIMP CVWScale3DTool::IsValid(IVWUIView *pVw,VARIANT_BOOL * pfValid)
{

	HRESULT hr = S_OK;
	CVWTransformPtr TransPtr;
	BSTR bstrReturnValue = NULL;
	VARIANT_BOOL	fLastItem = VARIANT_TRUE;
	COleVariant varProperty;
	IVWFrame *pVWFrame = NULL;
	IVWFrame *pVWParentFrame = NULL;
	CVWThingPtr ThingPtr;
	IVector			*pvPos = NULL;
	float			fPosx, fPosy, fPosz;
	CTranslate3DObject* pTmpTransObj;
	VARIANT_BOOL vbMoveable;

	ASSERT( pfValid );
	if (!pfValid ) return E_POINTER;

	*pfValid = VARIANT_FALSE;
	
	DestroyTransformList();

	if(	m_pSelectionList )
	{
		hr = m_pSelectionList->get_IsEmpty( &fLastItem  );
		if( FAILED(hr) )  goto EXIT_FAIL;

		if( VARIANT_FALSE == fLastItem ) 
		{
			hr = m_pSelectionList->FirstItem( &bstrReturnValue, &varProperty, &fLastItem );
			if( FAILED(hr) ) goto EXIT_FAIL;

			while( VARIANT_FALSE == fLastItem ) 
			{
				SAFEFREESTRING(bstrReturnValue);
				ThingPtr = varProperty;

				if (ThingPtr != NULL)
				{
					COleVariant			var; // get the geometry property
					CComBSTR			bstrType;

					SAFERELEASE(m_pWorld);
					hr = ThingPtr->get_World(&m_pWorld);
					if(FAILED(hr) || !m_pWorld) 	goto EXIT_FAIL;

					//Create our event vector if we don't have one already.
					if (!m_pVector)
					{
						hr = m_pWorld->CreateObjectPropertyExt(CLSID_Vector, NULL, (IObjectProperty**) &m_pVector);
						if (FAILED(hr)) goto EXIT_FAIL;
					}

					hr = ThingPtr->get_ObjectProperty(bstrScale, (IObjectProperty**)&pvPos);
					if (FAILED(hr)) goto EXIT_FAIL;

					hr = pvPos->get(&fPosx, &fPosy, &fPosz);
					if (FAILED(hr)) goto EXIT_FAIL;
					SAFERELEASE(pvPos);

					if (FAILED(hr = ThingPtr->CheckPropertySecurityExt(bstrScale, PS_WRITE)))
					{
						goto SECURITY_ERROR;
					}

					vbMoveable = VARIANT_TRUE;
					if (SUCCEEDED(hr = ThingPtr->get_BOOL(CComBSTR("IsMoveable"), &vbMoveable)) && !vbMoveable)
					{
						goto SECURITY_ERROR;
					}

					if (FAILED(hr = ThingPtr->get_Type(&bstrType.m_str)) || CompareElements(&bstrAvatar.m_str, &bstrType.m_str))
					{
						goto SECURITY_ERROR;
					}

					hr = ThingPtr->InvokeMethodExt(CComBSTR("GetFrame"), NULL, &var);
					if (FAILED(hr)) goto EXIT_FAIL;

					TransPtr = var;
					if( TransPtr != NULL )
					// At least one selected item has an IVWTransform
					{
						hr = TransPtr->QueryInterface(IID_IVWFrame, (void **) &pVWFrame);
						if (SUCCEEDED(hr) && pVWFrame != NULL)
						{
							hr = pVWFrame->GetParent(&pVWParentFrame);
							if (SUCCEEDED(hr) && pVWParentFrame != NULL)
							{
								*pfValid = VARIANT_TRUE;
								POSITION pos = m_TransformList.AddTail( pTmpTransObj = new CTranslate3DObject( ThingPtr, TransPtr, pVWFrame ) );

								pTmpTransObj->currentLocation.x = fPosx;
								pTmpTransObj->currentLocation.y = fPosy;
								pTmpTransObj->currentLocation.z = fPosz;
							}
		    				if( FAILED(hr) ) goto EXIT_FAIL;
							SAFERELEASE(pVWParentFrame);
						}
	    				if( FAILED(hr) ) goto EXIT_FAIL;
						SAFERELEASE(pVWFrame);
					}
SECURITY_ERROR:
					SAFERELEASE(pvPos);
					var.Clear();
				}
				varProperty.Clear();
				hr = m_pSelectionList->NextItem( &bstrReturnValue, &varProperty, &fLastItem );
    			if( FAILED(hr) ) goto EXIT_FAIL;
			}
		}  
	}
	goto EXIT_SUCCEED;
EXIT_FAIL:
	if (!m_TransformList.IsEmpty())
		DeletePtrListElements(&m_TransformList);

	*pfValid = FALSE;

EXIT_SUCCEED:
	SAFERELEASE(pvPos);
	SAFEFREESTRING(bstrReturnValue);
	SAFERELEASE(pVWFrame);
	SAFERELEASE(pVWParentFrame);

	return hr;

}
HRESULT CVWScale3DTool::ScaleSelectedObjects( float flDeltaX, float flDeltaY )
{
	CTranslate3DObject * pCTrans = NULL;
	IDirect3DRMFrame *pRMObjFrame = NULL;
	IDirect3DRMFrame *pRMParentFrame = NULL;
	IDirect3DRMFrame *pRMTmpFrame = NULL;
	D3DVECTOR axis;
	IVWFrame * pScene = NULL;
	BOOL bXAxisLocked, bYAxisLocked, bZAxisLocked;
	DWORD dwTimeNow;
	CComBSTR bstr1, bstr2, bstr3;
	CString tmpStr;
	static DWORD dwTime = - 1;
	HRESULT hr = S_OK;
	POSITION pos;
	CString szTmp;
	D3DVECTOR vecDelta, initialPos;
	IVector* vecPtr = NULL, *vecDestPtr = NULL;
	float fRot;
	float fX, fY, fZ, fTmp;

	D3DVECTOR vecCameraPos, vecObjToCam;

	if (IsPressed('S'))
	{
		flDeltaX *= SLOWKEY_SLOWFACTOR;
		flDeltaY *= SLOWKEY_SLOWFACTOR;
	}

	bXAxisLocked = m_nAxisLock & X_LOCK;
	bYAxisLocked = m_nAxisLock & Y_LOCK;
	bZAxisLocked = m_nAxisLock & Z_LOCK;

	if (m_nCameraMode == TOP)
	{
		flDeltaX /= 64.0f;
		flDeltaY /= 64.0f;
	}

	if (IsPressed('X'))
	{
		if (m_nCameraMode == TOP)
		{
			vecDelta.x = -flDeltaX / 4.0f; 
			vecDelta.y = 0.0f; 
			vecDelta.z = 0.0f;
		}
		else
		{
			vecDelta.x = -flDeltaX / 32.0f; 
			vecDelta.y = 0.0f; 
			vecDelta.z = 0.0f;
		}
	}
	else if (IsPressed('Y'))
	{
		if (m_nCameraMode == TOP)
		{
			vecDelta.x = 0.0; 
			vecDelta.y = 0.0f; 
			vecDelta.z = flDeltaY / 4.0f;
		}
		else
		{
			vecDelta.x = 0.0; 
			vecDelta.y = flDeltaY / 32.0f; 
			vecDelta.z = 0.0f;
		}
	}
	else if (IsPressed('Z'))
	{
		if (m_nCameraMode == TOP)
		{ 
			vecDelta.x = 0.0; 
			vecDelta.y = flDeltaY / 4.0f; 
			vecDelta.z = 0.0f;
		}
		else
		{
			vecDelta.x = 0.0; 
			vecDelta.y = 0.0f; 
			vecDelta.z = flDeltaY / 32.0f;
		}
	}
	else
	{
		if (m_nCameraMode == TOP)
		{
			vecDelta.x = (bXAxisLocked ? 0.0f : -flDeltaX / 4.0f);
			vecDelta.y = 0.0f; 
			vecDelta.z = (bZAxisLocked ? 0.0f : flDeltaY / 4.0f);
		}
		else
		{
			vecDelta.x = (bXAxisLocked ? 0.0f : flDeltaX / 32.0f); 
			vecDelta.y = 0.0f;
			vecDelta.z = (bZAxisLocked ? 0.0f : flDeltaY / 32.0f);  //0.0f; //(bZAxisLocked ? 0.0f : flDeltaX / 32.0f);
		}
	}
	
	hr = m_pRMCameraFrame->GetPosition(NULL, &vecCameraPos);
	if (FAILED(hr)) goto EXIT_FAIL;

	hr = CoCreateInstance(CLSID_Vector, NULL, CLSCTX_INPROC_SERVER, IID_IVector, (LPVOID*)&vecPtr);
	if (FAILED(hr)) goto EXIT_FAIL;

	hr = CoCreateInstance(CLSID_Vector, NULL, CLSCTX_INPROC_SERVER, IID_IVector, (LPVOID*)&vecDestPtr);
	if (FAILED(hr)) goto EXIT_FAIL;
	
	for( pos = m_TransformList.GetHeadPosition(); pos != NULL; )
	{
		pCTrans = m_TransformList.GetNext( pos );
		if(pCTrans != NULL && pCTrans->m_pTrans != NULL)
		{
			hr = pCTrans->m_pVWFrame->get_Frame3D(&pRMObjFrame);
			if (FAILED(hr) || (!pRMObjFrame)) goto EXIT_FAIL;

			hr = pRMObjFrame->GetParent(&pRMParentFrame);
			if (FAILED(hr) || (!pRMParentFrame)) goto EXIT_FAIL;

			pRMObjFrame->GetPosition(NULL, &initialPos);
			if (FAILED(hr)) goto EXIT_FAIL;

			if (!IsPressed(VK_SHIFT))
			{
				vecObjToCam.x = initialPos.x - vecCameraPos.x;
				vecObjToCam.y = 0.0f; //initialPos.y - vecCameraPos.y;
				vecObjToCam.z = initialPos.z - vecCameraPos.z;

				D3DRMVectorNormalize(&vecObjToCam);

				vecPtr->set(vecObjToCam.x, vecObjToCam.y, vecObjToCam.z);
				vecPtr->get_Rotation(&fRot);

				if (fRot >= 0.785 && fRot <= 2.355)
				{ //Camera is behind the object
				}
				else if (fRot >= 2.355 && fRot <= 3.925)
				{ //Camera is left of the object
					float fTmp;

					fTmp = vecDelta.x;
					vecDelta.x = vecDelta.z;
					vecDelta.z = fTmp;
				}
				else if (fRot >= 3.925 && fRot <= 5.495)
				{ //Camera is in front of the object
				}
				else
				{ //Camera is right of the object
					float fTmp;

					fTmp = vecDelta.x;
					vecDelta.x = vecDelta.z;
					vecDelta.z = fTmp;
				}

				ComputeEulerAngles(pCTrans->m_pVWFrame, vecDestPtr);
				vecDestPtr->get(&fX, &fY, &fZ);

				if (fX >= 0.785 && fX <= 2.355)
				{ //Camera is behind the object
					fTmp = vecDelta.z;
					vecDelta.z = vecDelta.y;
					vecDelta.y = fTmp;
				}
				else if (fX >= 2.355 && fX <= 3.925)
				{ //Camera is left of the object
				}
				else if (fX >= 3.925 && fX <= 5.495)
				{ //Camera is in front of the object
					fTmp = vecDelta.z;
					vecDelta.z = vecDelta.y;
					vecDelta.y = fTmp;
				}
				else
				{ //Camera is right of the object
				}

				if (fY >= 0.785 && fY <= 2.355) // && !(fX >= 2.355 && fX <= 3.925))
				{ //Camera is behind the object
					fTmp = vecDelta.x;
					vecDelta.x = vecDelta.z;
					vecDelta.z = fTmp;
				}
				else if (fY >= 2.355 && fY <= 3.925)
				{ //Camera is left of the object
				}
				else if (fY >= 3.925 && fY <= 5.495) // && !(fX >= 2.355 && fX <= 3.925) )
				{ //Camera is in front of the object
					fTmp = vecDelta.x;
					vecDelta.x = vecDelta.z;
					vecDelta.z = fTmp;
				}
				else
				{ //Camera is right of the object
				}
			}
			else
			{	//Shift it pressed
				vecDelta.y = vecDelta.x;
			}

			pRMObjFrame->SetPosition(NULL, 0.0f, 0.0f, 0.0f);
			if (FAILED(hr)) goto EXIT_FAIL;
		
			//Do a uniform (all axis) scaling
//				axis.x = 1.0f + (vecDelta.x > 0 ? vecDelta.x : vecDelta.z);
//				axis.y = 1.0f + (vecDelta.x > 0 ? vecDelta.x : vecDelta.z);
//				axis.z = 1.0f + (vecDelta.x > 0 ? vecDelta.x : vecDelta.z);
//			}
//			else //Normal perspective viewing
//			{
				axis.x = 1.0f + vecDelta.x;
				axis.y = 1.0f + vecDelta.y;
				axis.z = 1.0f + vecDelta.z;
//			}

			//Fix up current scale and fire UI event
			if (SIGN(pCTrans->currentLocation.x) == SIGN(axis.x) && axis.x != 0.0f)
			{
				fTmp = pCTrans->currentLocation.x;

				pCTrans->currentLocation.x *= axis.x;

				if (pCTrans->currentLocation.x < MIN_SCALE || pCTrans->currentLocation.x > MAX_SCALE)
				{
					pCTrans->currentLocation.x = fTmp;
					axis.x = 1.0f;
				}
			}
			else
				axis.x = 1.0f;

			if (SIGN(pCTrans->currentLocation.y) == SIGN(axis.y) && axis.y != 0.0f)
			{
				fTmp = pCTrans->currentLocation.y;

				pCTrans->currentLocation.y *= axis.y;

				if (pCTrans->currentLocation.y < MIN_SCALE || pCTrans->currentLocation.y > MAX_SCALE)
				{
					pCTrans->currentLocation.y = fTmp;
					axis.y = 1.0f;
				}
			}
			else
				axis.y = 1.0f;

			if (SIGN(pCTrans->currentLocation.z) == SIGN(axis.z) && axis.z != 0.0f)
			{
				fTmp = pCTrans->currentLocation.z;

				pCTrans->currentLocation.z *= axis.z;

				if (pCTrans->currentLocation.z < MIN_SCALE || pCTrans->currentLocation.z > MAX_SCALE)
				{
					pCTrans->currentLocation.z = fTmp;
					axis.z = 1.0f;
				}
			}
			else
				axis.z = 1.0f;

			hr = pRMObjFrame->AddScale(D3DRMCOMBINE_BEFORE, axis.x, axis.y, axis.z);
			if (FAILED(hr)) goto EXIT_FAIL;

			pRMObjFrame->SetPosition(NULL, initialPos.x, initialPos.y, initialPos.z);
			if (FAILED(hr)) goto EXIT_FAIL;

			dwTimeNow = GetTickCount();

			if (dwTimeNow - dwTime > 200)
			{
				tmpStr.Format("%0.3f", pCTrans->currentLocation.x);
				bstr1 = tmpStr;
				tmpStr.Format("%0.3f", pCTrans->currentLocation.y); 
				bstr2 = tmpStr;
				tmpStr.Format("%0.3f", pCTrans->currentLocation.z); 
				bstr3 = tmpStr;

				hr = InvokeToolEvent(TOOLEVENT_3DOBJECTSCALED, pCTrans->m_pThing, bstr1.m_str, bstr2.m_str, bstr3.m_str, VARIANT_TRUE);
				if(FAILED( hr )) goto EXIT_FAIL;

				dwTime = dwTimeNow;
			}

			SAFERELEASE(pRMObjFrame);
			SAFERELEASE(pRMParentFrame);
		}
	}

EXIT_FAIL:
	SAFERELEASE(pRMParentFrame);
	SAFERELEASE(pRMObjFrame);
	SAFERELEASE(pScene);
	SAFERELEASE(vecDestPtr);
	SAFERELEASE(vecPtr);
	
	return hr;
}
Exemple #23
0
void Sun::Draw ()
{
    glPushMatrix ();

    glDisable (GL_FOG);
    glEnable (GL_TEXTURE_2D);
    unsigned char LightingOn = glIsEnabled (GL_LIGHTING);
    if (LightingOn == GL_TRUE)
    {
        glDisable (GL_LIGHTING);
    }

    glEnable (GL_ALPHA_TEST);
		glDisable (GL_CULL_FACE);
    glAlphaFunc (GL_GREATER, 0.0f);

    // Sun should always be 90.0 feet away from camera
    IVector camPos = mpEngine->GetCamera ()->GetPosition ();
    glTranslatef (camPos.GetX (), camPos.GetY (), camPos.GetZ ());

    IVector sunPos = mpEngine->GetSunlightVector ().GetReverseVector ();
    sunPos *= 90.0f;

    const float sunRadius = 10.0f;

		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable (GL_BLEND);

	// Draw the sun
    mpTextureManager->LoadTexture (mTextureKey);
    glBegin (GL_QUADS);
    glColor3f (1.0f, 1.0f, 1.0f);
    glTexCoord2f (0.0f, 0.0f);
    glVertex3f (sunPos.GetX () - sunRadius, sunPos.GetY () - sunRadius, sunPos.GetZ ());
    glTexCoord2f (1.0f, 0.0f);
    glVertex3f (sunPos.GetX () + sunRadius, sunPos.GetY () - sunRadius, sunPos.GetZ ());
    glTexCoord2f (1.0f, 1.0f);
    glVertex3f (sunPos.GetX () + sunRadius, sunPos.GetY () + sunRadius, sunPos.GetZ ());
    glTexCoord2f (0.0f, 1.0f);
    glVertex3f (sunPos.GetX () - sunRadius, sunPos.GetY () + sunRadius, sunPos.GetZ ());
    glEnd ();

		mFlareTextureKey = -1;
	// Draw the lens flare
	if (mFlareTextureKey != -1)
	{
		IVector flareOffset = sunPos - mpEngine->GetCamera ()->GetForwardVector ();
		IVector flarePos = sunPos + 1.0f / sunPos.DotProduct (mpEngine->GetCamera ()->GetForwardVector ()) * flareOffset;
		flarePos.SetZ (flarePos.GetZ () + 10.0f);

		float flareRadius = 10.0f;
		mpTextureManager->LoadTexture (mFlareTextureKey);

		glBegin (GL_QUADS);
		glTexCoord2f (0.0f, 0.0f);
		glVertex3f (flarePos.GetX () - flareRadius, flarePos.GetY () - flareRadius, flarePos.GetZ ());
		glTexCoord2f (1.0f, 0.0f);
		glVertex3f (flarePos.GetX () + flareRadius, flarePos.GetY () - flareRadius, flarePos.GetZ ());
		glTexCoord2f (1.0f, 1.0f);
		glVertex3f (flarePos.GetX () + flareRadius, flarePos.GetY () + flareRadius, flarePos.GetZ ());
		glTexCoord2f (0.0f, 1.0f);
		glVertex3f (flarePos.GetX () - flareRadius, flarePos.GetY () + flareRadius, flarePos.GetZ ());
		glEnd ();
	}

    glAlphaFunc (GL_ALWAYS, 0.0f);
		glDisable (GL_BLEND);
    glDisable (GL_ALPHA_TEST);
    glDisable (GL_TEXTURE_2D);
		glEnable (GL_CULL_FACE);
		glEnable (GL_FOG);

    if (LightingOn == GL_TRUE)
    {
        glEnable (GL_LIGHTING);
    }
    glPopMatrix ();
}
STDMETHODIMP CVWExecuteGeomUndo::Redo( IVWUndoItem * predo )
{
	HRESULT hr = S_OK;
	VARIANT varTarget, varRedo;
	IThing *pThing = NULL;
	IVector	*pvPos = NULL;
	IVector	*pvUp = NULL;
	float fX, fY, fCenterX, fCenterY;
	static CComBSTR	bstrScale("Scale");
	static CComBSTR	bstrPosition("Position");
	static CComBSTR	bstrDirection("Direction");
	static CComBSTR	bstrUp("Up");
	IBoundary *pEC = NULL;
	IPropertyList *pBoundaryList = NULL;
	UndoData *pud;
	VARIANT_BOOL vbSafe;
	int i;

	VariantInit(&varTarget);
	VariantInit(&varRedo);

	hr = predo->get_UndoTarget(&varTarget);
	if (FAILED(hr)) goto FAIL_EXIT;

	hr = predo->get_UndoData(&varRedo);
	if (FAILED(hr))	goto FAIL_EXIT;

	pud = (UndoData*) varRedo.byref;
	ASSERT(pud);
	switch(pud->m_ot)
	{
	case SCALE:
		pThing = (IThing*) varTarget.pdispVal;
		ASSERT(pThing);

		if (FAILED(hr = pThing->get_ObjectProperty(bstrScale, (IObjectProperty**)&pvPos)))
			goto FAIL_EXIT;
		pvPos->set(pud->extra.scale.newScale.x, pud->extra.scale.newScale.y, pud->extra.scale.newScale.z);
		break;
	case SCALE2D:
		pEC = (IBoundary*) varTarget.pdispVal;
		ASSERT(pEC);

		fCenterX = pud->extra.scale.oldScale.x;
		fCenterY = pud->extra.scale.oldScale.y;

		i = 0;
		while (TRUE)
		{
			hr = pEC->GetVertexXYExt(i, &fX, &fY);
			if (hr == E_INVALIDARG)
			{
				hr = S_OK;
				break;
			}
			if(FAILED( hr )) goto FAIL_EXIT;

			hr = pEC->SetVertexXY(i, (fX - fCenterX) * pud->extra.scale.newScale.x + fCenterX, (fY - fCenterY) * pud->extra.scale.newScale.y + fCenterY);
			if(FAILED( hr )) goto FAIL_EXIT;
			i++;
		}

		break;
	case TRANSLATE:
		pThing = (IThing*) varTarget.pdispVal;
		ASSERT(pThing);

		if (FAILED(hr = pThing->get_ObjectProperty(bstrPosition, (IObjectProperty**)&pvPos)))
			goto FAIL_EXIT;
		pvPos->set(pud->extra.trans.newPosition.x, pud->extra.trans.newPosition.y, pud->extra.trans.newPosition.z);
		break;
	case TRANSLATE2D:
		pEC = (IBoundary*) varTarget.pdispVal;
		ASSERT(pEC);

		if (pud->extra.trans.nSelectedVert >= 0)  
		{
			//hr = pEC->Translate(pud->extra.trans.newPosition.x + fX, pud->extra.trans.newPosition.y + fY);
			hr = pEC->Translate(pud->extra.trans.newPosition.x, pud->extra.trans.newPosition.y);
			if (FAILED(hr))	goto FAIL_EXIT;
		}
		else //Move the whole Boundary
		{
			hr = pEC->Translate(pud->extra.trans.newPosition.x, pud->extra.trans.newPosition.y);
			if (FAILED(hr))	goto FAIL_EXIT;
		}

		break;
	case ROTATE:
		pThing = (IThing*) varTarget.pdispVal;
		ASSERT(pThing);

		if (FAILED(hr = pThing->get_ObjectProperty(bstrDirection, (IObjectProperty**)&pvPos)))
			goto FAIL_EXIT;
		if (FAILED(hr = pThing->get_ObjectProperty(bstrUp, (IObjectProperty**)&pvUp)))
			goto FAIL_EXIT;
		pvPos->set(pud->extra.rotate.newDirection.x, pud->extra.rotate.newDirection.y, pud->extra.rotate.newDirection.z);
		pvUp->set(pud->extra.rotate.newUp.x, pud->extra.rotate.newUp.y, pud->extra.rotate.newUp.z);
		break;
	case ROTATE2D:
		pEC = (IBoundary*) varTarget.pdispVal;
		ASSERT(pEC);

		hr = pEC->Rotate(0.0f);
		break;
	case NEWBOUNDARY:
		pEC = (IBoundary*) varTarget.pdispVal;
		ASSERT(pEC);

		pud->extra.newboundary.BoundaryList->Add( CComVariant(pEC) );
		if (FAILED(hr)) goto FAIL_EXIT;

		break;
	case DELETEBOUNDARY:
		pEC = (IBoundary*) varTarget.pdispVal;
		ASSERT(pEC);

		pud->extra.newboundary.BoundaryList->Remove(CComVariant(pEC));
		if (FAILED(hr)) goto FAIL_EXIT;

		break;
	case DELETEVERTEX2D:
		pEC = (IBoundary*) varTarget.pdispVal;
		ASSERT(pEC);

		hr = pEC->DeleteVertexSafe(pud->extra.deletevertex.ecVert.index, &vbSafe);
		if (FAILED(hr)) goto FAIL_EXIT;

		hr = pud->extra.deletevertex.BoundaryList->Remove(CComVariant(pEC));
		if (FAILED(hr)) goto FAIL_EXIT;
		hr = pud->extra.deletevertex.BoundaryList->Add(CComVariant(pEC));
		if (FAILED(hr)) goto FAIL_EXIT;

		break;

	case INSERTVERTEX2D:
		pEC = (IBoundary*) varTarget.pdispVal;
		ASSERT(pEC);

		hr = pEC->InsertVertexSafe(	pud->extra.insertvertex.ecVert.index, 
									pud->extra.insertvertex.ecVert.x, 
									pud->extra.insertvertex.ecVert.y, 
									&vbSafe);
		if (FAILED(hr)) goto FAIL_EXIT;

		hr = pud->extra.insertvertex.BoundaryList->Remove(CComVariant(pEC));
		if (FAILED(hr)) goto FAIL_EXIT;
		hr = pud->extra.insertvertex.BoundaryList->Add(CComVariant(pEC));
		if (FAILED(hr)) goto FAIL_EXIT;

		break;
	case FLIPBOUNDARY:
		//pECB = (IBoundaryBuilder*) varTarget.pdispVal;
		//ASSERT(pECB);
		//pECB->ReverseVertices();
		break;
	default:
		OutputDebugString("CVWExecuteGeomRedo::Redo: Unhandled redo type\n");
	}

FAIL_EXIT:
	SAFERELEASE(pvUp);
	SAFERELEASE(pvPos);
	SAFERELEASE(pEC);
	SAFERELEASE(pBoundaryList);
	
	return hr;
}
Exemple #25
0
void AppWin::calcDPosPeierlsNabarro_interm()
{
  int icurr = tabWidget->currentIndex();
  PltWin *pwthis = plotWidget[icurr];
  PltWin *pw;
  FILE *f;
  DVector ubat, dpos(2);
  IVector at;
  double ubmin, ubmax;
  int i, istart, iend, nat, j;
  bool ok;

  //  if (pwthis->nchain==0) {
  //    f = fopen("ub_pos.dat", "w+");
  //    fclose(f);
  //  }

  if (pwthis->applyHow==0)
    istart = iend = icurr;
  else {
    istart = 0;
    iend = tabWidget->count()-1;
  }

  at.Allocate(30); at.EnlargeStep(10);
  ubat.Allocate(30); ubat.EnlargeStep(10);  

  for (i=istart; i<=iend; i++) {
    pw = plotWidget[i];
    if (!pw->isSelected) continue;

    if (i != icurr) {
      pw->applyHow = pwthis->applyHow;
      pw->napicked = pwthis->napicked;
      pw->apicked = pwthis->apicked;
    }

    ok = findDPosPeierlsNabarro(pw, dpos, nat, at, ubat, ubmin, ubmax);
    if (!ok) {
      msgError(err_DPosPeierlsNabarro);
      at.Free();
      ubat.Free();
      pw->napicked = 0;
      pwthis->repaint();
      return;
    }

    if (pw->nchain == 0) {
      pw->dposchain.Allocate(6,2); pw->dposchain.EnlargeStep(2,0);
      pw->nachain.Allocate(6); pw->nachain.EnlargeStep(2);
      pw->achain.Allocate(6,30); pw->achain.EnlargeStep(2,10);
      pw->ubchain.Allocate(6,30); pw->ubchain.EnlargeStep(2,10);
      pw->ubchain_min.Allocate(6); pw->ubchain_min.EnlargeStep(2);
      pw->ubchain_max.Allocate(6); pw->ubchain_max.EnlargeStep(2);
    }

    pw->nchain++;
    pw->dposchain(pw->nchain,1) = dpos(1);
    pw->dposchain(pw->nchain,2) = dpos(2);
    pw->nachain(pw->nchain) = nat;
    pw->ubchain_min(pw->nchain) = ubmin;
    pw->ubchain_max(pw->nchain) = ubmax;
    for (j=1; j<=nat; j++) {
      pw->achain(pw->nchain,j) = at(j);
      pw->ubchain(pw->nchain,j) = ubat(j);
    }

    pw->napicked = 0;
  }

  at.Free();
  ubat.Free();
  pwthis->repaint();
}