Qt uploading texture thread - multithreading

I am using a QGLWidget for displaying a live Image Stream. Since uploading textures is an expensive operation I would like to avoid doing this on the GUI Thread. I have read here http://blog.qt.digia.com/blog/2011/06/03/threaded-opengl-in-4-8/ that it is possible to do this in from a different thread. Could anyone provide a short example how to do so? I am uncertain how to share the GL Context and how to make sure that there is no race condition.
This is what i currently have:
.h:
class ImageDisplay : public QGLWidget
{
Q_OBJECT
public:
ImageDisplay(QWidget* parent = 0);
void paintGL();
void resizeGL(int w, int h);
private:
QRectF plane;
GLuint texID;
public slots:
void sl_update(spImageHolder_t _myImageShPtr);
};
.cpp:
ImageDisplay::ImageDisplay(QWidget *parent)
: QGLWidget(parent)
, plane(QPointF(0,1),QSizeF(1,1))
{
QImage initImg(400,300,QImage::Format_Indexed8);
resize(initImg.size());
makeCurrent();
texID = bindTexture ( initImg, GL_TEXTURE_2D, GL_LUMINANCE, QGLContext::NoBindOption );
}
void ImageDisplay::paintGL()
{
makeCurrent();
drawTexture ( plane, texID, GL_TEXTURE_2D );
}
void ImageDisplay::resizeGL(int w, int h)
{
glViewport (0, 0, w, h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1,0,1,-1,1);
glMatrixMode (GL_MODELVIEW);
}
void ImageDisplay::sl_update(spImageHolder_t _myImageShPtr) //slot
{
QImage * imgPtr = _myImageShPtr->getImagePtr();
if (NULLPTR != imgPtr)
{
deleteTexture(texID);
texID = bindTexture( *imgPtr, GL_TEXTURE_2D, GL_LUMINANCE, QGLContext::NoBindOption );
}
updateGL();
}

Related

Applying a texture to a custom effect using DirectXTK results in the texture being stretched

