Exemplo n.º 1
0
HRESULT CDXVADecoderH264::DecodeFrame(BYTE* pDataIn, UINT nSize, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop)
{
    HRESULT hr = S_FALSE;
    UINT nSlices = 0;
    int nSurfaceIndex = -1;
    int nFieldType = -1;
    int nSliceType = -1;
    int nFramePOC = INT_MIN;
    int nOutPOC = INT_MIN;
    REFERENCE_TIME rtOutStart = _I64_MIN;
    CH264Nalu Nalu;
    UINT nNalOffset = 0;
    CComPtr<IMediaSample> pSampleToDeliver;
    CComQIPtr<IMPCDXVA2Sample> pDXVA2Sample;
    int slice_step = 1;

    if (FFH264DecodeBuffer(m_pFilter->GetAVCtx(), pDataIn, nSize, &nFramePOC, &nOutPOC, &rtOutStart) == -1) {
        return S_FALSE;
    }

    while (!nSlices && slice_step <= 2) {
        Nalu.SetBuffer(pDataIn, nSize, slice_step == 1 ? m_nNALLength : 0);
        while (Nalu.ReadNext()) {
            switch (Nalu.GetType()) {
                case NALU_TYPE_SLICE:
                case NALU_TYPE_IDR:
                    if (m_bUseLongSlice) {
                        m_pSliceLong[nSlices].BSNALunitDataLocation = nNalOffset;
                        m_pSliceLong[nSlices].SliceBytesInBuffer = (UINT)Nalu.GetDataLength() + 3; //.GetRoundedDataLength();
                        m_pSliceLong[nSlices].slice_id = nSlices;
                        FF264UpdateRefFrameSliceLong(&m_DXVAPicParams, &m_pSliceLong[nSlices], m_pFilter->GetAVCtx());

                        if (nSlices > 0) {
                            m_pSliceLong[nSlices - 1].NumMbsForSlice = m_pSliceLong[nSlices].NumMbsForSlice = m_pSliceLong[nSlices].first_mb_in_slice - m_pSliceLong[nSlices - 1].first_mb_in_slice;
                        }
                    }
                    nSlices++;
                    nNalOffset += (UINT)(Nalu.GetDataLength() + 3);
                    if (nSlices > MAX_SLICES) {
                        break;
                    }
                    break;
            }
        }
        slice_step++;
    }

    if (!nSlices) {
        return S_FALSE;
    }

    m_nMaxWaiting = min(max(m_DXVAPicParams.num_ref_frames, 3), 8);

    // If parsing fail (probably no PPS/SPS), continue anyway it may arrived later (happen on truncated streams)
    if (FAILED(FFH264BuildPicParams(&m_DXVAPicParams, &m_DXVAScalingMatrix, &nFieldType, &nSliceType, m_pFilter->GetAVCtx(), m_pFilter->GetPCIVendor()))) {
        return S_FALSE;
    }

    TRACE_H264("CDXVADecoderH264::DecodeFrame() : nFramePOC = %11d, nOutPOC = %11d[%11d], [%d - %d], rtOutStart = [%20I64d]\n", nFramePOC, nOutPOC, m_nOutPOC, m_DXVAPicParams.field_pic_flag, m_DXVAPicParams.RefPicFlag, rtOutStart);

    // Wait I frame after a flush
    if (m_bFlushed && !m_DXVAPicParams.IntraPicFlag) {
        TRACE_H264("CDXVADecoderH264::DecodeFrame() : Flush - wait I frame\n");
        m_nBrokenFramesFlag = 0;
        m_nBrokenFramesFlag_POC = 0;
        m_nfield_pic_flag = m_DXVAPicParams.field_pic_flag;
        m_nRefPicFlag = m_DXVAPicParams.RefPicFlag;
        m_nPrevOutPOC = INT_MIN;
        return S_FALSE;
    }

    /* Disabled, because that causes serious problems.
        // Some magic code for detecting the incorrect decoding of interlaced frames ...
        // TODO : necessary to make it better, and preferably on the side of ffmpeg ...
        if (m_nfield_pic_flag && m_nfield_pic_flag == m_DXVAPicParams.field_pic_flag && m_nRefPicFlag == m_DXVAPicParams.RefPicFlag) {
            if (m_nPrevOutPOC == m_nOutPOC && m_nOutPOC == INT_MIN) {
                m_nBrokenFramesFlag_POC++;
            }
            m_nBrokenFramesFlag++;
        } else {
            m_nBrokenFramesFlag     = 0;
            m_nBrokenFramesFlag_POC = 0;
        }
        m_nfield_pic_flag   = m_DXVAPicParams.field_pic_flag;
        m_nRefPicFlag       = m_DXVAPicParams.RefPicFlag;
        m_nPrevOutPOC       = m_nOutPOC;

        if (m_nBrokenFramesFlag > 4) {
            m_nBrokenFramesFlag = 0;
            if (m_nBrokenFramesFlag_POC > 1) {
                TRACE_H264("CDXVADecoderH264::DecodeFrame() : Detected broken frames ... flush data\n");
                m_nBrokenFramesFlag_POC = 0;
                Flush();
                return S_FALSE;
            }
        }
        //
    */

    CHECK_HR_TRACE(GetFreeSurfaceIndex(nSurfaceIndex, &pSampleToDeliver, rtStart, rtStop));
    FFH264SetCurrentPicture(nSurfaceIndex, &m_DXVAPicParams, m_pFilter->GetAVCtx());

    CHECK_HR_TRACE(BeginFrame(nSurfaceIndex, pSampleToDeliver));

    m_DXVAPicParams.StatusReportFeedbackNumber++;

    // Send picture parameters
    CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_PictureParametersBufferType, sizeof(m_DXVAPicParams), &m_DXVAPicParams));
    CHECK_HR_TRACE(Execute());

    // Add bitstream, slice control and quantization matrix
    CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_BitStreamDateBufferType, nSize, pDataIn, &nSize));

    if (m_bUseLongSlice) {
        CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_SliceControlBufferType, sizeof(DXVA_Slice_H264_Long)*nSlices, m_pSliceLong));
    } else {
        CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_SliceControlBufferType, sizeof(DXVA_Slice_H264_Short)*nSlices, m_pSliceShort));
    }

    CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_InverseQuantizationMatrixBufferType, sizeof(DXVA_Qmatrix_H264), (void*)&m_DXVAScalingMatrix));

    // Decode bitstream
    CHECK_HR_TRACE(Execute());
    CHECK_HR_TRACE(EndFrame(nSurfaceIndex));

#if defined(_DEBUG) && 0
    DisplayStatus();
