Clearing the stm32f4-discovery flash programatically - c++

I'm having a problem clearing the stm32f429 discovery board flash after creating a window using stemwin library. If I use the code below, flash will be cleared correctly:
EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3;
EraseInitStruct.Sector = FLASH_SECTOR_22;
EraseInitStruct.NbSectors = 1;
HAL_FLASH_Unlock();
uint32_t sectorError = 0;
if(HAL_FLASHEx_Erase(&EraseInitStruct,&sectorError)!=HAL_OK)
{
return HAL_FLASH_GetError();
}
HAL_FLASH_Lock();
CreateWindow();
But if I bring the CreateWindow() function to top of the code, flash will not be cleared. Here is CreateWindow() function:
WM_HWIN CreateWindow(void)
{
hWin = GUI_CreateDialogBox(_aDialogCreate, GUI_COUNTOF(_aDialogCreate), _cbDialog, WM_HBKWIN, 0, 0);
hMultiPage = MULTIPAGE_CreateEx(0, -20, 320, 260, WM_GetClientWindow(hWin), WM_CF_SHOW, 0, 0);
MULTIPAGE_SetSkin(hMultiPage,MULTIPAGE_SKIN_FLEX);
hPage1 = GUI_CreateDialogBox(_aDialogCreate2, GUI_COUNTOF(_aDialogCreate2), _cbDialogPage1, WM_UNATTACHED, 0, 0);
MULTIPAGE_AddPage(hMultiPage, hPage1, "Settings");
hPage2 = GUI_CreateDialogBox(_aDialogCreate3, GUI_COUNTOF(_aDialogCreate3), _cbDialogPage2, WM_UNATTACHED, 0, 0);
MULTIPAGE_AddPage(hMultiPage, hPage2, "Run");
MULTIPAGE_SelectPage(hMultiPage,0);
return hWin;
}

These 2 things has nothing to do between.
There could be a problem, however, that you want to delete sector where data are located (maybe images or similar) for your GUI.
Technically, there is no other option here.
Also, check which value "SectorError" variables has after function completes?

Related

How to get the IDWriteFont object from the font file downloaded in windows OS and not installed yet

Hi I am using DWrite APIs to get the system fonts metadata using DWrite APIs. I am doing the following.
HR(DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown **>(&factory)));
// Get the system font collection.
IDWriteFontCollection *collection = NULL;
HR(factory->GetSystemFontCollection(&collection, TRUE));
// Get the number of font families in the collection.
int familyCount = collection->GetFontFamilyCount();
// track unique font Ids we've already added
// using a set so we don't get any duplicates.
for (int i = 0; i < familyCount; i++)
{
IDWriteFontFamily *family = NULL;
// Get the font family.
HR(collection->GetFontFamily(i, &family));
int fontCount = family->GetFontCount();
for (int j = 0; j < fontCount; j++)
{
IDWriteFont *font = NULL;
HR(family->GetFont(j, &font));
fontMetaDataPtr* result = resultFromFont(font);
}
}
This will give me the information of the all the installed fonts. Now I need to get the information for the new fonts which I have downloaded, but there is no API in DWrite in which I can get IDWriteFont *font Object using font file path ex. "C:\Downloads\Fonts.ttf"
Can you share any working example for this.
I tried following code but it didn't work as it looks like font installing temporary not updating the collection.
int result = AddFontResourceW(wideFontFilePath.c_str());
if (result > 0) {
IDWriteFactory *factory = NULL;
HR(DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown **>(&factory)));
// Get the system font collection.
IDWriteFontCollection *collection = NULL;
HR(factory->GetSystemFontCollection(&collection, TRUE));
IDWriteFontFile *fontFile = NULL;
// Get the system font collection.
HR(factory->CreateFontFileReference(utf8ToUtf16(fontfile.c_str()), NULL, &fontFile));
if (fontFile) {
BOOL isSupported;
DWRITE_FONT_FILE_TYPE fileType;
DWRITE_FONT_FACE_TYPE fontFaceType;
UINT32 numFaces;
IDWriteFontFace* fontFace = NULL;
fontFile->Analyze(&isSupported, &fileType, &fontFaceType, &numFaces);
factory->CreateFontFace(fontFaceType, 1, &fontFile, 0, DWRITE_FONT_SIMULATIONS_NONE, &fontFace);
IDWriteFont *font = NULL;
collection->GetFontFromFontFace(fontFace, &font);
fontMetaDataPtr* result = resultFromFont(font);
}
}
result = RemoveFontResourceW(wideFontFilePath.c_str());
I found a work around for this problem
HR(DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory3),
reinterpret_cast<IUnknown **>(&factory)));
HR(factory->CreateFontSetBuilder(&fontSetBuilder));
HR(factory->CreateFontFileReference(utf8ToUtf16(fontFilePath.c_str()), NULL, &fontFile));
if (fontFile) {
fontFile->Analyze(&isSupported, &fileType, &fontFaceType, &numberOfFonts);
// If there are more than 1 fonts are there, then we are taking only first index of the font
// TODO: need to check for multiple fonts
IDWriteFontFaceReference* fontFaceReference;
factory->CreateFontFaceReference(fontFile, 0, DWRITE_FONT_SIMULATIONS_NONE, &fontFaceReference);
fontSetBuilder->AddFontFaceReference(fontFaceReference);
IDWriteFontSet* customFontSet;
fontSetBuilder->CreateFontSet(&customFontSet);
UINT32 fontCnt = customFontSet->GetFontCount();
if (fontCnt > 1) {
// TODO: need to check for multiple fonts
}
string postscriptName = getStringFromFontSet(customFontSet, DWRITE_FONT_PROPERTY_ID_POSTSCRIPT_NAME);
}
like this using IDWriteFontSet and DWRITE_FONT_PROPERTY_ID enum from dwrite_3.h helped me to get my solution.