I'm trying to apply a custom effect using the DirectXTK. The effect is supposed to be an "unlit" shader with just one texture. But for some reason, the texture is stretched across the model. I looked in renderdoc and the texturecoordinates appear to be loaded correctly so i'm not sure what's going on.
UnlitEffect.h
#pragma once
#include <vector>
class UnlitEffect : public DirectX::IEffect, public DirectX::IEffectMatrices
{
public:
explicit UnlitEffect(ID3D11Device* device);
UnlitEffect() = default;
virtual void Apply(_In_ ID3D11DeviceContext* deviceContext) override;
virtual void GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength) override;
void SetTexture(ID3D11ShaderResourceView* value);
void XM_CALLCONV SetWorld(DirectX::FXMMATRIX value) override;
void XM_CALLCONV SetView(DirectX::FXMMATRIX value) override;
void XM_CALLCONV SetProjection(DirectX::FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(DirectX::FXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection) override;
struct __declspec(align(16)) UnlitEffectConstants
{
DirectX::XMMATRIX MVP;
};
DirectX::ConstantBuffer<UnlitEffectConstants> m_constantBuffer;
protected:
Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vs;
Microsoft::WRL::ComPtr<ID3D11PixelShader> m_ps;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_texture;
std::vector<uint8_t> m_vsBlob;
DirectX::SimpleMath::Matrix m_World;
DirectX::SimpleMath::Matrix m_View;
DirectX::SimpleMath::Matrix m_Projection;
DirectX::SimpleMath::Matrix m_MVP;
uint32_t m_dirtyFlags;
};
UnlitEffect.cpp
#include "pch.h"
#include "UnlitEffect.h"
#include "ReadData.h"
namespace
{
constexpr uint32_t DirtyConstantBuffer = 0x1;
constexpr uint32_t DirtyMVPMatrix= 0x2;
}
UnlitEffect::UnlitEffect(ID3D11Device* device)
:m_constantBuffer(device),m_dirtyFlags(uint32_t(-1))
{
m_vsBlob = DX::ReadData(L"Shaders/UnlitVS.cso");
DX::ThrowIfFailed(
device->CreateVertexShader(m_vsBlob.data(), m_vsBlob.size(), nullptr, m_vs.ReleaseAndGetAddressOf())
);
auto ps_blob = DX::ReadData(L"Shaders/UnlitPS.cso");
DX::ThrowIfFailed(
device->CreatePixelShader(ps_blob.data(), ps_blob.size(), nullptr, m_ps.ReleaseAndGetAddressOf())
);
}
void UnlitEffect::Apply(_In_ ID3D11DeviceContext* deviceContext)
{
if(m_dirtyFlags & DirtyMVPMatrix)
{
m_MVP = m_World * m_View;
m_MVP = m_MVP * m_Projection;
m_dirtyFlags &= ~DirtyMVPMatrix;
m_dirtyFlags |= DirtyConstantBuffer;
}
if(m_dirtyFlags & DirtyConstantBuffer)
{
UnlitEffectConstants constants;
constants.MVP = m_MVP.Transpose();
m_constantBuffer.SetData(deviceContext, constants);
m_dirtyFlags &= ~DirtyConstantBuffer;
}
auto cb = m_constantBuffer.GetBuffer();
deviceContext->VSSetConstantBuffers(0, 1, &cb);
deviceContext->PSSetShaderResources(0, 1, m_texture.GetAddressOf());
deviceContext->VSSetShader(m_vs.Get(), nullptr, 0);
deviceContext->PSSetShader(m_ps.Get(), nullptr, 0);
}
void UnlitEffect::GetVertexShaderBytecode(_Out_ void const** pShaderByteCode, _Out_ size_t* pByteCodeLength)
{
assert(pShaderByteCode != nullptr && pByteCodeLength != nullptr);
*pShaderByteCode = m_vsBlob.data();
*pByteCodeLength = m_vsBlob.size();
}
void UnlitEffect::SetTexture(ID3D11ShaderResourceView* value)
{
m_texture = value;
}
void XM_CALLCONV UnlitEffect::SetWorld(DirectX::FXMMATRIX value)
{
m_World = value;
m_dirtyFlags |= DirtyMVPMatrix;
}
void XM_CALLCONV UnlitEffect::SetView(DirectX::FXMMATRIX value)
{
m_View = value;
m_dirtyFlags |= DirtyMVPMatrix;
}
void XM_CALLCONV UnlitEffect::SetProjection(DirectX::FXMMATRIX value)
{
m_Projection = value;
m_dirtyFlags |= DirtyMVPMatrix;
}
void XM_CALLCONV UnlitEffect::SetMatrices(DirectX::FXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX projection)
{
m_View = view;
m_World = world;
m_Projection = projection;
m_dirtyFlags |= DirtyMVPMatrix;
}
Unlit.hlsli
#ifndef __UNLINT_HLSLI__
#define __UNLINT_HLSLI__
cbuffer UnlitConstants : register(b0)
{
float4x4 MVP;
}
struct VSOutput
{
float4 PositionPS : SV_Position;
float2 TexCoord : TEXCOORD0;
};
struct VSInput
{
float4 Position : SV_Position;
float2 TexCoord : TEXCOORD0;
};
#endif
UnlitPS.hlsl
#include "Unlit.hlsli"
Texture2D BaseColor : register(t0);
SamplerState SampleType : register(s0);
float4 main(VSOutput vout) : SV_TARGET0
{
return BaseColor.Sample(SampleType, normalize(vout.TexCoord));
}
UnlitVS.hlsl
#include "Unlit.hlsli"
VSOutput main(VSInput vin)
{
VSOutput vout;
vout.PositionPS = mul(vin.Position, MVP);
vout.TexCoord = vin.TexCoord;
return vout;
}
here is the result
Chuck Walbourn was correct. My issue was that I was normalizing my texture coordinates in the pixel shader.
The correct code is
return BaseColor.Sample(SampleType, vout.TexCoord);

'player' : unknown override specifier

