Timming desynchronization when rendering two elements with DirectX - directx

I want to render two boxes that change the color at the exact same time. I am using DirectX and measuring when they change the color with a photoresistor attached to the screen (measures change of luminance).
The two boxes change from black to white every 200ms. They should change at the same time but I am measuring latencies of 0-20ms. Is there any option to force DirectX to render at the exact same time?
OnTimer_Elapsed(Object source, System.Timers.ElapsedEventArgs e)
{
if (i/2==1)
clr=clrWhite
else
clr=clrBlack
i++;
d2dRenderTarget.BeginDraw();
d2dRenderTarget.Clear(clrTrans);
d2dRenderTarget.DrawRectangle(rect1, clr);
d2dRenderTarget.FillRectangle(rect1, clr);
d2dRenderTarget.DrawRectangle(rect2, clr);
d2dRenderTarget.FillRectangle(rect2, clr);
d2dRenderTarget.EndDraw();
sc1.Present(1, PresentFlags.None);
}
This is the swapchain
sc1= new SwapChainDescription()
{
BufferCount = 1,
Flags = SwapChainFlags.None,
IsWindowed = true,
ModeDescription = new ModeDescription(
this.ClientSize.Width,
this.ClientSize.Height,
new Rational(60, 1),
Format.R8G8B8A8_UNorm),
OutputHandle = frm.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};

Related

How do I print image on their original size in Excel using libxlsxwriter?

I just started to use libxlsxwriter to create excel sheet. My problem is I don't know how to centralized the picture and how to print pictures on their original size. Just consider the set having only 3 columns and each column having different size for example 30,10,20. I need to know what is the calculation do I need to find offset and scale values.
lxw_image_options options = {.x_offset = 0, .y_offset = 0,.x_scale = 0.9, .y_scale = 0.9};
worksheet_insert_image_opt(worksheet, row, 0, img_path, &options);
With that, I need to Know How many rows the picture can hold.Then only I can create the upcoming set without overlap.
how to print pictures on their original size
libxlsxwriter inserts images into an xlsx file at their original size based on the width, height and DPI information in the image. It should insert images in exactly the same way as if you did it in Excel via the user interface.
However, images in OpenOffice or LibreOffice may not appear to the correct size. This isn't an libxlsxwriter issue: the same thing happens with Excel.
To insert images at precise positions you will need to know the dimensions of the images in pixels and also the DPI since Excel scales according to it's default DPI (usually 96) Here is an example of inserting two images in a row:
/*
* An example of inserting images with the libxlsxwriter library.
*/
#include "xlsxwriter.h"
int main() {
/* Create a new workbook and add a worksheet. */
lxw_workbook *workbook = workbook_new("demo.xlsx");
lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);
lxw_image_options options = {.x_offset = 0, .y_offset = 0,
.x_scale = 1, .y_scale = 1};
double default_dpi = 96.0;
double image_dpi = 90.0;
int32_t image_height = 138;
int32_t image_offset = (int32_t)(image_height * default_dpi/image_dpi);
/* Insert the first image. */
worksheet_insert_image(worksheet, 1, 2, "logo.png");
/* Insert the second image relative to the first. */
options.y_offset += image_offset;
worksheet_insert_image_opt(worksheet, 1, 2, "logo.png", &options);
workbook_close(workbook);
return 0;
}
Output:
How many rows did picture hold?
I want to Present my findings here to improvise the result.
int row=1;
lxw_image_options options = {.x_offset = 0, .y_offset = 0};
worksheet_insert_image_opt(worksheet, row, 2,"logo.png", &options);
row+=(options.height/worksheet->default_row_pixels);
Here I used the variable options.height to calculate How many rows the picture hold. The libxlsxwriter did read the height from the image file in pixels. It uses struct variable option only for read initialized variable it will never write anything in the set. But I did by adding the line user_options->height=options->height; in the function worksheet_insert_image_opt at worksheet.c.
lxw_error worksheet_insert_image_opt(lxw_worksheet *self,
lxw_row_t row_num, lxw_col_t col_num,
const char *filename,
lxw_image_options *user_options)
{
FILE *image_stream;
char *short_name;
lxw_image_options *options;
if (!filename) {
LXW_WARN("worksheet_insert_image()/_opt(): "
"filename must be specified.");
return LXW_ERROR_NULL_PARAMETER_IGNORED;
}
/* Check that the image file exists and can be opened. */
image_stream = fopen(filename, "rb");
if (!image_stream) {
LXW_WARN_FORMAT1("worksheet_insert_image()/_opt(): "
"file doesn't exist or can't be opened: %s.",
filename);
return LXW_ERROR_PARAMETER_VALIDATION;
}
/* Get the filename from the full path to add to the Drawing object. */
short_name = lxw_basename(filename);
if (!short_name) {
LXW_WARN_FORMAT1("worksheet_insert_image()/_opt(): "
"couldn't get basename for file: %s.", filename);
fclose(image_stream);
return LXW_ERROR_PARAMETER_VALIDATION;
}
/* Create a new object to hold the image options. */
options = calloc(1, sizeof(lxw_image_options));
if (!options) {
fclose(image_stream);
return LXW_ERROR_MEMORY_MALLOC_FAILED;
}
if (user_options) {
memcpy(options, user_options, sizeof(lxw_image_options));
options->url = lxw_strdup(user_options->url);
options->tip = lxw_strdup(user_options->tip);
}
/* Copy other options or set defaults. */
options->filename = lxw_strdup(filename);
options->short_name = lxw_strdup(short_name);
options->stream = image_stream;
options->row = row_num;
options->col = col_num;
if (!options->x_scale)
options->x_scale = 1;
if (!options->y_scale)
options->y_scale = 1;
if (_get_image_properties(options) == LXW_NO_ERROR) {
user_options->height=options->height;
STAILQ_INSERT_TAIL(self->image_data, options, list_pointers);
return LXW_NO_ERROR;
}
else {
free(options);
return LXW_ERROR_IMAGE_DIMENSIONS;
}
}
this how I was calcuating rows. If there is a better way please let me know.