#endif

    bool bAdded = AddToStore(nSurfaceIndex, pSampleToDeliver, m_DXVAPicParams.RefPicFlag, rtStart, rtStop,
                             m_DXVAPicParams.field_pic_flag, (FF_FIELD_TYPE)nFieldType,
                             (FF_SLICE_TYPE)nSliceType, nFramePOC);

    FFH264UpdateRefFramesList(&m_DXVAPicParams, m_pFilter->GetAVCtx());
    ClearUnusedRefFrames();

    if (bAdded) {
        hr = DisplayNextFrame();
    }

    if (nOutPOC != INT_MIN) {
        m_nOutPOC = nOutPOC;
        m_rtOutStart = rtOutStart;
    }

    m_bFlushed = false;
    return hr;
}
Exemplo n.º 2
0
// === Public functions
HRESULT TDXVADecoderVC1::DecodeFrame(BYTE* pDataIn, UINT nSize, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop)
{
    HRESULT               hr;
    int                   nSurfaceIndex;
    CComPtr<IMediaSample> pSampleToDeliver;
    int                   nFieldType, nSliceType;
    UINT                  nFrameSize, nSize_Result;

    m_pCodec->libavcodec->FFVC1UpdatePictureParam(&m_PictureParams, m_pCodec->avctx, &nFieldType, &nSliceType, pDataIn, nSize, &nFrameSize, FALSE, &m_bFrame_repeat_pict);

    if (m_pCodec->libavcodec->FFIsSkipped(m_pCodec->avctx)) {
        return S_OK;
    }

    // Wait I frame after a flush
    if (m_bFlushed && ! m_PictureParams.bPicIntra) {
        return S_FALSE;
    }

    hr = GetFreeSurfaceIndex(nSurfaceIndex, &pSampleToDeliver, rtStart, rtStop);
    if (FAILED(hr)) {
        ASSERT(hr == VFW_E_NOT_COMMITTED);  // Normal when stop playing
        return hr;
    }

    CHECK_HR(BeginFrame(nSurfaceIndex, pSampleToDeliver));

    DPRINTF(_l("TDXVADecoderVC1::DecodeFrame - PictureType = %s, rtStart = %I64d  Surf=%d\n"), m_pCodec->libavcodec->GetFFMpegPictureType(nSliceType), rtStart, nSurfaceIndex);

    m_PictureParams.wDecodedPictureIndex    = nSurfaceIndex;
    m_PictureParams.wDeblockedPictureIndex  = m_PictureParams.wDecodedPictureIndex;

    // Manage reference picture list
    if (!m_PictureParams.bPicBackwardPrediction) {
        if (m_wRefPictureIndex[0] != NO_REF_FRAME) {
            RemoveRefFrame(m_wRefPictureIndex[0]);
        }
        m_wRefPictureIndex[0] = m_wRefPictureIndex[1];
        m_wRefPictureIndex[1] = nSurfaceIndex;
    }
    m_PictureParams.wForwardRefPictureIndex  = (m_PictureParams.bPicIntra == 0)                ? m_wRefPictureIndex[0] : NO_REF_FRAME;
    m_PictureParams.wBackwardRefPictureIndex = (m_PictureParams.bPicBackwardPrediction == 1) ? m_wRefPictureIndex[1] : NO_REF_FRAME;

    m_PictureParams.bPic4MVallowed       = (m_PictureParams.wBackwardRefPictureIndex == NO_REF_FRAME && m_PictureParams.bPicStructure == 3) ? 1 : 0;
    m_PictureParams.bPicDeblockConfined |= (m_PictureParams.wBackwardRefPictureIndex == NO_REF_FRAME) ? 0x04 : 0;

    m_PictureParams.bPicScanMethod++; // Use for status reporting sections 3.8.1 and 3.8.2

    DPRINTF(_l("TDXVADecoderVC1::DecodeFrame - Decode frame %i\n"), m_PictureParams.bPicScanMethod);

    // Send picture params to accelerator
    CHECK_HR(AddExecuteBuffer(DXVA2_PictureParametersBufferType, sizeof(m_PictureParams), &m_PictureParams));

    // Send bitstream to accelerator
    CHECK_HR(AddExecuteBuffer(DXVA2_BitStreamDateBufferType, nFrameSize ? nFrameSize : nSize, pDataIn, &nSize_Result));

    m_SliceInfo.wQuantizerScaleCode = 1;    // TODO : 1->31 ???
    m_SliceInfo.dwSliceBitsInBuffer = nSize_Result * 8;
    CHECK_HR(AddExecuteBuffer(DXVA2_SliceControlBufferType, sizeof(m_SliceInfo), &m_SliceInfo));

    // Decode frame
    CHECK_HR(Execute());
    CHECK_HR(EndFrame(nSurfaceIndex));

    // ***************
    if (nFrameSize) { // Decoding Second Field
        m_pCodec->libavcodec->FFVC1UpdatePictureParam(&m_PictureParams, m_pCodec->avctx, NULL, NULL, pDataIn, nSize, NULL, TRUE, &m_bFrame_repeat_pict);

        CHECK_HR(BeginFrame(nSurfaceIndex, pSampleToDeliver));

        DPRINTF(_l("TDXVADecoderVC1::DecodeFrame - PictureType = %s\n"), m_pCodec->libavcodec->GetFFMpegPictureType(nSliceType));

        CHECK_HR(AddExecuteBuffer(DXVA2_PictureParametersBufferType, sizeof(m_PictureParams), &m_PictureParams));

        // Send bitstream to accelerator
        CHECK_HR(AddExecuteBuffer(DXVA2_BitStreamDateBufferType, nSize - nFrameSize, pDataIn + nFrameSize, &nSize_Result));

        m_SliceInfo.wQuantizerScaleCode = 1;        // TODO : 1->31 ???
        m_SliceInfo.dwSliceBitsInBuffer = nSize_Result * 8;
        CHECK_HR(AddExecuteBuffer(DXVA2_SliceControlBufferType, sizeof(m_SliceInfo), &m_SliceInfo));

        // Decode frame
        CHECK_HR(Execute());
        CHECK_HR(EndFrame(nSurfaceIndex));
    }
    // ***************

#ifdef _DEBUG
    DisplayStatus();
#endif

    // Re-order B frames
    if (m_pCodec->isReorderBFrame()) {
        if (m_PictureParams.bPicBackwardPrediction == 1) {
            SwapRT(rtStart, m_rtStartDelayed);
            SwapRT(rtStop,  m_rtStopDelayed);
        } else {
            // Save I or P reference time (swap later)
            if (!m_bFlushed) {
                if (m_nDelayedSurfaceIndex != -1) {
                    UpdateStore(m_nDelayedSurfaceIndex, m_rtStartDelayed, m_rtStopDelayed);
                }
                m_rtStartDelayed = m_rtStopDelayed = _I64_MAX;
                SwapRT(rtStart, m_rtStartDelayed);
                SwapRT(rtStop,  m_rtStopDelayed);
                m_nDelayedSurfaceIndex = nSurfaceIndex;
            }
        }
    }

    AddToStore(nSurfaceIndex, pSampleToDeliver, (m_PictureParams.bPicBackwardPrediction != 1), rtStart, rtStop,
               false, (FF_FIELD_TYPE)nFieldType, (FF_SLICE_TYPE)nSliceType, 0);

    m_bFlushed = false;

    return DisplayNextFrame();
}
Exemplo n.º 3
0
// === Public functions
HRESULT CDXVADecoderMpeg2::DecodeFrame(BYTE* pDataIn, UINT nSize, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop)
{
    HRESULT hr;
    int nFieldType;
    int nSliceType;

    FFMpeg2DecodeFrame(&m_PictureParams, &m_QMatrixData, m_SliceInfo, &m_nSliceCount, m_pFilter->GetAVCtx(),
                       m_pFilter->GetFrame(), &m_nNextCodecIndex, &nFieldType, &nSliceType, pDataIn, nSize);

    if (m_PictureParams.bSecondField && !m_bSecondField) {
        m_bSecondField = true;
    }

    // Wait I frame after a flush
    if (m_bFlushed && (!m_PictureParams.bPicIntra || (m_bSecondField && m_PictureParams.bSecondField))) {
        TRACE_MPEG2("CDXVADecoderMpeg2::DecodeFrame() : Flush - wait I frame\n");
        return S_FALSE;
    }

    if (m_bSecondField) {
        if (!m_PictureParams.bSecondField) {
            m_rtStart = rtStart;
            m_rtStop  = rtStop;
            m_pSampleToDeliver = NULL;
            hr = GetFreeSurfaceIndex(m_nSurfaceIndex, &m_pSampleToDeliver, rtStart, rtStop);
            if (FAILED(hr)) {
                ASSERT(hr == VFW_E_NOT_COMMITTED);      // Normal when stop playing
                return hr;
            }
        }
    } else {
        m_rtStart = rtStart;
        m_rtStop  = rtStop;
        m_pSampleToDeliver = NULL;
        hr = GetFreeSurfaceIndex(m_nSurfaceIndex, &m_pSampleToDeliver, rtStart, rtStop);
        if (FAILED(hr)) {
            ASSERT(hr == VFW_E_NOT_COMMITTED);      // Normal when stop playing
            return hr;
        }
    }

    if (m_pSampleToDeliver == NULL) {
        return S_FALSE;
    }

    CHECK_HR_TRACE(BeginFrame(m_nSurfaceIndex, m_pSampleToDeliver));

    if (m_bSecondField) {
        if (!m_PictureParams.bSecondField) {
            UpdatePictureParams(m_nSurfaceIndex);
        }
    } else {
        UpdatePictureParams(m_nSurfaceIndex);
    }

    TRACE_MPEG2("CDXVADecoderMpeg2::DecodeFrame() : Surf = %d, PictureType = %d, SecondField = %d, m_nNextCodecIndex = %d, rtStart = [%I64d]\n",
                m_nSurfaceIndex, nSliceType, m_PictureParams.bSecondField, m_nNextCodecIndex, rtStart);

    CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_PictureParametersBufferType, sizeof(m_PictureParams), &m_PictureParams));
    CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_InverseQuantizationMatrixBufferType, sizeof(m_QMatrixData), &m_QMatrixData));

    // Send bitstream to accelerator
    CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_SliceControlBufferType, sizeof(DXVA_SliceInfo)*m_nSliceCount, &m_SliceInfo));
    CHECK_HR_TRACE(AddExecuteBuffer(DXVA2_BitStreamDateBufferType, nSize, pDataIn, &nSize));

    // Decode frame
    CHECK_HR_TRACE(Execute());
    CHECK_HR_TRACE(EndFrame(m_nSurfaceIndex));

    if (m_bSecondField) {
        if (m_PictureParams.bSecondField) {
            AddToStore(m_nSurfaceIndex, m_pSampleToDeliver, (m_PictureParams.bPicBackwardPrediction != 1), m_rtStart, m_rtStop,
                       false, (FF_FIELD_TYPE)nFieldType, (FF_SLICE_TYPE)nSliceType, FFGetCodedPicture(m_pFilter->GetAVCtx()));
            hr = DisplayNextFrame();
        }
    } else {
        AddToStore(m_nSurfaceIndex, m_pSampleToDeliver, (m_PictureParams.bPicBackwardPrediction != 1), m_rtStart, m_rtStop,
                   false, (FF_FIELD_TYPE)nFieldType, (FF_SLICE_TYPE)nSliceType, FFGetCodedPicture(m_pFilter->GetAVCtx()));
        hr = DisplayNextFrame();
    }

    m_bFlushed = false;

    return hr;
}
// Render the scene.
void D3D12Multithreading::OnRender()
{
	BeginFrame();

#if SINGLETHREADED
	for (int i = 0; i < NumContexts; i++)
	{
		WorkerThread(reinterpret_cast<LPVOID>(i));
	}
	MidFrame();
	EndFrame();
	m_commandQueue->ExecuteCommandLists(_countof(m_pCurrentFrameResource->m_batchSubmit), m_pCurrentFrameResource->m_batchSubmit);
#else
	for (int i = 0; i < NumContexts; i++)
	{
		SetEvent(m_workerBeginRenderFrame[i]); // Tell each worker to start drawing.
	}

	MidFrame();
	EndFrame();

	WaitForMultipleObjects(NumContexts, m_workerFinishShadowPass, TRUE, INFINITE);

	// You can execute command lists on any thread. Depending on the work 
	// load, apps can choose between using ExecuteCommandLists on one thread 
	// vs ExecuteCommandList from multiple threads.
	m_commandQueue->ExecuteCommandLists(NumContexts + 2, m_pCurrentFrameResource->m_batchSubmit); // Submit PRE, MID and shadows.

	WaitForMultipleObjects(NumContexts, m_workerFinishedRenderFrame, TRUE, INFINITE);

	// Submit remaining command lists.
	m_commandQueue->ExecuteCommandLists(_countof(m_pCurrentFrameResource->m_batchSubmit) - NumContexts - 2, m_pCurrentFrameResource->m_batchSubmit + NumContexts + 2);
#endif

	m_cpuTimer.Tick(NULL);
	if (m_titleCount == TitleThrottle)
	{
		WCHAR cpu[64];
		swprintf_s(cpu, L"%.4f CPU", m_cpuTime / m_titleCount);
		SetCustomWindowText(cpu);

		m_titleCount = 0;
		m_cpuTime = 0;
	}
	else
	{
		m_titleCount++;
		m_cpuTime += m_cpuTimer.GetElapsedSeconds() * 1000;
		m_cpuTimer.ResetElapsedTime();
	}

	// Present and update the frame index for the next frame.
	PIXBeginEvent(m_commandQueue.Get(), 0, L"Presenting to screen");
	ThrowIfFailed(m_swapChain->Present(0, 0));
	PIXEndEvent(m_commandQueue.Get());
	m_frameIndex = m_swapChain->GetCurrentBackBufferIndex();

	// Signal and increment the fence value.
	m_pCurrentFrameResource->m_fenceValue = m_fenceValue;
	ThrowIfFailed(m_commandQueue->Signal(m_fence.Get(), m_fenceValue));
	m_fenceValue++;
}
Exemplo n.º 5
0
void KX_KetsjiEngine::Render()
{
	if(m_usedome){
		RenderDome();
		return;
	}
	KX_Scene* firstscene = *m_scenes.begin();
	const RAS_FrameSettings &framesettings = firstscene->GetFramingType();

	m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);
	SG_SetActiveStage(SG_STAGE_RENDER);

	// hiding mouse cursor each frame
	// (came back when going out of focus and then back in again)
	if (m_hideCursor)
		m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);

	// clear the entire game screen with the border color
	// only once per frame
	m_canvas->BeginDraw();
	if (m_drawingmode == RAS_IRasterizer::KX_TEXTURED) {
		m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());
		if (m_overrideFrameColor)
		{
			// Do not use the framing bar color set in the Blender scenes
			m_canvas->ClearColor(
				m_overrideFrameColorR,
				m_overrideFrameColorG,
				m_overrideFrameColorB,
				1.0
				);
		}
		else
		{
			// Use the framing bar color set in the Blender scenes
			m_canvas->ClearColor(
				framesettings.BarRed(),
				framesettings.BarGreen(),
				framesettings.BarBlue(),
				1.0
				);
		}
		// clear the -whole- viewport
		m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
	}

	m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_LEFTEYE);

	// BeginFrame() sets the actual drawing area. You can use a part of the window
	if (!BeginFrame())
		return;

	KX_SceneList::iterator sceneit;
	for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
	// for each scene, call the proceed functions
	{
		KX_Scene* scene = *sceneit;
		KX_Camera* cam = scene->GetActiveCamera();
		// pass the scene's worldsettings to the rasterizer
		SetWorldSettings(scene->GetWorldInfo());

		// this is now done incrementatlly in KX_Scene::CalculateVisibleMeshes
		//scene->UpdateMeshTransformations();

		// shadow buffers
		RenderShadowBuffers(scene);

		// Avoid drawing the scene with the active camera twice when it's viewport is enabled
		if(cam && !cam->GetViewport())
		{
			if (scene->IsClearingZBuffer())
				m_rasterizer->ClearDepthBuffer();
	
			m_rendertools->SetAuxilaryClientInfo(scene);
	
			// do the rendering
			RenderFrame(scene, cam);
		}
		
		list<class KX_Camera*>* cameras = scene->GetCameras();
		
		// Draw the scene once for each camera with an enabled viewport
		list<KX_Camera*>::iterator it = cameras->begin();
		while(it != cameras->end())
		{
			if((*it)->GetViewport())
			{
				if (scene->IsClearingZBuffer())
					m_rasterizer->ClearDepthBuffer();
		
				m_rendertools->SetAuxilaryClientInfo(scene);
		
				// do the rendering
				RenderFrame(scene, (*it));
			}
			
			it++;
		}
		PostRenderScene(scene);
	}

	// only one place that checks for stereo
	if(m_rasterizer->Stereo())
	{
		m_rasterizer->SetEye(RAS_IRasterizer::RAS_STEREO_RIGHTEYE);

		if (!BeginFrame())
			return;


		for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
		// for each scene, call the proceed functions
		{
			KX_Scene* scene = *sceneit;
			KX_Camera* cam = scene->GetActiveCamera();

			// pass the scene's worldsettings to the rasterizer
			SetWorldSettings(scene->GetWorldInfo());
		
			if (scene->IsClearingZBuffer())
				m_rasterizer->ClearDepthBuffer();

			//pass the scene, for picking and raycasting (shadows)
			m_rendertools->SetAuxilaryClientInfo(scene);

			// do the rendering
			//RenderFrame(scene);
			RenderFrame(scene, cam);

			list<class KX_Camera*>* cameras = scene->GetCameras();			
	
			// Draw the scene once for each camera with an enabled viewport
			list<KX_Camera*>::iterator it = cameras->begin();
			while(it != cameras->end())
			{
				if((*it)->GetViewport())
				{
					if (scene->IsClearingZBuffer())
						m_rasterizer->ClearDepthBuffer();
			
					m_rendertools->SetAuxilaryClientInfo(scene);
			
					// do the rendering
					RenderFrame(scene, (*it));
				}
				
				it++;
			}
			PostRenderScene(scene);
		}
	} // if(m_rasterizer->Stereo())

	EndFrame();
}
Exemplo n.º 6
0
void KX_KetsjiEngine::RenderDome()
{
	GLuint	viewport[4]={0};
	glGetIntegerv(GL_VIEWPORT,(GLint *)viewport);
	
	m_dome->SetViewPort(viewport);

	KX_Scene* firstscene = *m_scenes.begin();
	const RAS_FrameSettings &framesettings = firstscene->GetFramingType();

	m_logger->StartLog(tc_rasterizer, m_kxsystem->GetTimeInSeconds(), true);

	// hiding mouse cursor each frame
	// (came back when going out of focus and then back in again)
	if (m_hideCursor)
		m_canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);

	// clear the entire game screen with the border color
	// only once per frame

	m_canvas->BeginDraw();

	// BeginFrame() sets the actual drawing area. You can use a part of the window
	if (!BeginFrame())
		return;

	KX_SceneList::iterator sceneit;
	KX_Scene* scene;

	int n_renders=m_dome->GetNumberRenders();// usually 4 or 6
	for (int i=0;i<n_renders;i++){
		m_canvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER|RAS_ICanvas::DEPTH_BUFFER);
		for (sceneit = m_scenes.begin();sceneit != m_scenes.end(); sceneit++)
		// for each scene, call the proceed functions
		{
			scene = *sceneit;
			KX_Camera* cam = scene->GetActiveCamera();

			m_rendertools->BeginFrame(m_rasterizer);
			// pass the scene's worldsettings to the rasterizer
			SetWorldSettings(scene->GetWorldInfo());

			// shadow buffers
			if (i == 0){
				RenderShadowBuffers(scene);
			}
			// Avoid drawing the scene with the active camera twice when it's viewport is enabled
			if(cam && !cam->GetViewport())
			{
				if (scene->IsClearingZBuffer())
					m_rasterizer->ClearDepthBuffer();
		
				m_rendertools->SetAuxilaryClientInfo(scene);
		
				// do the rendering
				m_dome->RenderDomeFrame(scene,cam, i);
				//render all the font objects for this scene
				RenderFonts(scene);
			}
			
			list<class KX_Camera*>* cameras = scene->GetCameras();
			
			// Draw the scene once for each camera with an enabled viewport
			list<KX_Camera*>::iterator it = cameras->begin();
			while(it != cameras->end())
			{
				if((*it)->GetViewport())
				{
					if (scene->IsClearingZBuffer())
						m_rasterizer->ClearDepthBuffer();
			
					m_rendertools->SetAuxilaryClientInfo(scene);
			
					// do the rendering
					m_dome->RenderDomeFrame(scene, (*it),i);
					//render all the font objects for this scene
					RenderFonts(scene);
				}
				
				it++;
			}
			// Part of PostRenderScene()
			m_rendertools->MotionBlur(m_rasterizer);
			scene->Render2DFilters(m_canvas);
			// no RunDrawingCallBacks
			// no FlushDebugLines
		}
		m_dome->BindImages(i);
	}	

	m_canvas->EndFrame();//XXX do we really need that?

	m_canvas->SetViewPort(0, 0, m_canvas->GetWidth(), m_canvas->GetHeight());

	if (m_overrideFrameColor) //XXX why do we want
	{
		// Do not use the framing bar color set in the Blender scenes
		m_canvas->ClearColor(
			m_overrideFrameColorR,
			m_overrideFrameColorG,
			m_overrideFrameColorB,
			1.0
			);
	}
	else
	{
		// Use the framing bar color set in the Blender scenes
		m_canvas->ClearColor(
			framesettings.BarRed(),
			framesettings.BarGreen(),
			framesettings.BarBlue(),
			1.0
			);
	}
	m_dome->Draw();
	// Draw Callback for the last scene