Why isn't my code working??? What does this error mean? FYI: I wanted to create a top down shooter game. all my code was basically just copied from different sources(some I just solved on my own).
I intended to put the player class in the game loop or game class. here's the code:
game.cpp
#include "Player.h"
//Private Functions
void game::intVariables()
{
this->window = nullptr;
this->points = 0;
this->enemySpawnTimerMax = 1000.f;
this->enemySpawnTimer = this->enemySpawnTimerMax;
this->maxEnemies = 8;
}
void game::intWindow()
{
this->videoMode.height = 1080;
this->videoMode.width = 1780;
this->window = new sf::RenderWindow(this->videoMode, "Top Down Shooter", sf::Style::Close | sf::Style::Titlebar);
this->window->setFramerateLimit(60);
this->window->setKeyRepeatEnabled(true);
Player player("player.png");
}
void game::intEnemies()
{
this->enemy.setPosition(30.f, 30.f);
this->enemy.setSize(sf::Vector2f(50.f, 50.f));
this->enemy.setFillColor(sf::Color(0, 128, 128));
this->enemy.setOutlineColor(sf::Color::Black);
this->enemy.setOutlineThickness(-4.f);
}
//Constructors or Destructors
game::game()
{
this->intVariables();
this->intWindow();
this->intEnemies();
}
//prevents memory leak
game::~game()
{
delete this->window;
}
//Accessors
const bool game::running() const
{
return this->window->isOpen();
}
//functions
void game::player1()
{
player.drawPlayer(*this->window);
}
void game::spawnEnemy()
{
/*
#return void
Spawns enemies and sets their color and positions.
- select random position
- select random color
- add enemy to vector
*/
this->enemy.setPosition(
static_cast<float>(rand() % static_cast<int>(this->window->getSize().x - this->enemy.getSize().x)),
static_cast<float>(rand() % static_cast<int>(this->window->getSize().y - this->enemy.getSize().y))
);
this->enemy.setFillColor(sf::Color(0, 128, 128));
//spawns the enemy
this->enemies.push_back(this->enemy);
}
void game::pollEvents()
{
//event polling
while (this->window->pollEvent(this->evnt))
{
switch (this->evnt.type)
{
case sf::Event::Closed:
this->window->close();
break;
case sf::Event::KeyPressed:
if (this->evnt.key.code == sf::Keyboard::Escape)
this->window->close();
break;
}
}
}
void game::updateEnemies()
{
/*
#return void
updates the enemy spawn timer and spawns enemies
when the total amount of enemies is smaller than the maximum.
removes the enemies at the edge of the screen. //to do
*/
//Updating the timer for enemy spawning
if (this->enemies.size() < this->maxEnemies)
{
if (this->enemySpawnTimer >= this->enemySpawnTimerMax)
{
//spawn the enemy and reset the timer
this->spawnEnemy();
this->enemySpawnTimer = 0.f;
}
else
this->enemySpawnTimer += 1.f;
}
// Move the enemies
for (auto &e : this->enemies)
{
e.move(0.f, 1.f);
}
}
void game::update()
{
this->pollEvents();
this->updateMousePositions();
this->updateEnemies();
}
void game::renderEnemies()
{
for (auto &e : this->enemies)
{
this->window->draw(e);
}
}
void game::render()
{
/*
- clears old frame
- renders objects
- display frames on window
renders game objects.
*/
this->window->clear(sf::Color(128, 128, 128));
//draw game objects
this->renderEnemies();
this->player1();
this->window->display();
}
void game::updateMousePositions()
{
/*
#return void
updates the mouse position
*mouse postion relative to window (vector2i)*
*/
this->mousePosWindow = sf::Mouse::getPosition(*this->window);
}
game.h
#include <iostream>
#include <vector>
#include <ctime>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
/* class acts as the game engine
wrapper class.
*/
class game
{
protected:
//variables
//window
sf::RenderWindow* window;
sf::VideoMode videoMode;
sf::Event evnt;
//mouse positions
sf::Vector2i mousePosWindow;
//game logic
int points;
float enemySpawnTimer;
float enemySpawnTimerMax;
int maxEnemies;
//game objects
std::vector<sf::RectangleShape> enemies;
sf::RectangleShape enemy;
Player player;
// Private Functions
void intVariables();
void intWindow();
void intEnemies();
public:
// Constructors or Destructors
game();
virtual ~game();
// Accessors
const bool running() const;
// Functions
void player1();
void spawnEnemy();
void pollEvents();
void updateEnemies();
void update();
void renderEnemies();
void render();
void updateMousePositions();
};
Player.h
#include <iostream>
#include <SFML/Graphics.hpp>
#include "game.h"
class Player
{
public:
Player() {
//default
}
Player(std::string imgDirectory) {
if (!playerTexture.loadFromFile(imgDirectory)) {
std::cerr << "Error\n";
}
playerSprite.setTexture(playerTexture);
}
void drawPlayer(sf::RenderWindow& window) {
window.draw(playerSprite);
}
void movePlayer(char direction, float moveSpeed) {
if (direction == 'u')
{
playerSprite.move(0, -moveSpeed);
}
else if (direction == 'd')
{
playerSprite.move(0, -moveSpeed);
}
else if (direction == 'l')
{
playerSprite.move(-moveSpeed, 0);
}
else if (direction == 'r')
{
playerSprite.move(moveSpeed, 0);
}
}
private:
sf::Texture playerTexture;
sf::Sprite playerSprite;
};

How to change the background properties of an mfc application