Resize D3D11Texture2D DirectX 11

I would like to resize a D3D11Texture2D to make it smaller. For example I have a texture in 1920x1080 and I would like to scale it 1280x720 for example.
Just so you know I'm not drawing at all, I just want to get the byte buffer scaled. Here is my code :
if (mRealTexture == nullptr) {
D3D11_TEXTURE2D_DESC description;
texture2D->GetDesc(&description);
description.BindFlags = 0;
description.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
description.Usage = D3D11_USAGE_STAGING;
description.MiscFlags = 0;
hr = mDevice->CreateTexture2D(&description, NULL, &mRealTexture);
if (FAILED(hr)) {
if (mRealTexture) {
mRealTexture->Release();
mRealTexture = nullptr;
}
return NULL;
}
}
mImmediateContext->CopyResource(mRealTexture, texture2D);
if (mScaledTexture == nullptr) {
D3D11_TEXTURE2D_DESC description;
texture2D->GetDesc(&description);
description.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
description.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
description.Width = 1440;
description.Height = 585;
description.MipLevels = 4;
description.ArraySize = 1;
description.SampleDesc.Count = 1;
description.SampleDesc.Quality = 0;
description.Usage = D3D11_USAGE_DEFAULT;
hr = mDevice->CreateTexture2D(&description, NULL, &mScaledTexture);
if (FAILED(hr)) {
if (mScaledTexture) {
mScaledTexture->Release();
mScaledTexture = nullptr;
}
return NULL;
}
} //I want to copy the mRealTexture on the mScaledTexture, map the scaledTexture and get the buffer.
Thanks for help
Having thought about this and that you are left with only a couple of options.
1 - You create a viewport etc and render to your target size with a full screen quad. Which I get the feeling you don't want to do.
2 - You roll your own scaling which isn't too bad and scale texture as you copy the data from one buffer to another.
Option 2 isn't too bad, the roughest scaling would be reading a points based on the scaling ratio, but a more accurate version would be to average a number of samples based a weighted grid (the weights need to be recalculated for each pixel you visit on your target.)

XNA Vertex Buffer is drawing very wrongly