#ifdef WITH_PYTHON
	scene->RunDrawingCallbacks(scene->GetPostDrawCB());
#endif	
	EndFrame();
}
Exemplo n.º 7
0
int main(int argc, char *argv[]){



# ifdef UNIX
 static char state[256];
 initstate(1997,state,256);
# else
  Exit_wait(1);
# endif

 Set_comment_char(';');

 StartTime();
 char *cfgfile="Params.dta";
 if(argc>1)cfgfile=argv[1];

 int no_remove=1;
 if(argc>2)if(strstr(argv[2],"new"))no_remove=0;

 Open_param_file(cfgfile);
 int nions,i;


 Read_param("Number of ions: %d",&nions);
 Read_param("Ionisation degree: %d",&i);
 ion_charge=i;

 double imass=1.;
 Set_stop(0);
 if(Read_param("Ion mass: %lf",&imass)){
   printf("Non-symmetric plasma specified!\n");
   non_symm=1;
 }

 char tmpstr[256];

 int sep_cm=0;
 if(Read_param("Center-of-mass for components: %s",tmpstr)){
   if(strstr(tmpstr,"separate")){
     printf("Plasma with separated center of masses specified!\n");
     sep_cm=1;
   }
 }



 Plasma *TheGas;  // allocation of the Gas
 double bdens, bTv;
 int bq;
 int bunch=Read_param("Bunch propagation: %lf, %lf, %d",&bdens,&bTv,&bq);
 if(bunch>0){
   printf("Bunch in plasma specified!\n");
   if(bunch!=3){
     msg_error("Invalid bunch specification!\n");
     exit(1);
   }
   bunch=1;
   bTv=sqrt(3*nions*i*bTv); // converting temperature to velocity
   TheGas=(Plasma *)new PlasmaBunch(bdens,bTv,bq,nions,i,imass);
 }
 else{
   TheGas=new Plasma(nions,i,imass);
   bunch=0;
 }
 Plasma &Gas=*TheGas;

 Gas.non_symm=non_symm;
 Gas.one_center=1-sep_cm;

 char dataname[50];
 Read_param("Data name: %s",dataname);
 strncpy(Gas.dataname,dataname,50);

 char ofile[256], pfile[256]="poten.dat";


 strcat(strcpy(pfile,dataname),".pot");

 Read_param("Output file: %s",ofile);
 if(strstr(ofile,"default")){
   strcpy(ofile,dataname);
   strcat(ofile,".eq");
 }

 Read_param("Log file: %s",logfile);
 if(strstr(logfile,"default")){
   strcpy(logfile,dataname);
   strcat(logfile,".log");
 }



 Parameter *p;
 int np=InitParameters(&p);


 double T,Gamma;

 potspec_t reader;
 reader.read_spec(cfgfile);
 Gas.potential=reader.potential;
 strncpy(Gas.charpot,reader.charpot,50);


 /*
 Read_param("Potential: %s",tmpstr);
 strncpy(Gas.charpot,tmpstr,50);
 if(strstr(tmpstr,"Kelbg"))Gas.potential=PotentialKELBG;
 else if(strstr(tmpstr,"Lennard-Johnes"))Gas.potential=PotentialJONES;
 else if(strstr(tmpstr,"Deutsch"))Gas.potential=PotentialDEUTSCH;
 else if(strstr(tmpstr,"Erf"))Gas.potential=PotentialERF;
 else if(strstr(tmpstr,"Cutoff")){
  if(!strcmp(tmpstr,"Cutoff1")){
    Gas.potential=PotentialCUT1;
  }
  else{
    Gas.potential=PotentialCUT;
    Read_param("Cutoff value*: %lf",&E_cut);
  }
 }
 else if(strstr(tmpstr,"ln")){
  Gas.potential=PotentialLN;
  Read_param("Cutoff value*: %lf",&E_cut);
 }
 else if(strstr(tmpstr,"table")){
  Gas.potential=PotentialTAB;
  Read_param("Potential table file: %s",tmpstr);
  Close_param_file();
  ReadPotential(tmpstr);
  Open_param_file(cfgfile);
 }
 else serror("Unknown potential type specified!\n");


 Read_param("Pauli part: %s",tmpstr);
 if(strstr(tmpstr,"n"))Pauli_part=0;


 double Lambda, Lambda_set;
 Read_param("R0: %s",tmpstr);
 if(strstr(tmpstr,"default"))Lambda_set=0.;
 else Lambda_set=atof(tmpstr);

 double Clam_ep=1.,Clam_ee=1;
 Read_param("e-e R0 coefficient: %lf",&Clam_ee);
 Read_param("e-p R0 coefficient: %lf",&Clam_ep);
 */

 int ask=0;
 Read_param("Dialog: %s",tmpstr);
 if(strstr(tmpstr,"y"))ask=1;

 auto_rf=0;
 Gf=10.;
 Read_param("Random force strength: %s",tmpstr);
 if(strstr(tmpstr,"auto"))auto_rf=1;
 else if(strstr(tmpstr,"fluct"))auto_rf=2;
 if(!sscanf(tmpstr,"%lf",&Gf) && auto_rf==0)serror("Can't read Random force strength\n");



 Read_param("Scale velocities: %s",tmpstr);
 if(strstr(tmpstr,"y"))scale_vel=1;

 Read_param("Delta: %lf",&delta);

 Read_param("Trajectory write interval: %ld",&wr_int);
 if(wr_int<=0)wr_int=-1;

 int new_rec=0;
 long wr_ions=0, wr_enseq=-1;
 Set_stop(0);
 if(Read_param("Ions write interval: %ld",&wr_ions)){
   new_rec=1;
   if(!Read_param("Electrons write sequence: %ld",&wr_enseq))wr_enseq=-1;
 }
 Set_stop(1);


 Read_param("Steps to check equillibrium: %ld",&chk_nsteps);
 Read_param("Steps with random force: %ld",&rf_nsteps);
 Read_param("Check steps with random force: %ld",&tst_nsteps);
 Read_param("Steps in equillibrium: %ld",&eq_nsteps);
 Read_param("Time step in equillibrium: %lf",&eq_dt);

 Read_param("Time step for random force: %lf",&rf_dt0);


 char trfile[256]="trajectory";

 int wr_tr=0;
 Set_stop(0);

 /*int pot_corr=0;
 if(Read_param("Potential correction: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
     pot_corr=1;
     strcat(Gas.charpot," corr.");
   }                                       
 }*/


 if(Read_param("Total energy stability: %lf",&stab_acc))e_stab=1;


 if(Read_param("Positive cutoff: %lf",&E_negcut))neg_cut=1;
 else neg_cut=0;

 if(!Read_param("Random generator *:>",tmpstr))strcpy(tmpstr,"3");
 cList rndlist(tmpstr);

 int nrepeats=1;
 if(!Read_param("Repeats: %d",&nrepeats))nrepeats=1;


 char mdistrfile[256]="r-r.distrib";
 double rr_r0=0., rr_r1=-1.;
 if(Read_param("Write r-r distribution: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
     write_distr=1;
     if(!Read_param("r-r file: %s",mdistrfile)||strstr(mdistrfile,"default")){
       strcpy(mdistrfile,"%s%d.rr");
     }
     if(Read_param("r-r range: %lf, %lf",&rr_r0,&rr_r1)!=2){
       rr_r0=0.;
       rr_r1=-1.;
     }
   }
 }


 if(Read_param("Soft step: %s",tmpstr)){
  if(strstr(tmpstr,"n"))soft_step=0;
 }

 if(Read_param("Soft random force: %s",tmpstr)){
  if(strstr(tmpstr,"y")){
    rf_sw_off=1;
    Set_stop(1);
    Read_param("Switch off steps: %ld",&sw_nsteps);
    Set_stop(0);
  }
  else rf_sw_off=0;
 }

 if(Read_param("Relative step: %s",tmpstr)){
  if(strstr(tmpstr,"y"))rel_step=1;
 }


 if(Read_param("Animation : %s",&tmpstr)){
   if(strstr(tmpstr,"y")){
      if(!Read_param("Film directory: %s",filmdir)||strstr(filmdir,"default")){
       strcpy(filmdir,"film/");
      }
   }
 }

 in_cs=-1.;
 Read_param("Initial cluster size: %lf",&in_cs);

 int restart=0,load_fried=0;
 int new_input=0;
 char inptrj[256];

 if(Read_param("Restart: %s",tmpstr)){
  if(strstr(tmpstr,"y")){
    restart=1;
    if(Read_param("Load Friedemann: %s",tmpstr)){
      if(strstr(tmpstr,"y"))load_fried=1;
    }
    if(Read_param("Input from: %s",inptrj))new_input=1;
  }

 }

 long wtype=0;
 if(Read_param("Trajectory file: %s",&trfile)){
  if(strstr(trfile,"default"))strcpy(trfile,"%s%d.r");



  Set_stop(1);
  wr_tr=1;

  Read_param("In output:>",tmpstr);
  if(strstr(tmpstr,"vel"))wtype|=VEL;
  if(strstr(tmpstr,"coord"))wtype|=COORD;
  if(strstr(tmpstr,"flow"))wtype|=FLOW;
  Set_stop(0);

 }
 else printf("Warning: no trajectory file\n");

 int mc_one=0;
 int mc_diff=0;
 int auto_adjust=1;
 double mc_inistep;

 int no_equilibr=0;
 Set_stop(1);
 if(Read_param("Equilibration procedure: %s",tmpstr)){
   if(strstr(tmpstr,"monte-carlo")){
     Set_stop(1);
     mc_equil=1;
     Read_param("One particle MC-step: %s",tmpstr);
     if(strstr(tmpstr,"y")){
       mc_one=1;
       // rf_dt0/=Gas.n;
     }
     Read_paramn(2,"MC step mode and value: %s %lf",tmpstr, &mc_inistep);
     if(strstr(tmpstr,"auto"))auto_adjust=1;
     else if(strstr(tmpstr,"stable"))auto_adjust=0;
     else serror("Unknown MC step mode.\n");
     Set_stop(0);
     mc_diff=0;
     if(Read_param("MC different temperatures: %s",tmpstr)){
       if(strstr(tmpstr,"y")){
	 if(mc_one)serror("Can use different MC temperatures\n"
			  "only in MC one-particle mode!\n");
	 mc_diff=1;
       }
     }
   }
   else{
     mc_equil=0;
     if(strstr(tmpstr,"off"))no_equilibr=1;
     else if(!strstr(tmpstr,"random-force")){
       serror("Unknown equilibration procedure: %s\n",tmpstr);
     }
   }
 }

 

 Set_stop(0);
 mc_calc=0;
 if(Read_param("Equilibrium calculation: %s",tmpstr)){
   if(strstr(tmpstr,"monte-carlo")){
     Set_stop(1);
     mc_calc=1;
     Read_param("One particle MC-step: %s",tmpstr);
     if(strstr(tmpstr,"y")){
       mc_one=1;
       // rf_dt0/=Gas.n;
     }
     Read_paramn(2,"MC step mode and value: %s %lf",tmpstr, &mc_inistep);
     if(strstr(tmpstr,"auto"))auto_adjust=1;
     else if(strstr(tmpstr,"stable"))auto_adjust=0;
     else serror("Unknown MC step mode.\n");
     Set_stop(0);
     mc_diff=0;
     if(Read_param("MC different temperatures: %s",tmpstr)){
       if(strstr(tmpstr,"y")){
	 if(mc_one)serror("Can use different MC temperatures\n"
			  "only in MC one-particle mode!\n");
	 mc_diff=1;
       }
     }
   }
 }

//# ifdef UNIX

 char out_dirs[250]="./",out_dirl[250]="./";
 if(Read_param("Data output directory: %s",out_dirs)){
   if(out_dirs[strlen(out_dirs)-1]!='/')strcat(out_dirs,"/");
   sprintf(tmpstr,out_dirs,dataname);
   strcpy(out_dirs,tmpstr);
# ifdef UNIX
   if(mkdir(out_dirs,S_IRWXU|S_IRGRP|S_IROTH)){
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirs,strerror(errno));
   }
   sprintf(tmpstr,"cp %s %s%s.cfg",cfgfile,out_dirs,dataname);
   //strcat(strcat(tmpstr,dataname),".cfg");
   if(system(tmpstr)==-1)
     printf("\nExec: %s\n",strerror(errno));
# else
   if(_mkdir(out_dirs)){
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirs,strerror(errno));
   }
   char cfgfilef[_MAX_PATH], out_dirsf[_MAX_PATH];
   _fullpath(cfgfilef, cfgfile, _MAX_PATH);
   _fullpath(out_dirsf, out_dirs, _MAX_PATH);
   sprintf(tmpstr,"copy %s %s%s.cfg",cfgfilef,out_dirsf,dataname);
   //strcat(strcat(tmpstr,dataname),".cfg");
   if(system(tmpstr)==-1)
     printf("\nExec: %s\n",strerror(errno));