CURRENT UI
NEW UI
I want to change the background color of a button in MFC application. I have created my user interface(UI) in MFC .I have added every controls from the toolbox.But the problem is that i want to change the background and foreground properties of a button and window.How it is possible?
please help me to change the properties of controls in MFC.In windows application we can directly change the properties in the property window.
But in the case of MFC application that is not possible.
please help me..i have not enough experience in MFC application development.....
Thanks in advance......................
code from dialer.h
class CButtonDialer : public CButton
{
// Construction
public:
CButtonDialer();
// Attributes
public:
CButton m_button;
// CButton IDC_KEY_1;
CBrush m_brush;
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CButtonDialer)
public:
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
// Implementation
public:
virtual ~CButtonDialer();
// Generated message map functions
protected:
//{{AFX_MSG(CButtonDialer)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
CFont m_FontLetters;
CMapStringToString m_map;
HTHEME m_hTheme;
void OpenTheme() { m_hTheme = OpenThemeData(m_hWnd, L"Button"); }
void CloseTheme() {
if (m_hTheme) { CloseThemeData(m_hTheme); m_hTheme = NULL; }
}
DECLARE_MESSAGE_MAP()
virtual void PreSubclassWindow();
afx_msg LRESULT OnThemeChanged();
afx_msg void OnMouseMove(UINT,CPoint);
afx_msg void OnSize(UINT type, int w, int h);
};
code from dialer.cpp file
#include "stdafx.h"
#include "ButtonDialer.h"
#include "Strsafe.h"
#include "const.h"
/////////////////////////////////////////////////////////////////////////////
// CButtonDialer
CButtonDialer::CButtonDialer()
{
//255,255,255
m_brush.CreateSolidBrush(
(173, 41, 41));
m_map.SetAt(_T("1"),_T(""));
m_map.SetAt(_T("2"),_T("ABC"));
m_map.SetAt(_T("3"),_T("DEF"));
m_map.SetAt(_T("4"),_T("GHI"));
m_map.SetAt(_T("5"),_T("JKL"));
m_map.SetAt(_T("6"),_T("MNO"));
m_map.SetAt(_T("7"),_T("PQRS"));
m_map.SetAt(_T("8"),_T("TUV"));
m_map.SetAt(_T("9"),_T("WXYZ"));
m_map.SetAt(_T("0"),_T(""));
m_map.SetAt(_T("*"),_T(""));
m_map.SetAt(_T("#"),_T(""));
}
CButtonDialer::~CButtonDialer()
{
CloseTheme();
}
BEGIN_MESSAGE_MAP(CButtonDialer, CButton)
ON_WM_THEMECHANGED()
ON_WM_MOUSEMOVE()
ON_WM_SIZE()
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CButtonDialer message handlers
void CButtonDialer::PreSubclassWindow()
{
OpenTheme();
HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
LOGFONT lf;
GetObject(hFont, sizeof(LOGFONT), &lf);
lf.lfHeight = 14;
StringCchCopy(lf.lfFaceName,LF_FACESIZE,_T("Microsoft Sans Serif"));
m_FontLetters.CreateFontIndirect(&lf);
DWORD dwStyle = ::GetClassLong(m_hWnd, GCL_STYLE);
dwStyle &= ~CS_DBLCLKS;
::SetClassLong(m_hWnd, GCL_STYLE, dwStyle);
}
LRESULT CButtonDialer::OnThemeChanged()
{
CloseTheme();
OpenTheme();
return 0L;
}
void CButtonDialer::OnSize(UINT type, int w, int h)
{
CButton::OnSize(type, w, h);
}
void CButtonDialer::OnMouseMove(UINT nFlags,CPoint point)
{
CRect rect;
GetClientRect(&rect);
if (rect.PtInRect(point)) {
if (GetCapture() != this) {
SetCapture();
Invalidate();
}
}
else {
ReleaseCapture();
Invalidate();
}
CButton::OnMouseMove(nFlags, point);
}
void CButtonDialer::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
CDC dc;
dc.Attach(lpDrawItemStruct->hDC); //Get device context object
CRect rt;
rt = lpDrawItemStruct->rcItem; //Get button rect
dc.FillSolidRect(rt,dc.GetBkColor());
dc.SetBkMode(TRANSPARENT);
CRect rtl = rt;
UINT state = lpDrawItemStruct->itemState; //Get state of the button
if (!m_hTheme) {
UINT uStyle = DFCS_BUTTONPUSH;
if ( (state & ODS_SELECTED) ) {
uStyle |= DFCS_PUSHED;
rtl.left+=1;
rtl.top+=1;
}
dc.DrawFrameControl(rt, DFC_BUTTON, uStyle);
} else {
UINT uStyleTheme = RBS_NORMAL;
if ( (state & ODS_SELECTED) ) {
uStyleTheme = PBS_PRESSED;
} else if (GetCapture()==this) {
uStyleTheme = PBS_HOT;
}
DrawThemeBackground(m_hTheme, dc.m_hDC,
BP_PUSHBUTTON, uStyleTheme,
rt, NULL);
}
CString strTemp;
GetWindowText(strTemp); // Get the caption which have been set
rtl.top += 4;
CString letters;
COLORREF crOldColor;
if (m_map.Lookup(strTemp,letters)) {
rtl.left+=15;
dc.DrawText(strTemp,rtl,DT_LEFT|DT_TOP|DT_SINGLELINE); // Draw out the caption
HFONT hOldFont = (HFONT)SelectObject(dc.m_hDC, m_FontLetters);
// Do your text drawing
rtl.left += 13;
rtl.top += 4;
rtl.right -=4;
crOldColor = dc.SetTextColor(RGB(148, 167, 70));
dc.DrawText(letters,rtl,DT_LEFT | DT_TOP | DT_SINGLELINE);
dc.SetTextColor(crOldColor);
// Always select the old font back into the DC
SelectObject(dc.m_hDC, hOldFont);
} else {
//127,127,127
crOldColor = dc.SetTextColor(RGB(148, 167, 70));
dc.DrawText(strTemp,rtl,DT_CENTER|DT_TOP|DT_SINGLELINE); // Draw out the caption
dc.SetTextColor(crOldColor);
}
if ( (state & ODS_FOCUS ) ) // If the button is focused
{
int iChange = 3;
rt.top += iChange;
rt.left += iChange;
rt.right -= iChange;
rt.bottom -= iChange;
dc.DrawFocusRect(rt);
}
dc.Detach();
}
BOOL CButtonDialer::OnEraseBkgnd(CDC* pDC)
{
CRect rect;
GetClientRect(&rect);
//255,255,255
CBrush myBrush(RGB(173, 41, 41)); // dialog background color
CBrush *pOld = pDC->SelectObject(&myBrush);
BOOL bRes = pDC->PatBlt(0, 0, rect.Width(), rect.Height(), PATCOPY);
pDC->SelectObject(pOld); // restore old brush
return bRes; // CDialog::OnEraseBkgnd(pDC);
}
You need to provide a message handler for the WM_ERASEBKGND message and paint the background yourself.
Put a normal button on the Resource Editor.
On the .h file of the form where you use it, declare a CMFCButton variable like m_btnRead.
In the DoDataExchange method of your form append a line
DDX_Control(pDX, IDC_BUTTON_READ, m_btnRead);
On the method where you initialize your form (OnInitDialog, Create, etc.) append a line
m_btnRead.SetFaceColor(RGB(0, 255, 255));
and now you are done!