Dear IMGUI and DirectX 12 Overlay (DXGI_ERROR_INVALID_CALL)

I'm trying to make a simple frame counter for DirectX 12 games using Dear IMGUI. I simply want to overlay a small transparent window that displays the sequential order of frames during gameplay. To do so, I hook Present(), so I can get the SwapChain, and count the number of times the method is called (frame counting). THIS IS NOT FOR A CHEAT. I am not writing cheats for games, I simply want to record frame numbers for analytical purposes.
I have successfully done this for DirectX 11 using the ShowExampleAppSimpleOverlay() example provided in here: https://github.com/ocornut/imgui/blob/master/imgui_demo.cpp
Here is an image sample showing the frame counter in a DX 11 game.
I'm now trying to do the same with DirectX 12. Hooking the Present() is not an issue.
Using example code provided here: https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx12/main.cpp
I attempt to use the ShowExampleAppSimpleOverlay() method again, however in my code on the call to d3d12CommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&d3d12CommandList); (to render the overlay) it results in an error saying (0x887A0001: DXGI_ERROR_INVALID_CALL). This is the last line of code in the code sample provided below:
I'm not sure how to proceed. Any thoughts?
Edit: I forgot to mention that I'm also hooking and acquiring the games command que. So d3d12CommandQueue is acquired directly from the game. It doesn't return NULL so I'm assuming it is the correct object. I could be wrong though...
For each call to Present() do the following:
//iterate frame
Frame_Number = Frame_Number + 1;
//Get Device, using IDXGISwapChain3
ID3D12Device* device;
HRESULT gd = pSwapChain->GetDevice(__uuidof(ID3D12Device), (void**)&device);
assert(gd == S_OK);
//Get window handle from swapchain for IMGUI
DXGI_SWAP_CHAIN_DESC sd;
pSwapChain->GetDesc(&sd);
window = sd.OutputWindow;
//Get backbuffers
buffersCounts = sd.BufferCount;
frameContext = new FrameContext[buffersCounts];
D3D12_DESCRIPTOR_HEAP_DESC descriptorImGuiRender = {};
descriptorImGuiRender.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
descriptorImGuiRender.NumDescriptors = buffersCounts;
descriptorImGuiRender.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
// Create Descriptor Heap IMGUI render
if (device->CreateDescriptorHeap(&descriptorImGuiRender, IID_PPV_ARGS(&d3d12DescriptorHeapImGuiRender)) != S_OK)
return false;
//Create Command Allocator
ID3D12CommandAllocator* allocator;
if (device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)) != S_OK)
return false;
for (size_t i = 0; i < buffersCounts; i++) {
frameContext[i].commandAllocator = allocator;
}
if (device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, NULL, IID_PPV_ARGS(&d3d12CommandList)) != S_OK ||
d3d12CommandList->Close() != S_OK)
return false;
//create descriptor heap, describe and create a render target view (RTV) descriptor heap.
D3D12_DESCRIPTOR_HEAP_DESC descriptorBackBuffers;
descriptorBackBuffers.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
descriptorBackBuffers.NumDescriptors = buffersCounts;
descriptorBackBuffers.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
descriptorBackBuffers.NodeMask = 1;
if (device->CreateDescriptorHeap(&descriptorBackBuffers, IID_PPV_ARGS(&d3d12DescriptorHeapBackBuffers)) != S_OK)
return false;
const auto rtvDescriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
// Create frame resources.
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = d3d12DescriptorHeapBackBuffers->GetCPUDescriptorHandleForHeapStart();
// Create a RTV for each frame.
for (size_t i = 0; i < buffersCounts; i++) {
ID3D12Resource* pBackBuffer = nullptr;
frameContext[i].main_render_target_descriptor = rtvHandle;
pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer));
device->CreateRenderTargetView(pBackBuffer, nullptr, rtvHandle);
frameContext[i].main_render_target_resource = pBackBuffer;
rtvHandle.ptr += rtvDescriptorSize;
}
// Setup Platform/Renderer bindings dor IMGUI
ImGui_ImplWin32_Init(window);
ImGui_ImplDX12_Init(device, buffersCounts,
DXGI_FORMAT_R8G8B8A8_UNORM, d3d12DescriptorHeapImGuiRender,
d3d12DescriptorHeapImGuiRender->GetCPUDescriptorHandleForHeapStart(),
d3d12DescriptorHeapImGuiRender->GetGPUDescriptorHandleForHeapStart());
ImGui::GetIO().ImeWindowHandle = window;
// Start the Dear ImGui frame
ImGui_ImplDX12_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
//call imgui menues here
bool bShow = true;
ShowExampleAppSimpleOverlay(&bShow);
// Rendering (imgui)
FrameContext& currentFrameContext = frameContext[pSwapChain->GetCurrentBackBufferIndex()];
currentFrameContext.commandAllocator->Reset();
D3D12_RESOURCE_BARRIER barrier;
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
barrier.Transition.pResource = currentFrameContext.main_render_target_resource;
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
d3d12CommandList->Reset(currentFrameContext.commandAllocator, nullptr);
d3d12CommandList->ResourceBarrier(1, &barrier);
d3d12CommandList->OMSetRenderTargets(1, &currentFrameContext.main_render_target_descriptor, FALSE, nullptr);
d3d12CommandList->SetDescriptorHeaps(1, &d3d12DescriptorHeapImGuiRender);
ImGui::Render();
ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), d3d12CommandList);
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
d3d12CommandList->ResourceBarrier(1, &barrier);
d3d12CommandList->Close();
d3d12CommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&d3d12CommandList);
DXGI_ERROR_INVALID_CALL tells that one command in the list is invalid but not which.
you need to use the d3d12 debug layer for runtime checks at command list creation.
The debug layer also tell you the reason why it is invalid.
see msdn for more info.
you can aktivate it with the following code, but it needs to be called before device creation
ID3D12Debug* debugInterface;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugInterface)))) {
debugInterface->EnableDebugLayer();
}