# endif

   


   strcpy(ofile,strcat(strcpy(tmpstr,out_dirs),ofile));
   strcpy(mdistrfile,strcat(strcpy(tmpstr,out_dirs),mdistrfile));
   strcpy(sfile,strcat(strcpy(tmpstr,out_dirs),sfile));
   strcpy(pfile,strcat(strcpy(tmpstr,out_dirs),pfile));
   if(wr_film){
     strcpy(filmdir,strcat(strcpy(tmpstr,out_dirs),ofile));
# ifdef UNIX
     if(mkdir(filmdir,S_IRWXU|S_IRGRP|S_IROTH)){
# else
     if(_mkdir(filmdir)){
# endif
       if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			       filmdir,strerror(errno) );
     }
     strcat(filmdir,dataname);
   }
 }
 if(Read_param("Process output directory: %s",out_dirl)){
   if(out_dirl[strlen(out_dirl)]!='/')strcat(out_dirl,"/");
   sprintf(tmpstr,out_dirl,dataname);
   strcpy(out_dirl,tmpstr);


# ifdef UNIX
   if(mkdir(out_dirl,S_IRWXU|S_IRGRP|S_IROTH)){
# else
   if(_mkdir(out_dirl)){
# endif 
     if(errno!=EEXIST)serror("Can not create directory: %s.\n%s\n",
			     out_dirl,strerror(errno));
   }


   strcpy(logfile,strcat(strcpy(tmpstr,out_dirl),logfile));
   strcpy(trfile,strcat(strcpy(tmpstr,out_dirl),trfile));
 }

//# endif  // UNIX

 int spwn_trj=0;

 if(Read_param("Spawn trajectories: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
    spwn_trj=1;
    //Read_paramn(1,"Spawn frame: %d",&spwn_frame);
    no_test=1; // no RF test for equilibrartion
   }
 }

 Gas.stable_ions=0;
 if(Read_param("Stable ions: %s",tmpstr)){
   if(strstr(tmpstr,"y")){
    Gas.stable_ions=1;

   }
 }

 int repc_i=0;
 if(!Read_param("Repeat counter start: %d",&repc_i))repc_i=0;

 int irescale=0;
 if(Read_param("Ion velocity rescale: %s",tmpstr)){
  if(strstr(tmpstr,"y"))irescale=1;
  if(strstr(tmpstr,"reset"))irescale=2;
 }

 /*
 int limrescale=0;
 if(Read_param("Rescale on electron temperature reached: %lf  %ld",&limTe,&limstpe)==2){
  limrescale=1;
  limspec=0x2;
  limrescale_switch(0);
 } */

 int limrescale=0;
 int inc_mes=0;

 if(Read_param("Incremental measurement (T0,dT,mes_steps): %lf,%lf,%ld",&incT0,&incdT,&incStp)==3){
   inc_mes=1;
   fixT=incT0;
   limstpe=1;
   limstpi=1;
 }



 Set_stop(1);



 Gas.ini_Te=Gas.ini_Ti=1.;  // by default equal temperatures
 Read_param("Initial velocity distribution: %s",tmpstr);
 if(strstr(tmpstr,"maxwell"))in_distr=MAXWELL;
 else if(strstr(tmpstr,"max_polak"))in_distr=MAXWELL_P;
 else if(strstr(tmpstr,"zero")){
   if(mc_equil){
     in_distr=MAXWELL;
     printf("Warning: setting 'maxwell' initial vel. distribution for MC!\n");
   }
   else in_distr=ZEROVEL;
 }
 else if(strstr(tmpstr,"separate")){
   in_distr=SEPARATE;
   int &ndistr=Gas.idistr;
   int nr;
   char relstr[200];
   for(i=0;i<2;i++){
    if(i==0)nr=  Read_param("Electron velocity distribution: %s  %lf  %s",tmpstr,&Gas.ini_Te,relstr);
    else{
     nr= Read_param("Ion velocity distribution: %s  %lf %s",tmpstr,&Gas.ini_Ti,relstr);
     Gas.edistr=ndistr;
    }
    if(nr<2){
      serror("Can't read velocity distribution parameters!\n");
    }
    if(nr>=2){
      if(strstr(relstr,"abs")){
        if(i==0)Gas.rel_Te=0;
        else Gas.rel_Ti=0;
      }
    }

    if(strstr(tmpstr,"maxwell"))ndistr=MAXWELL;
    else if(strstr(tmpstr,"max_polak"))ndistr=MAXWELL_P;
    else if(strstr(tmpstr,"zero"))ndistr=ZEROVEL;
    else {
     printf("Warning: unknown distribution '%s', setting to 'zero'\n",tmpstr);
     ndistr=ZEROVEL;
    }
   }
 }
 else{
   printf("Warning: unknown distribution '%s', setting to 'zero'\n",tmpstr);
   in_distr=ZEROVEL;
 }

 

 Close_param_file();


 Statistics sT(&Gas.T),sEcoul(&Gas.Ecoul),sEpotent(&Gas.Epotent),sQuant(&Gas.Quant), sEtot(&Gas.Etot);
 Statistics sTi(&Gas.Ti),sTe(&Gas.Te);
 const int nstat=7;
 Statistics *stats[nstat]={&sT,&sEcoul,&sEpotent,&sQuant,&sEtot,&sTi,&sTe};

 SetTableform(GNU);
 if(no_remove){
   no_remove=CheckData(sfile,ofile,dataname,np,p,ask);
 }

 if(restart && !wr_tr && !new_input)serror("No trajectory file specified, cannot restart.\n");
 if(restart && new_input && wr_tr)
   if(!strcmp(trfile,inptrj))
     serror("Equal names for input and output trj-files.\n");


 FILE *f1;
 if(!no_remove || no_remove==2){
  if(!no_remove)f1=Err_fopen(ofile,"wt");
  else f1=Err_fopen(ofile,"at");
  BeginFrame(f1,dataname,np,p);
  fprintf(f1,"%9.9s %9.9s %9.9s %9.9s %9.9s %9.9s %9.9s %9.9s\n",
             "T","Ecoul","Epotent","Equant","dT","dEcoul","dEpotent","dEquant");
  fclose(f1);
 }

 double t=0;

 f1=fopen(logfile,"rt");
 if(f1){
   if(!restart && !no_remove){
     fclose(f1);
     remove(logfile);
   }
   else {// reading 'log' time
     fseek(f1,0,SEEK_END);
     long pos=ftell(f1)-4;
     do{
       fseek(f1,pos,SEEK_SET);
       if(fgetc(f1)=='\n'){
	        fscanf(f1,"%lf",&t);
         //printf("new t: %f\n",t);
	        break;
       }
       pos--;
     }while(pos>=0);
     fclose(f1);
   }
 }


 int ccount=CurrentCount(np,p);
 WriteStatus(!ccount,sfile,dataname,np,p);



 do{

   //Gamma=get_pc(p[0]);
   //T=get_pc(p[1]);



  char ctrfile[256];
  sprintf(ctrfile,trfile,dataname,ccount);
  char ss[100];
  sprintf(ss,"%s%d",dataname,ccount);
  sprintf(distrfile,mdistrfile,dataname,ccount);

  // StatusLine(str,np,p);
  //show_status(440,str);

  long i,n,m,nf=0;

  //Gas.adjustTG(T,Gamma);

  AdjustGas(Gas,p,np);
  T=Gas.par_T;
  Gamma=Gas.par_Gamma;

  double me=0.9109534e-30;
  double qe=1.602e-19;
  double Kb=1.38e-23;
  double unit_t=qe*qe/(4*M_PI*8.854e-12)*sqrt(me);


  // overcoming g++ bug with -O3
  double jojo=Kb*T*1.e4;
  //printf("c2: %e\n",jojo);
  jojo=jojo*jojo*jojo;
  jojo=sqrt(jojo);
  //printf("c21: %e\n",jojo);
  unit_t/=jojo;
  //printf("c3:\n");

  double unit_h=Kb*T*1e4*unit_t;
  double h_qwer=1.0545887e-34;

  reader.calc_lambda(T,Gas.ini_Te,Gas.ini_Ti,Gas.mass);

  /*
  if(!non_symm){
   if(Lambda_set!=0.0){
     Lambda=Lambda_set/unit_l;
     equal_lambda=0;
   }
   else {
     Lambda=0.179*sqrt(T);
     equal_lambda=1;
   }
   Lambda_pauli=0.179*sqrt(T);
   //non_symm=0;
   Lambda_ee=Lambda_pp=Lambda*Clam_ee;
   if(fabs(Clam_ee-1.)>1e-5)equal_lambda=0;
   Lambda_ep=Lambda*Clam_ep;
  }
  else{
   if(Lambda_set!=0.0){
     serror("Can not setup lambda for nonsymmetric plasma.\n");
     //Lambda=Lambda_set/unit_l;
     //Lambda_ep=Lambda*Clam_ep;
     //Lambda_ee=Lambda*Clam_ee;
     //equal_lambda=0;
   }
   else{
     if(strstr(Gas.charpot,"Deutsch")){
       printf("Setting lambda values for Deutsch potential !!!\n");
       Lambda_pauli=h_qwer/(unit_h);
       Lambda=Lambda_pauli/sqrt(2*M_PI);
       double m_ee=0.5, m_pp=0.5*Gas.mass, m_ep=Gas.mass/(1.+Gas.mass);

       Lambda_ee=Lambda/sqrt(m_ee);
       Lambda_pp=Lambda/sqrt(m_pp);
       Lambda_ep=Lambda/sqrt(m_ep);
     }
     else { //if(strstr(Gas.charpot,"Kelbg")){
       printf("Setting lambda values for Kelbg potential !!!\n");

       Lambda_pauli=h_qwer/(unit_h);
       Lambda=Lambda_pauli;
       double m_ee=0.5, m_pp=0.5*Gas.mass, m_ep=Gas.mass/(1.+Gas.mass);
       double t_ep=Gas.ini_Te;
       double t_pp=Gas.ini_Ti;
       double t_ee=Gas.ini_Te;

       Lambda_ee=Lambda/sqrt(2*m_ee*t_ee);
       Lambda_pp=Lambda/sqrt(2*m_pp*t_pp);
       Lambda_ep=Lambda/sqrt(2*m_ep*t_ep);
     }

   }
  } */


  if(rel_step)rf_dtcoeff=1./Gas.Wpe;

  double kk=(1.602e-19)*(1.602e-19)/(4*M_PI*1.38e-23*T*1e4*8.854e-12);



  printf("Simulation parameters:\n");
  printf("Gamma =%f\n"
	 "L=%f=%12e m\n"
	 "lambda=%f=%12e m\n"
	 "1/Wp=%f\n"
	 "Rd=%f\n",Gamma,Gas.L, Gas.L*kk,reader.Lambda,reader.Lambda*kk,1./Gas.Wpe,RDebye);
  printf("Density = %1.2e cm^(-3)\n"
	 "T= %f K\n",Gas.par_density*1e19,T*1e4);

  printf("Time step relations:\n");
  printf("dtrf*Wp= %f, dteq*Wp= %f\n", (rel_step ? rf_dt0 : rf_dt0*Gas.Wpe),
	 (rel_step ? eq_dt : eq_dt*Gas.Wpe));


  double t_inter=RDebye/sqrt(2*getEmax(Gas));


  printf("dtrf/tint= %f, dteq/tint= %f\n", rf_dt0*rf_dtcoeff/t_inter,
	 eq_dt*rf_dtcoeff/t_inter);


  reader.calc_correction(Gas.par_T);
  reader.write_pot(pfile, Gas.L);

  /*
  //if(ccount==1)t/=Gas.Wpe;
  if(pot_corr){
    //Correction(IONION,Gas.potential,Gas.par_T);
    Correction(IONELC,Gas.potential,Gas.par_T);
    Correction(ELCELC,Gas.potential,Gas.par_T);
  }*/

  Statistics rs[nstat];



  int repi=0;
  int repc=repc_i;

  do{ //through nrepeats

    printf("\nStarting calculation #%d...\n",repc);
    flm_count=0;

    if(repc>0){
      repi++;
      sprintf(tmpstr,"%02d",repc);
      if(repi>1){
       distrfile[strlen(distrfile)-2]=0;
       ctrfile[strlen(ctrfile)-2]=0;
      }
      strcat(distrfile,tmpstr);
      strcat(ctrfile,tmpstr);
    }


    if(write_distr){
      DRRee.init(rr_r0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
      DRRep.init(rr_r0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
      if(non_symm)DRRpp.init(0,(rr_r1>0 ? rr_r1 : Gas.L/2),400);
    }

    long ftype=wtype;


    if(restart){
      printf("restarting...\n");
      if((mc_equil && spwn_trj) || mc_calc){
        mc_equil=-1;
        MC = new mc_simm(Gas,mc_inistep*Gas.L /*Gas.L/Gas.n*/,0.5,
			 mc_one,mc_diff);
        if(!MC)serror("Cannot allocate MCsimm\n");
        MC->auto_adjust=auto_adjust;
      }
      else mc_equil=0;

      if(!new_input)strcpy(inptrj,ctrfile);

      if(load_fried){
        LoadFriedemann(inptrj,Gas);
        Gas.dt=eq_dt;
        if(rel_step)Gas.dt/=Gas.Wpe;

        if(eq_nsteps<wr_int)eq_nsteps=wr_int;
	m=wr_int;
	n=eq_nsteps/m;
	Gas.ext_force=void_force1;
	wr_tr=0;
	ftype=0;
      }
      else{
	Gas.dt=(rel_step ? eq_dt/Gas.Wpe : eq_dt);
	Trajectory.Check(inptrj,wtype,Gas,wr_int,wr_ions,wr_enseq,new_input);
	if(Trajectory.wtype !=0 && !new_input){
	  Gas.dt=Trajectory.AdjustInterval(Gas.dt);
	}

	long stp;
	if(!new_input){
	  stp=Trajectory.ReloadGas(Gas,1);
	  t=stp*Trajectory.file_dt();
	  nf=(long)(t/Gas.dt/wr_int+0.01);
	}
	else{
	  stp=Trajectory.ReloadGas(Gas,0);
	  t=0;
	  nf=0;
	}
	printf("t= %f, nf= %ld,  %f\n",t,nf,(t/Gas.dt/wr_int));

	//serror("Restart is not yet implemented !\n");
        Gas.ext_force=void_force1;
      }
      //restart=0;
    }
    else{
      rand_init=rndlist.step();
      if(rand_init<0){
        rndlist.rewind();
        rand_init=rndlist.step();
      }

      strcat(distrfile,"e");


      if((mc_equil && (!spwn_trj || (repc==repc_i && spwn_trj))) || mc_calc){
        mc_equil=1;
        MC = new mc_simm(Gas,mc_inistep*Gas.L /*Gas.L/Gas.n*/,0.5,
			 mc_one,mc_diff);
        if(!MC)serror("Cannot allocate MCsimm\n");
        MC->auto_adjust=auto_adjust;
      }

      if(!no_equilibr){
        if(!spwn_trj || (spwn_trj && repc==repc_i)){
          limrescale_switch(0);
          Equillibrium(t,Gas,stats,nstat);
          limrescale_switch(limrescale);
        }
      }
      else{
        Gas.r0=0.05;
        Gas.init_config(in_cs,in_distr);
      }

      distrfile[strlen(distrfile)-1]=0; // deleting 'e'

      if(mc_equil){
       if(spwn_trj){
        Gas.init_vel(in_distr);
       }
       else if(!mc_calc){
	 delete MC;
	 mc_equil=-1;
       }
       else
         mc_equil=1;
      }

      Gas.dt=eq_dt;
      if(rel_step)Gas.dt/=Gas.Wpe;

    }
    if(irescale){
     if(irescale==1)Gas.ivel_scale(1.);
     else Gas.init_vel(in_distr);
    }

    if(eq_nsteps<wr_int)eq_nsteps=wr_int;
    if(wr_int>0){
      n=eq_nsteps/wr_int;
      m=wr_int;
    }
    else if(eq_nsteps>=500){
      n=eq_nsteps/500;
      m=500;
    }
    else{
      n=1;
      m=eq_nsteps;
    }

    if(wr_tr && (!restart || new_input || (restart && ftype==0))){

      //WriteHeader(ctrfile,wtype,Gas,Gamma,T, ss,m);

      // initializing PlasmaRec
      Trajectory.Clear();
      Trajectory.Init(ctrfile,wtype,Gas,wr_int,wr_ions,wr_enseq);
    }
    if(wr_tr && (restart && ftype==0)){
      //WriteStep(ctrfile,wtype,Gas,0);
    }

    Statistics statsl[nstat];

    Trajectory.valid=wr_tr;
    // new cycle

    if(bunch){
      PlasmaBunch *pb=(PlasmaBunch *)&Gas;
      pb->start_bunch();
    }
    for(i=nf;i<n;i++){
      double term_c=1.;
      if(Gas.stable_ions)term_c=(double)Gas.ne/Gas.n;
      printf("Equilibrium calculation: %f%% complete, T= %f Et=%f\n",(i+1)*100./n,Gas.T,Gas.T*3/2*term_c+Gas.Epotent/Gas.n);

      if(StopStatus(sfile,3)){
       	StopStatus(sfile,-1);
        serror("Program interrupted!\n");
      }

      if(mc_equil && spwn_trj){
        mc_equil=1;
        double ratio=MC->get_ratio();
        if(ratio<1e-10)printf("Estimated randomization steps: infinity\n");
        else printf("Estimated randomization steps: %d\n",(int)(Gas.n*Gas.L/MC->dc[1]/ratio));
      }
      MoveIt(t,m,m,Gas,stats,statsl,nstat);


      //if(wr_tr)WriteStep(ctrfile,wtype,Gas,i);
      if(write_distr)WriteDRR(distrfile);
      if(wr_film)WriteFilm(filmdir,Gas);
    }
    if(bunch){
      PlasmaBunch *pb=(PlasmaBunch *)&Gas;
      pb->stop_bunch();
    }

    if(write_distr)WriteDRR(distrfile);

    for(i=0;i<nstat;i++)rs[i]+=*(stats[i]);
    repc++;

    if(new_input)restart=0;
  }while(repc<nrepeats);

  if(spwn_trj)delete MC;

  f1=Err_fopen(ofile,"at");
  MiddleFrame(f1,np,p);
  int gn=Gas.n;
  //fprintf(f1,"%9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f\n",
  //       sT.av()*T,sEcoul.av()/gn,sEpotent.av()/gn,sQuant.av()/gn,
  //       sT.dev()*T,sEcoul.dev()/gn,sEpotent.dev()/gn,sQuant.dev()/gn);

  fprintf(f1,"%9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f\n",
         rs[0].av()*T,rs[1].av()/gn,rs[2].av()/gn,rs[3].av()/gn,
         rs[0].dev()*T,rs[1].dev()/gn,rs[2].dev()/gn,rs[3].dev()/gn);

  fclose(f1);

  ccount=CycleCount(np,p);
  WriteStatus(!ccount,sfile,dataname,np,p);

  restart=0;
  repc=0;
 }while(ccount);
 return 0;
}
Exemplo n.º 8
0
///////////////////////////////////////////////////////////////////////////////////////////////////
/// CelShadeApp::CelShadeD3D
///
/// @brief
///     Render a cel-shading demo using Direct3D
/// @return
///     N/A
///////////////////////////////////////////////////////////////////////////////////////////////////
void CelShadeApp::CelShadeD3D()
{
    ID3D11DeviceContext* pContext = m_pDxData->pD3D11Context;
    ID3D11Device* pDevice = m_pDxData->pD3D11Device;

    D3DX11_IMAGE_LOAD_INFO imageLoadInfo;
    memset( &imageLoadInfo, 0, sizeof(D3DX11_IMAGE_LOAD_INFO) );
    imageLoadInfo.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    imageLoadInfo.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

    DxTextureCreateInfo shadeTexInfo;
    memset(&shadeTexInfo, 0, sizeof(DxTextureCreateInfo));
    shadeTexInfo.flags.RenderTarget = TRUE;
    shadeTexInfo.flags.ShaderInput = TRUE;
    shadeTexInfo.format = DXGI_FORMAT_R8G8B8A8_UNORM;
    shadeTexInfo.width = m_screenWidth;
    shadeTexInfo.height = m_screenHeight;
    DxTexture* pShadeTex = DxTexture::Create(pDevice, &shadeTexInfo);

    DxTextureCreateInfo edgeTexInfo;
    memset(&edgeTexInfo, 0, sizeof(DxTextureCreateInfo));
    edgeTexInfo.flags.RenderTarget = TRUE;
    edgeTexInfo.flags.ShaderInput = TRUE;
    edgeTexInfo.format = DXGI_FORMAT_R8G8B8A8_UNORM;
    edgeTexInfo.width = m_screenWidth;
    edgeTexInfo.height = m_screenHeight;
    DxTexture* pEdgeTex = DxTexture::Create(pDevice, &edgeTexInfo);

    // Samplers  /////////////////////////////////////////////////////////////////////////////

    // SamplerState PointSampler : register(s0);

    D3D11_SAMPLER_DESC pointSamplerDesc;
    memset(&pointSamplerDesc, 0, sizeof(D3D11_SAMPLER_DESC));
    pointSamplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
    pointSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    pointSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    pointSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    pointSamplerDesc.MinLOD = -FLT_MAX;
    pointSamplerDesc.MaxLOD = FLT_MAX;
    pointSamplerDesc.MipLODBias = 0.0f;
    pointSamplerDesc.MaxAnisotropy = 16;

    ID3D11SamplerState* pPointSampler = NULL;
    pDevice->CreateSamplerState(&pointSamplerDesc, &pPointSampler);

    //
    UINT numVertices = 0, numIndices = 0;
    VertexPTN* pVB = NULL;
    UINT* pIB = NULL;
    ImportPly("Content/dragon_vrip_res3.ply", numVertices, &pVB, numIndices, &pIB);
    //ImportPly("Content/bun_zipper_res4.ply", numVertices, &pVB, numIndices, &pIB);
    DxMeshCreateInfo meshCreateInfo = {0};
    meshCreateInfo.indexCount = numIndices;
    meshCreateInfo.pIndexArray = pIB;
    meshCreateInfo.indexFormat = DXGI_FORMAT_R32_UINT;
    meshCreateInfo.pVertexArray = pVB;
    meshCreateInfo.vertexCount = numVertices;
    meshCreateInfo.vertexElementSize = sizeof(VertexPTN);
    DxMesh* pMesh = DxMesh::Create(pDevice, &meshCreateInfo);

    Plane p;
    DxMeshCreateInfo planeMeshInfo;
    memset(&planeMeshInfo, 0, sizeof(planeMeshInfo));
    planeMeshInfo.pVertexArray = p.GetVB();
    planeMeshInfo.vertexCount = p.NumVertices();
    planeMeshInfo.vertexElementSize = sizeof(VertexPTN);

    DxMesh* pPlaneMesh = DxMesh::Create(pDevice, &planeMeshInfo);

    Cube c;
    DxMeshCreateInfo cubeMeshInfo;
    memset(&cubeMeshInfo, 0, sizeof(cubeMeshInfo));
    cubeMeshInfo.pVertexArray = c.GetVB();
    cubeMeshInfo.vertexCount = c.NumVertices();
    cubeMeshInfo.vertexElementSize = sizeof(VertexPT);

    DxMesh* pCubeMesh = DxMesh::Create(pDevice, &cubeMeshInfo);

    D3D11_SUBRESOURCE_DATA cbInitData;
    memset(&cbInitData, 0, sizeof(D3D11_SUBRESOURCE_DATA));	

    // Camera Buffer
    CameraBufferData cameraData;
    memset(&cameraData, 0, sizeof(CameraBufferData));

    DxBufferCreateInfo cameraBufferCreateInfo = {0};
    cameraBufferCreateInfo.flags.cpuWriteable = TRUE;
    cameraBufferCreateInfo.elemSizeBytes = sizeof(CameraBufferData);
    cameraBufferCreateInfo.pInitialData = &cameraData;
    DxBuffer* pCameraBuffer = DxBuffer::Create(pDevice, &cameraBufferCreateInfo);

    // Shaders ////////////////////////////////////////////////////////////////////////////////////

    m_pPosTexTriVS = DxShader::CreateFromFile(pDevice, "PosTexTri", "Content/shaders/CelShade.hlsl", PosTexVertexDesc, PosTexElements);
    m_pPosTexNormVS = DxShader::CreateFromFile(pDevice, "PosTexNorm", "Content/shaders/CelShade.hlsl", PosTexNormVertexDesc, PosTexNormElements);

    m_pCelShadePS = DxShader::CreateFromFile(pDevice, "CelShade", "Content/shaders/CelShade.hlsl");
    DxShader* pDetectEdges = DxShader::CreateFromFile(pDevice, "DetectEdges", "Content/shaders/CelShade.hlsl");
    DxShader* pApplyTexPS = DxShader::CreateFromFile(pDevice, "ApplyTex", "Content/shaders/CelShade.hlsl");

    DxShader* pCubeVS = DxShader::CreateFromFile(pDevice, "PosTex", "Content/shaders/CelShade.hlsl", PosTexVertexDesc, PosTexElements);
    DxShader* pCubePS = DxShader::CreateFromFile(pDevice, "CubePS", "Content/shaders/CelShade.hlsl");


    ////////////////////////////////////////////////////////////////////////////////////////

    pContext->ClearState();

    // SET RENDER STATE

    FLOAT clearColor[4];
    clearColor[0] = 0.2f;
    clearColor[1] = 0.2f;
    clearColor[2] = 0.2f; 
    clearColor[3] = 1.0f;

    D3D11_RASTERIZER_DESC shadeDesc;
    shadeDesc.FillMode = D3D11_FILL_SOLID;
    shadeDesc.CullMode = D3D11_CULL_BACK;
    shadeDesc.FrontCounterClockwise = FALSE;
    shadeDesc.DepthBias = 0;
    shadeDesc.DepthBiasClamp = 0.0f;
    shadeDesc.SlopeScaledDepthBias = 0;
    shadeDesc.DepthClipEnable = false;
    shadeDesc.ScissorEnable = false;
    shadeDesc.MultisampleEnable = false;
    shadeDesc.AntialiasedLineEnable = false;

    ID3D11RasterizerState* pShadeRS = NULL;
    pDevice->CreateRasterizerState(&shadeDesc, &pShadeRS);

    pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    m_pWindow->Show();

    BOOL quit = false;
    FLOAT yRotationAngle = 0.0f;
    while (!quit)
    {
        ProcessUpdates();

        BeginFrame();

        CameraBufferData* pCameraData = NULL;

        // new frame, clear state
        pContext->ClearState();

        pContext->RSSetViewports(1, &m_pDxData->viewport);
        pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        pContext->RSSetState(pShadeRS);
        pContext->PSSetSamplers(0, 1, &pPointSampler);

        pContext->OMSetRenderTargets(1,
                                       &m_pDxData->pAppRenderTargetView,
                                       m_pDxData->pAppDepthStencilTex->GetDepthStencilView());
        pContext->ClearRenderTargetView(m_pDxData->pAppRenderTargetView, clearColor);
        pContext->ClearDepthStencilView(m_pDxData->pAppDepthStencilTex->GetDepthStencilView(),
                                          D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL,
                                          1.0,
                                          0);

        ///// Draw Mesh ///////////////////////////////////////////////////////////////////////////

        FLOAT viewRotationY = (GetMousePos().x - (m_screenWidth / 2.0f)) /(m_screenWidth / 2.0f);
        viewRotationY *= (3.14159f / 4.0f);

        FLOAT viewRotationZ = (GetMousePos().y - (m_screenHeight / 2.0f)) /(m_screenHeight / 2.0f);
        viewRotationZ *= (3.14159f / 4.0f);

        pCameraData = reinterpret_cast<CameraBufferData*>(pCameraBuffer->Map(pContext));
        pCameraData->worldMatrix = XMMatrixScaling(25, 25, 25) * XMMatrixRotationY(yRotationAngle) *
                                   XMMatrixTranslation(m_pCamera->Position().x,
                                                       m_pCamera->Position().y,
                                                       m_pCamera->Position().z) ;
        // translate world +6 in Z to position camera -9 from world origin
        pCameraData->viewMatrix = m_pCamera->W2C();
        pCameraData->projectionMatrix = m_pCamera->C2S();

        pCameraBuffer->Unmap(pContext);

        pCameraBuffer->BindVS(pContext, 0);

        pMesh->Bind(pContext);

        m_pPosTexNormVS->Bind(pContext);
        m_pCelShadePS->Bind(pContext);
        pMesh->Draw(pContext);

        ///// Detect Edges ///////////////////////////////////////////////////////////////////////////


        ///// Draw Light Position ////////////////////////////////////////////////////////////////////

        //yRotationAngle = 0;
        pCameraData = reinterpret_cast<CameraBufferData*>(pCameraBuffer->Map(pContext));
        pCameraData->worldMatrix = XMMatrixScaling(1, 1, 1);
                                 //  XMMatrixRotationY(yRotationAngle);
                                  // XMMatrixTranslation(-10, 10, 10);
        // translate world +6 in Z to position camera -9 from world origin
        pCameraData->viewMatrix = XMMatrixTranslation(0, 0, 10) * m_pCamera->W2C();
        pCameraData->projectionMatrix = m_pCamera->C2S();

        pCameraBuffer->Unmap(pContext);
        pCameraBuffer->BindVS(pContext, 0);

        pCubeVS->Bind(pContext);

        pCubePS->Bind(pContext);

        pCubeMesh->Bind(pContext);
        pCubeMesh->Draw(pContext);

        ///// Draw UI ////////////////////////////////////////////////////////////////////////////////

        ///@todo Consider moving the following UI drawing to Draw2D()
        m_pUI->Begin();
        // Draw UI stuff
        m_pUI->RenderRect();
        m_pUI->RenderText();
        m_pUI->End();

        /// Blend UI onto final image
        DrawUI();

        m_pDxData->pDXGISwapChain->Present(0,0);

        EndFrame();

        Sleep(50);
        yRotationAngle += 3.14159f / 60.0f;
    }

    // Shader Resource Views

    pCameraBuffer->Destroy();

    // Shaders
    m_pCelShadePS->Destroy();
    m_pCelShadePS = NULL;

    m_pPosTexTriVS->Destroy();
    m_pPosTexTriVS = NULL;

    m_pPosTexNormVS->Destroy();
    m_pPosTexNormVS = NULL;

    pApplyTexPS->Destroy();
    pApplyTexPS = NULL;

    pPlaneMesh->Destroy();
    pPlaneMesh = NULL;

    // Samplers
    pPointSampler->Release();

    // Rasterizer State
    pShadeRS->Release();

    m_pDxData->pD3D11Context->ClearState();
    m_pDxData->pD3D11Context->Flush(); 
}