Does anyone know of a low level (no frameworks) example of a drag & drop, re-order-able list?

I am looking for code (any language) of a basic graphical list which can be reordered by drag and drop. So exactly this functionality http://jqueryui.com/sortable/ but written directly on the frame buffer/canvas without any frameworks (or low level 'put pixel' libraries at most) and probably not in HTML/JS (unless it's Canvas only without CSS).
The simpler the better as I will be using it in assembler and I don't want to reinvent the wheel if not needed.
heh I hate frameworks so this is easy as pie for me...
this is what I coded for my students during my lectures few years back:
http://ulozto.net/x2b7WLwJ/select-drag-drop-zip
This is the main engine code (complete project + exe is in that zip above):
//---------------------------------------------------------------------------
//--- Constants: ------------------------------------------------------------
//---------------------------------------------------------------------------
const int _select_max_l=16;
const int _select_max_ll=_select_max_l*_select_max_l;
const int _half_size=10;
const int _atoms_max=32;
//---------------------------------------------------------------------------
enum _atom_type_enum //++++
{
_atom_type_non=0,
_atom_type_kruh,
_atom_type_stvorec,
_atom_type_enum_end
};
//---------------------------------------------------------------------------
enum _editor_edit_mode_enum //****
{
_editor_edit_mode_non=0,
_editor_edit_mode_move,
_editor_edit_mode_mov,
_editor_edit_mode_add_kruh,
_editor_edit_mode_add_stvorec,
_editor_edit_mode_del,
_editor_edit_mode_enum_end
};
//---------------------------------------------------------------------------
//--- viewer: ---------------------------------------------------------------
//---------------------------------------------------------------------------
class viewer
{
public: int x0,y0;
viewer() { x0=0; y0=0; }
void world2screen(int &sx,int &sy,int wx,int wy) { sx=wx-x0; sy=wy-y0; }
void screen2world(int &wx,int &wy,int sx,int sy) { wx=sx+x0; wy=sy+y0; }
void world2screen(int &sl,int wl) { sl=wl; }
void screen2world(int &wl,int sl) { wl=sl; }
};
//---------------------------------------------------------------------------
//--- atom kruh: ------------------------------------------------------------
//---------------------------------------------------------------------------
class atom_kruh
{
public: int x,y,r; // world coordinates
TColor col0,col1,col2;
AnsiString str;
atom_kruh() { x=0; y=0; r=_half_size; str=""; col0=clBlue; col1=clAqua; col2=clWhite; }
void draw(TCanvas *scr,const viewer &view)
{
int xx,yy,rr;
view.world2screen(xx,yy,x,y);
view.world2screen(rr,r);
scr->Brush->Color=col0;
scr->Pen ->Color=col1;
scr->Font ->Color=col2;
scr->Ellipse(xx-rr,yy-rr,xx+rr,yy+rr);
scr->Brush->Style=bsClear;
xx-=scr->TextWidth(str)>>1;
yy-=scr->TextHeight(str)>>1;
scr->TextOutA(xx,yy,str);
scr->Brush->Style=bsSolid;
}
bool select(int &ll,int wx,int wy)
{
int qq,xx,yy;
xx=wx-x; xx*=xx;
yy=wy-y; yy*=yy;
qq=xx+yy;
if ((qq<=_select_max_ll)&&((qq<=ll)||(ll<0))) { ll=qq; return true; }
return false;
}
};
//---------------------------------------------------------------------------
//--- atom kruh: ------------------------------------------------------------
//---------------------------------------------------------------------------
class atom_stvorec
{
public: int x,y,r; // world coordinates
TColor col0,col1,col2;
AnsiString str;
atom_stvorec() { x=0; y=0; r=_half_size; str=""; col0=clBlue; col1=clAqua; col2=clWhite; }
void draw(TCanvas *scr,const viewer &view)
{
int xx,yy,rr;
view.world2screen(xx,yy,x,y);
view.world2screen(rr,r);
scr->Brush->Color=col0;
scr->Pen ->Color=col1;
scr->Font ->Color=col2;
scr->Rectangle(xx-rr,yy-rr,xx+rr,yy+rr);
scr->Brush->Style=bsClear;
xx-=scr->TextWidth(str)>>1;
yy-=scr->TextHeight(str)>>1;
scr->TextOutA(xx,yy,str);
scr->Brush->Style=bsSolid;
}
bool select(int &ll,int wx,int wy)
{
int qq,xx,yy;
xx=wx-x; xx*=xx;
yy=wy-y; yy*=yy;
qq=xx+yy;
if ((qq<=_select_max_ll)&&((qq<=ll)||(ll<0))) { ll=qq; return true; }
return false;
}
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class editor
{
public: Graphics::TBitmap *bmp; // back buffer
int xs,ys;
int sel_ix,sel_tp; // actual mouse selected item
int edit_mode; // selected edit tool
viewer view; // view
bool redraw; // redraw needed?
bool locked; // edit in progress?
WORD key,key0;
int mx,my,mx0,my0;
TShiftState sh,sh0;
atom_kruh kruh[_atoms_max]; // all object lists
atom_stvorec stvorec[_atoms_max];
int kruhov;
int stvorcov;
editor();
~editor();
void resize(int _xs,int _ys); // interface with window
void draw();
void mouse(int x,int y,TShiftState s) { mx0=mx; my0=my; sh0=sh; mx=x; my=y; sh=s; edit(); }
void keys(WORD k,TShiftState s) { key0=key; sh0=sh; key=k; sh=s; edit(); }
void select(); // helper functions
void edit();
void move (bool q0,bool q1,int x,int y,int dx,int dy);
void mov (bool q0,bool q1,int x,int y,int dx,int dy);
void add_kruh (bool q0,bool q1,int x,int y,int dx,int dy);
void add_stvorec(bool q0,bool q1,int x,int y,int dx,int dy);
void del (bool q0,bool q1,int x,int y,int dx,int dy);
};
//---------------------------------------------------------------------------
editor::editor()
{
bmp=new Graphics::TBitmap;
resize(1,1);
sel_ix=-1;
sel_tp=_atom_type_non;
edit_mode=_editor_edit_mode_non;
key=0; key0=0;
mx=0; mx0=0;
my=0; my0=0;
locked=false;
kruhov=0;
stvorcov=0;
}
//---------------------------------------------------------------------------
editor::~editor()
{
delete bmp;
}
//---------------------------------------------------------------------------
void editor::resize(int _xs,int _ys)
{
bmp->Width=_xs;
bmp->Height=_ys;
xs=bmp->Width;
ys=bmp->Height;
redraw=true;
}
//---------------------------------------------------------------------------
void editor::draw()
{
int i;
if (!redraw) return;
redraw=false;
bmp->Canvas->Brush->Color=clBlack;
bmp->Canvas->FillRect(Rect(0,0,xs,ys));
//++++
for (i=0;i<kruhov ;i++) kruh[i] .draw(bmp->Canvas,view);
for (i=0;i<stvorcov;i++) stvorec[i].draw(bmp->Canvas,view);
}
//---------------------------------------------------------------------------
void editor::select()
{
int i,wx,wy,ll;
int sel_tp0=sel_tp; sel_tp=_atom_type_non;
int sel_ix0=sel_ix; sel_ix=-1;
view.screen2world(wx,wy,mx,my);
//++++
ll=-1;
for (i=0;i<kruhov ;i++) if (kruh[i] .select(ll,wx,wy)) { sel_tp=_atom_type_kruh; sel_ix=i; };
for (i=0;i<stvorcov;i++) if (stvorec[i].select(ll,wx,wy)) { sel_tp=_atom_type_stvorec; sel_ix=i; };
if (sel_tp!=sel_tp0) redraw=true;
if (sel_ix!=sel_ix0) redraw=true;
}
//---------------------------------------------------------------------------
void editor::edit()
{
bool q0,q1;
int x,y,dx,dy;
x=mx; dx=mx-mx0;
y=my; dy=my-my0;
view.screen2world( x, y, x, y);
view.screen2world(dx,dx);
view.screen2world(dy,dy);
q0=sh0.Contains(ssLeft);
q1=sh .Contains(ssLeft);
if (!locked) select();
//****
if(edit_mode==_editor_edit_mode_mov) mov (q0,q1,x,y,dx,dy);
if(edit_mode==_editor_edit_mode_add_kruh) add_kruh (q0,q1,x,y,dx,dy);
if(edit_mode==_editor_edit_mode_add_stvorec)add_stvorec (q0,q1,x,y,dx,dy);
if(edit_mode==_editor_edit_mode_del) del (q0,q1,x,y,dx,dy);
q0=sh0.Contains(ssRight);
q1=sh .Contains(ssRight);
if (!locked) move(q0,q1,x,y,dx,dy);
}
//---------------------------------------------------------------------------
void editor::move (bool q0,bool q1,int x,int y,int dx,int dy)
{
if ((sel_ix>=0)&&(sel_tp!=_atom_type_non)) return;
if (q1)
{
view.x0-=dx;
view.y0-=dy;
redraw=true;
}
}
//---------------------------------------------------------------------------
void editor::mov (bool q0,bool q1,int x,int y,int dx,int dy)
{
if ((!locked)&&((sel_ix<0)||(sel_tp==_atom_type_non))) return;
locked=false;
if ((q1)||((q0)&&(!q1)))
{
//++++
if (sel_tp==_atom_type_kruh)
{
kruh[sel_ix].x=x;
kruh[sel_ix].y=y;
}
if (sel_tp==_atom_type_stvorec)
{
stvorec[sel_ix].x=x;
stvorec[sel_ix].y=y;
}
locked=true;
}
if (!q1) locked=false;
redraw=true;
}
//---------------------------------------------------------------------------
void editor::add_kruh (bool q0,bool q1,int x,int y,int dx,int dy)
{
if ((!locked)&&(sel_ix>=0)&&(sel_tp!=_atom_type_non)) return;
locked=false;
if (kruhov>=_atoms_max) return;
if ((!q0)&&( q1))
{
sel_tp=_atom_type_kruh;
sel_ix=kruhov;
kruhov++;
kruh[sel_ix].x=x;
kruh[sel_ix].y=y;
kruh[sel_ix].str=kruhov;
locked=true;
}
if (( q0)&&( q1))
{
kruh[sel_ix].x=x;
kruh[sel_ix].y=y;
locked=true;
}
if (( q0)&&(!q1))
{
kruh[sel_ix].x=x;
kruh[sel_ix].y=y;
}
if ((!q0)&&(!q1))
{
}
redraw=true;
}
//---------------------------------------------------------------------------
void editor::add_stvorec(bool q0,bool q1,int x,int y,int dx,int dy)
{
if ((!locked)&&(sel_ix>=0)&&(sel_tp!=_atom_type_non)) return;
locked=false;
if (stvorcov>=_atoms_max) return;
if ((!q0)&&( q1))
{
sel_tp=_atom_type_stvorec;
sel_ix=stvorcov;
stvorcov++;
stvorec[sel_ix].x=x;
stvorec[sel_ix].y=y;
stvorec[sel_ix].str=stvorcov;
locked=true;
}
if (( q0)&&( q1))
{
stvorec[sel_ix].x=x;
stvorec[sel_ix].y=y;
locked=true;
}
if (( q0)&&(!q1))
{
stvorec[sel_ix].x=x;
stvorec[sel_ix].y=y;
}
if ((!q0)&&(!q1))
{
}
redraw=true;
}
//---------------------------------------------------------------------------
void editor::del (bool q0,bool q1,int x,int y,int dx,int dy)
{
locked=false;
if ((sel_ix<0)||(sel_tp==_atom_type_non)) return;
if ((!q0)&&( q1))
{
//++++
if (sel_tp==_atom_type_kruh)
if (kruhov>0)
{
kruhov--;
kruh[sel_ix]=kruh[kruhov];
}
if (sel_tp==_atom_type_stvorec)
if (stvorcov>0)
{
stvorcov--;
stvorec[sel_ix]=stvorec[stvorcov];
}
sel_ix=-1;
sel_tp=_atom_type_non;
}
redraw=true;
}
//---------------------------------------------------------------------------
sorry for that its not entirely in English
kruh means circle
stvorec means square
This is code for window (BDS2006 VCL style)
//$$---- Form CPP ----
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "editor.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
editor edit;
int x0,y0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void draw() // redraw app screen
{
edit.draw();
Form1->Canvas->Draw(x0,y0,edit.bmp);
// here just some info print outs
int dy=16,x=x0,y=y0-dy;
Form1->Canvas->Font->Color=clAqua;
Form1->Canvas->Brush->Style=bsClear;
Form1->Canvas->TextOutA(x,y+=dy,AnsiString().sprintf("locked: %i",edit.locked));
Form1->Canvas->TextOutA(x,y+=dy,AnsiString().sprintf("Key: %d",edit.key));
Form1->Canvas->TextOutA(x,y+=dy,AnsiString().sprintf("sel_tp: %i",edit.sel_tp));
Form1->Canvas->TextOutA(x,y+=dy,AnsiString().sprintf("sel_ix: %i",edit.sel_ix));
Form1->Canvas->TextOutA(x,y+=dy,AnsiString().sprintf("kruhov: %i",edit.kruhov));
Form1->Canvas->TextOutA(x,y+=dy,AnsiString().sprintf("stvorcov: %i",edit.stvorcov));
Form1->Canvas->Brush->Style=bsSolid;
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner):TForm(Owner) // init app
{
// select tool on app start
bt_tool_kruhClick(this);
}
//--- window events: ---------------------------------------------------------
void __fastcall TForm1::FormPaint(TObject *Sender) { draw(); }
void __fastcall TForm1::FormResize(TObject *Sender) { x0=pan_top->Left; y0=pan_top->Height; edit.resize(ClientWidth-x0,ClientHeight-y0); draw(); }
void __fastcall TForm1::FormActivate(TObject *Sender) { draw(); }
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift) { edit.keys(Key,Shift); draw(); }
void __fastcall TForm1::FormMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { edit.mouse(X-x0,Y-y0,Shift); draw(); }
void __fastcall TForm1::FormMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y){ edit.mouse(X-x0,Y-y0,Shift); draw(); }
void __fastcall TForm1::FormMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { edit.mouse(X-x0,Y-y0,Shift); draw(); }
//---------------------------------------------------------------------------
void __fastcall TForm1::bt_tool_kruhClick(TObject *Sender) // event on any tool button click
{
// select editor tool mode ...
edit.edit_mode=_editor_edit_mode_non;
if (bt_tool_kruh ->Down) edit.edit_mode=_editor_edit_mode_add_kruh;
if (bt_tool_stvorec->Down) edit.edit_mode=_editor_edit_mode_add_stvorec;
if (bt_tool_move ->Down) edit.edit_mode=_editor_edit_mode_mov;
if (bt_tool_delete ->Down) edit.edit_mode=_editor_edit_mode_del;
}
//---------------------------------------------------------------------------
Window has only 4 tool buttons (locked together by same guid so only one can be down at a time)
add circle tool
add square tool
move tool
delete tool
Everything is statically allocated for simplicity
[edit1] more info
create gfx object data type/class (atom_xxxx)
it should hold the size,position,shape of visual gfx representation of object. Add connection variables (object type and object index to what it should be connected). Add the real object/data inside
object ID
I am using int tp,ix;
tp means type of object
ix means index in list of object of type tp
editor engine
this should be also class or set of variables and functions. It should hold the whole edited world (lists of objects):
visualization variables like screen/backbufer bitmap or rendering context, mouse position, selection list
add functions/events like onmouse, onkey, draw,...
add edit function it should be able to select,add,del,move (drag&drop) objects. Ideally controlled by set of command to ease up the undo/redo operation
add undo/redo
add save,load
add your desired simulation functionality
and that is all if I did not forgot something.
create Application GUI interface
so create window, add panel with buttons for each tool,menu and whatever you need. Add events for mouse,keyboard,repaint,resize,drag&drop,... My example looks like this:
Add editor edit; to it globally or as a member of it. Member option is better if you want to have MDI later. Add events interface between edit and window (the second source code).
[Notes]
++++ marks part of code where you need add changes if any atom type is added to the system
**** marks part of code where you need add changes if any edit mode is added to the system
Sorry for not add more commented code if you need clarify something comment me.
Hope it helps a little ...