vkCreateSwapchainKHR: internal drawable creation failed

I had my Vulkan application working but for some reason it stopped working(I don't believe I touched anything that could have broken it, besides making my engine project a .lib instead of a .dll) and started giving the "vkCreateSwapchainKHR: internal drawable creation failed" error in the validation layers. vkCreateSwapchainKHR returns VK_ERROR_VALIDATION_FAILED_EXT.
I already checked this answer:
Wat does the "vkCreateSwapchainKHR:internal drawable creation failed." means, but it was not my problem, (as I said, it was working until it wasn't). Here's all the code I believe is relevant, if you need something else just comment:
Window Creation:
/* Initialize the library */
if (!glfwInit())
/* Create a windowed mode window and its OpenGL context */
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_DECORATED, _WCI.IsDecorated);
GLFWWindow = glfwCreateWindow(Extent.Width, Extent.Height, _WCI.Name.c_str(), nullptr, nullptr);
if (!GLFWWindow) glfwTerminate();
//glfwMakeContextCurrent(GLFWWindow);
uint32 Count = 0;
auto ff = glfwGetRequiredInstanceExtensions(&Count);
GS_BASIC_LOG_MESSAGE("GLFW required extensions:")
for (uint8 i = 0; i < Count; ++i)
{
GS_BASIC_LOG_MESSAGE("%d: %s", i, ff[i]);
}
WindowObject = glfwGetWin32Window(GLFWWindow);
WindowInstance = GetModuleHandle(nullptr);
I'm using the correct instance extensions:
const char* Extensions[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME, VK_EXT_DEBUG_UTILS_EXTENSION_NAME };
VKSwapchainCreator VulkanRenderContext::CreateSwapchain(VKDevice* _Device, VkSwapchainKHR _OldSwapchain) const
{
VkSwapchainCreateInfoKHR SwapchainCreateInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
SwapchainCreateInfo.surface = Surface.GetHandle();
SwapchainCreateInfo.minImageCount = 3;
SwapchainCreateInfo.imageFormat = Format.format;
SwapchainCreateInfo.imageColorSpace = Format.colorSpace;
SwapchainCreateInfo.imageExtent = Extent2DToVkExtent2D(RenderExtent);
//The imageArrayLayers specifies the amount of layers each image consists of. This is always 1 unless you are developing a stereoscopic 3D application.
SwapchainCreateInfo.imageArrayLayers = 1;
SwapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
SwapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
SwapchainCreateInfo.queueFamilyIndexCount = 0;
SwapchainCreateInfo.pQueueFamilyIndices = nullptr;
SwapchainCreateInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
SwapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
SwapchainCreateInfo.presentMode = PresentMode;
SwapchainCreateInfo.clipped = VK_TRUE;
SwapchainCreateInfo.oldSwapchain = _OldSwapchain;
return VKSwapchainCreator(_Device, &SwapchainCreateInfo);
}
Both VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR and VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR are supported by my GPU.
VkBool32 Supports = 0;
vkGetPhysicalDeviceSurfaceSupportKHR(_PD, PresentationQueue.GetQueueIndex(), _Surface, &Supports);
VkSurfaceCapabilitiesKHR SurfaceCapabilities = {};
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(_PD, _Surface, &SurfaceCapabilities);
VkBool32 Supported = 0;
vkGetPhysicalDeviceSurfaceSupportKHR(_PD, PresentationQueue.GetQueueIndex(), _Surface, &Supported);
auto bb = vkGetPhysicalDeviceWin32PresentationSupportKHR(_PD, PresentationQueue.GetQueueIndex());
Everything here returns true, although it seemed suspicious to me that VkSurfaceCapabilitiesKHR returned the same extent for currentExtent, minImageExtent and maxImageExtent.
/* Initialize the library */
if (!glfwInit())
/* Create a windowed mode window and its OpenGL context */
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_DECORATED, _WCI.IsDecorated);
If this is your actual code, it means "if glfwInit() succeeds skip glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);". And as we know not calling the hint causes the error.
The if should perhaps not have negation inside. And (this not being Python) it should have scope {} to cover all the init code.
The solution was to remove the glfwInit call from inside the if and place it outside.
if (!glfwInit()) -> glfwInit()
No idea why, if someone knows why this could've have caused the problem I would love to know.