I'm new to using the vertex buffer in XNA. In my project I construct one using a very large amount of vertices. I have been drawing the primitives heretofore with DrawUserIndexedPrimitives(), but I have grown out of that and need more efficiency, so I am trying to figure out the basics of buffers.
I think I've successfully implemented a buffer (and have been very satisfied with the performance improvements), except that all the faces look wrong. Here's how the primitives looked without the buffer: http://i.imgur.com/ygsnB.jpg (the intended look), and here's how they look without: http://i.imgur.com/rQN1p.jpg
Here's my code for loading a vertex buffer and index buffer:
private void RefreshVertexBuffer()
{
List<VertexPositionNormalTexture> vertices = new List<VertexPositionNormalTexture>();
List<int> indices = new List<int>();
//rebuild the vertex list and index list
foreach(var entry in blocks)
{
Block block = entry.Value;
for (int q = 0; q < block.Quads.Count; q++)
{
vertices.AddRange(block.Quads[q].Corners);
int offset = vertices.Count;
foreach (Triangle tri in block.Quads[q].Triangles)
{
indices.Add(tri.Indices[0] + offset);
indices.Add(tri.Indices[1] + offset);
indices.Add(tri.Indices[2] + offset);
}
}
}
vertexBuffer = new DynamicVertexBuffer(graphics, typeof(VertexPositionNormalTexture), vertices.Count, BufferUsage.None);
indexBuffer = new DynamicIndexBuffer(graphics, IndexElementSize.ThirtyTwoBits, indices.Count, BufferUsage.None);
vertexBuffer.SetData<VertexPositionNormalTexture>(vertices.ToArray(), 0, vertices.Count);
indexBuffer.SetData<int>(indices.ToArray(), 0, indices.Count);
}
and here is the draw call for plain rendering:
public void Render(Planet planet, Camera camera)
{
effect.View = camera.View;
effect.Projection = camera.Projection;
effect.World = planet.World;
foreach (KeyValuePair<Vector3, Block> entry in planet.Geometry.Blocks)
{
int blockID = planet.BlockMap.Blocks[entry.Value.U][entry.Value.V][entry.Value.W];
if (blockID == 1)
effect.Texture = dirt;
else if (blockID == 2)
effect.Texture = rock;
effect.CurrentTechnique.Passes[0].Apply();
foreach (Quad quad in entry.Value.Quads)
{
foreach (Triangle tri in quad.Triangles)
{
graphics.DrawUserIndexedPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList,
quad.Corners, 0, quad.Corners.Length, tri.Indices, 0, 1);
}
}
}
}
...and for the vertex buffer rendering:
public void RenderFromBuffer(Planet planet, Camera camera)
{
effect.View = camera.View;
effect.Projection = camera.Projection;
effect.World = planet.World;
graphics.SetVertexBuffer(planet.Geometry.VertexBuffer);
graphics.Indices = planet.Geometry.IndexBuffer;
effect.CurrentTechnique.Passes[0].Apply();
graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, planet.Geometry.VertexBuffer.VertexCount, 0, planet.Geometry.IndexBuffer.IndexCount / 6);
}
My indices may be off? Or is this due to some quirks with how the graphics device acts with a buffer vs. user indexed?
Edit: It may also have something to do with the way I stitch triangle indices. When I built this project with DrawUserIndexedPrimitives, I ran into some issues similar to this where triangles facing a certain direction would draw on the wrong 'side' (or, the wrong face would be culled). So I came up with this solution:
Triangle[] tris;
if (faceDirection == ADJACENT_FACE_NAMES.BOTTOM | faceDirection == ADJACENT_FACE_NAMES.OUTER | faceDirection == ADJACENT_FACE_NAMES.LEFT)
{
//create the triangles for the quad
tris = new Triangle[2]{
new Triangle( //the bottom triangle
new int[3] {
0, //the bottom left corner
1, //the bottom right corner
2 //the top left corner
}),
new Triangle( //the top triangle
new int[3] {
1, //the bottom right corner
3, //the top right corner
2 //the top left corner
})};
}
else
{
tris = new Triangle[2]{
new Triangle(
new int[3] {
2, //the top left corner
1,
0
}),
new Triangle(
new int[3] {
2,
3,
1
})
};
}
The problem is that the triangles are being culled. So you have two options to fix this:
You can change the order of the triangle indices.
foreach (Triangle tri in block.Quads[q].Triangles)
{
indices.Add(tri.Indices[1] + offset);
indices.Add(tri.Indices[0] + offset);
indices.Add(tri.Indices[2] + offset);
}
You can change your RasterizerState...
Default rasterizer state is RasterizerState.CullClockwise...
You can change it to RasterizerState.CullCounterClockwise
EDIT:
this line has a bug:
graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, planet.Geometry.VertexBuffer.VertexCount, 0, planet.Geometry.IndexBuffer.IndexCount / 6)
should be:
graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, planet.Geometry.VertexBuffer.VertexCount, 0, planet.Geometry.IndexBuffer.IndexCount / 3)

achartengine x-axis labels shift compared to values