VC++ does not show output

I am new to VC++ and its been a few times now, and this is the third program that does not give output even after it is build succesfully.
#include <AFXWIN.H>
#include <math.h>
#define PI 3.1415926
#define SEGMENTS 500
class CMyApp : public CWinApp {
public:
virtual BOOL InitInstance();
};
class CMainWindow : public CFrameWnd
{
public:
CMainWindow();
protected:
afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT, CPoint);
DECLARE_MESSAGE_MAP();
};
CMyApp myAPP;
BOOL CMyApp::InitInstance() {
m_pMainWnd = new CMainWindow;
m_pMainWnd->ShowWindow(SW_MAXIMIZE);
m_pMainWnd->UpdateWindow();
return TRUE;
}
BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
ON_WM_PAINT ()
END_MESSAGE_MAP ()
CMainWindow::CMainWindow() {
Create(NULL,"The Hello Application",WS_OVERLAPPEDWINDOW);
}
void CMainWindow::OnPaint() {
CRect rect;
int nWidth = rect.Width();
int nHeight = rect.Height();
CPaintDC dc (this);
CPoint aPoint[SEGMENTS];
for (int i =0; i < SEGMENTS; i++){
aPoint[i].x = ((i*nWidth)/SEGMENTS );
aPoint[i].y= (int)((nHeight/2)* (1-(sin((2*PI*i)/SEGMENTS))));
}
dc.Polyline(aPoint, SEGMENTS);
UpdateData(false);
}
The above program should give Sine curve as the output, except that I get a blank window. And I don't know why does it happen. If it helps, I am using VC++ 6.0
The problem is probably that the rectangle you use to get the width and height is not initialized. You have to get the rectangle from somewhere, see e.g. CWnd::GetClientRect.

Resources