Get window title with XCB

I am trying to get information about the window in focus. It seems that I get a correct window id from xcb_get_input_focus_reply_t->focus: it stays the same for my Eclipse IDE (56623164) and is another for any other window in focus. However, the value length is always 0 for XCB_ATOM_WM_NAME.
shortened code
cookie = xcb_get_property(c, 0, fr->focus, XCB_ATOM_WM_NAME,
XCB_ATOM_STRING, 0, 0);
if ((reply = xcb_get_property_reply(c, cookie, NULL))) {
int len = xcb_get_property_value_length(reply);
if (len == 0) {
printf("Zero Length\n");
free(reply);
return;
}
printf("WM_NAME is %.*s\n", len, (char*) xcb_get_property_value(reply));
}
Eclipse Debugger
reply xcb_get_property_reply_t * 0x60bd40
response_type uint8_t 1 '\001'
format uint8_t 0 '\0'
sequence uint16_t 2
length uint32_t 0
type xcb_atom_t 0
bytes_after uint32_t 0
value_len uint32_t 0
pad0 unsigned char [12] 0x60bd54
There is no error (I passed and inspected a xcb_generic_error_t). Do you have any idea what could go wrong? Maybe I should use Xlib instead...
This code works for me, it is in js-ctypes but you can ignore that part and see this for API use:
var win = aXcbWindowT;
// console.log('win:', win);
var req_title = ostypes.API('xcb_get_property')(ostypes.HELPER.cachedXCBConn(), 0, win, ostypes.CONST.XCB_ATOM_WM_NAME, ostypes.CONST.XCB_ATOM_STRING, 0, 100); // `100` means it will get 100*4 so 400 bytes, so that 400 char, so `rez_title.bytes_after` should be `0` but i can loop till it comes out to be 0
var rez_title = ostypes.API('xcb_get_property_reply')(ostypes.HELPER.cachedXCBConn(), req_title, null);
// console.log('rez_title:', rez_title);
var title_len = ostypes.API('xcb_get_property_value_length')(rez_title); // length is not null terminated so "Console - chrome://nativeshot/content/resources/scripts/MainWorker.js?0.01966718940939427" will be length of `88`, this matches `rez_title.length` but the docs recommend to use this call to get the value, i dont know why
console.log('title_len:', title_len, 'rez_title.contents.length:', rez_title.contents.length); // i think `rez_title.contents.length` is the actual length DIVIDED by 4, and rez_title_len is not dividied by 4
var title_buf = ostypes.API('xcb_get_property_value')(rez_title); // "title_len: 89 rez_title.contents.length: 23" for test case of "Console - chrome://nativeshot/content/resources/scripts/MainWorker.js?0.01966718940939427"
// console.log('title_buf:', title_buf);
var title = ctypes.cast(title_buf, ctypes.char.array(title_len).ptr).contents.readString();
console.log('title:', title);
ostypes.API('free')(rez_title);
return title;
Sometimes though what is returned by xcb_get_input_focus_reply_t->focus is not the window to act on. I have found that sometimes it doesn't have a title, but if you use xcb_query_tree you can find its parent window probaby has a title:
var req_query = ostypes.API('xcb_query_tree')(ostypes.HELPER.cachedXCBConn(), win);
var rez_query = ostypes.API('xcb_query_tree_reply')(ostypes.HELPER.cachedXCBConn(), req_query, null);
console.log('rez_query.contents:', rez_query.contents);
if (root === -1) {
root = rez_query.contents.root;
}
win = rez_query.contents.parent; // this win should have the title