I noticed that the Xlabels of my Timechart are out of sync with the X-
values. The points should be right above the labels. On the left side
it OK, but it shifts towards the right. I don't know how to solve this
What i get:
http://tinypic.com/r/2uqj905/7
How it should be like:
http://www.achartengine.org/dimages/average_temperature.png
I tried a line chart or converted the date to a double but that had no
effect.
Any help would be be nice.
regards, Christian
This is some of my code:
XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
renderer.setPointSize(5.5f);
renderer.setZoomEnabled(false, false);
renderer.setMarginsColor(Color.parseColor("#00FF0000"));
renderer.setAxisTitleTextSize(16);
renderer.setYLabelsAlign(Align.RIGHT);
renderer.setLabelsTextSize(15);
renderer.setLegendTextSize(15);
renderer.setMargins(new int[] { 10, 65, 18, 10 });
int length = renderer.getSeriesRendererCount();
for (int i = 0; i < length; i++) {
XYSeriesRenderer seriesRenderer = (XYSeriesRenderer) renderer
.getSeriesRendererAt(i);
seriesRenderer.setFillPoints(true);
seriesRenderer.setLineWidth(4.0f); // dikte van lijn
}
MinMax minMax = determineMinMax(targetSteps, samples);
setChartSettings(renderer, context.getString(R.string.graph_title),
dateLabelOnScreenType(type),
context.getString(R.string.graph_y_axis), minMax.minX,
minMax.maxX, minY, maxY, Color.WHITE,
Color.BLACK);
renderer.setXLabels(7);
renderer.setYLabels(0);
renderer.setDisplayChartValues(false);
renderer.setShowGrid(true);
renderer.setPanEnabled(false, false);
// set the data
String[] titles = new String[] {
context.getString(R.string.graph_legend_target),
context.getString(R.string.graph_legend_actual) };
XYMultipleSeriesDataset dataSet = buildDateDataset(titles,
xSeriesList,
ySeriesList);
TimeChart chart = new TimeChart(dataSet, renderer);
chart.setDateFormat(dateFormatOnSampleType(type));
GraphicalView gview = new GraphicalView(context, chart);
renderer.setYLabelsAlign(Align.RIGHT);
Change to:
renderer.setYLabelsAlign(Align.CENTER);
The solution to this was added recently. Just call:
renderer.setXRoundedLabels(false)

Microsoft charts: transparency

I want a chart with transparent background, and therefore PNG seems a good choice. But when I set transparent background, the quality of the axis labels falls dramatically. How do I fix this? See the following code. As it stands, the chart has a transparent background, as I want, but the text quality is atrocious. If I comment out the two "Color.Transparent" settings, then the text quality is nice, but the background is not transparent.
How do I get transparency and nice text?
public static void Main(string[] args)
{
Chart c = new Chart();
c.TextAntiAliasingQuality = TextAntiAliasingQuality.High;
Series s = new Series("Series1");
c.Series.Clear();
c.Series.Add(s);
s.ChartType = SeriesChartType.Line;
s.Color = Color.Black;
ChartArea chartArea = new ChartArea("ChartArea1");
c.ChartAreas.Clear();
c.ChartAreas.Add(chartArea);
chartArea.BackColor = Color.FromArgb(255, 255, 255);
chartArea.BackSecondaryColor = Color.FromArgb(220, 220, 220);
chartArea.BackGradientStyle = GradientStyle.TopBottom;
chartArea.AxisX.LineColor = Color.Gray;
chartArea.AxisX.LineWidth = 2;
chartArea.AxisX.LineDashStyle = ChartDashStyle.Solid;
chartArea.AxisY.LineColor = Color.Gray;
chartArea.AxisY.LineWidth = 2;
chartArea.AxisY.LineDashStyle = ChartDashStyle.Solid;
chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
chartArea.AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dash;
chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
chartArea.AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dash;
c.BackColor = Color.Transparent;
chartArea.BackColor = Color.Transparent;
double[] x = new double[] { 1999, 2005 };
double[] y = new double[] { 3210, 13456 };
Axis ay = chartArea.AxisY;
ay.Maximum = 13456;
ay.Minimum = 3210;
Axis ax = chartArea.AxisX;
ax.Maximum = 2005;
ax.Minimum = 1999;
for (int i = 0; i < x.Length; i++)
{
double xvalue = x[i];
double yvalue = y[i];
s.Points.AddXY(xvalue, yvalue);
}
// Save chart-image to disk:
c.SaveImage("chartimage.png", ChartImageFormat.Png);
}
Set chart's AntiAliasing to AntiAliasingStyles.Graphics to disable the antialiasing on text.
Taken from this thread.
Maybe this help you
in your .aspx file where your chart code is, look for the asp:ChartArea tag. then add BackColor = "Transparent".
<asp:ChartArea Name="ChartArea1" BackColor="Transparent"
</asp:ChartArea>
Hope this help.
chart.TextAntiAliasingQuality = TextAntiAliasingQuality.SystemDefault;
I read this from here: http://forums.asp.net/p/1656335/4315304.aspx?Re%20Chart%20transparency%20and%20text%20quality

Resources