Migration of JCoFunction in sapjco 3.x

I'm migrating from JCO2.x to 3.x. I have rewritten almost the whole code, but with this I cannot move.
Original 2.x code:
JCO.ParameterList input = new JCO.ParameterList();
input.addInfo("APP_AREA", JCO.TYPE_STRING, 0, 0, 0, JCO.IMPORT_PARAMETER, null);
input.addInfo("XML", JCO.TYPE_STRING, 0, 0, 0, JCO.IMPORT_PARAMETER, null);
JCO.Function function = new JCO.Function(
BAPI_NAMESPACE + "ZZZ",
input, // input
new JCO.ParameterList(), // output
new JCO.ParameterList() // tables
);
My proposed code:
JCoParameterList input = new JCoParameterList();
input.addInfo("APP_AREA", JCO.TYPE_STRING, 0, 0, 0, JCO.IMPORT_PARAMETER, null);
input.addInfo("XML", JCO.TYPE_STRING, 0, 0, 0, JCO.IMPORT_PARAMETER, null);
JCoFunction function = new JCoFunction(
BAPI_NAMESPACE + "ZZZ",
input, // input
new JCoParameterList(), // output
new JCoParameterList() // tables
);
Thing is that JCoFunction cannot be instantiated in this form in 3.x. Should I create function template? Thank you for any hints.
.... a little late response...
You have to get the JcoFunction from your JcoDestination.
e.g.
JCoDestination destination = JCoDestinationManager
.getDestination(destinationName);
JCoRepository repository = destination.getRepository();
JCoFunctionTemplate template = repository.getFunctionTemplate(functionName);
JCoFunction function = template.getFunction();
JCoParameterList input = function_.getImportParameterList();
//set data on input
//execute the function
function.execute(destination);
//access the output
JCoParameterList output = function_.getExportParameterList();
JCoParameterList table = function_.getTableParameterList();