initial (bad) voxel renderer
This commit is contained in:
commit
7ae6a01949
31 files changed
+4268
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
Generated
+2300
File diff suppressed because it is too large.
Load diff
+15
@@ -0,0 +1,15 @@
|
|||||||
|
[package]
|
||||||
|
name = "pixelgame"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
bytemuck = {version="1.14.0", features=["derive"]}
|
||||||
|
nalgebra = {version="0.32.5", features=["bytemuck"]}
|
||||||
|
pollster = "0.3"
|
||||||
|
rand = "0.8.5"
|
||||||
|
simba = "0.8.1"
|
||||||
|
wgpu = "0.20"
|
||||||
|
winit = {version="0.30", features=["serde"]}
|
||||||
+491
@@ -0,0 +1,491 @@
|
|||||||
|
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" width="1200" height="934" onload="init(evt)" viewBox="0 0 1200 934" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:fg="http://github.com/jonhoo/inferno"><!--Flame graph stack visualization. See https://github.com/brendangregg/FlameGraph for latest version, and http://www.brendangregg.com/flamegraphs.html for examples.--><!--NOTES: --><defs><linearGradient id="background" y1="0" y2="1" x1="0" x2="0"><stop stop-color="#eeeeee" offset="5%"/><stop stop-color="#eeeeb0" offset="95%"/></linearGradient></defs><style type="text/css">
|
||||||
|
text { font-family:monospace; font-size:12px }
|
||||||
|
#title { text-anchor:middle; font-size:17px; }
|
||||||
|
#matched { text-anchor:end; }
|
||||||
|
#search { text-anchor:end; opacity:0.1; cursor:pointer; }
|
||||||
|
#search:hover, #search.show { opacity:1; }
|
||||||
|
#subtitle { text-anchor:middle; font-color:rgb(160,160,160); }
|
||||||
|
#unzoom { cursor:pointer; }
|
||||||
|
#frames > *:hover { stroke:black; stroke-width:0.5; cursor:pointer; }
|
||||||
|
.hide { display:none; }
|
||||||
|
.parent { opacity:0.5; }
|
||||||
|
</style><script type="text/ecmascript"><![CDATA[
|
||||||
|
var nametype = 'Function:';
|
||||||
|
var fontsize = 12;
|
||||||
|
var fontwidth = 0.59;
|
||||||
|
var xpad = 10;
|
||||||
|
var inverted = false;
|
||||||
|
var searchcolor = 'rgb(230,0,230)';
|
||||||
|
var fluiddrawing = true;
|
||||||
|
var truncate_text_right = false;
|
||||||
|
]]><![CDATA["use strict";
|
||||||
|
var details, searchbtn, unzoombtn, matchedtxt, svg, searching, frames, known_font_width;
|
||||||
|
function init(evt) {
|
||||||
|
details = document.getElementById("details").firstChild;
|
||||||
|
searchbtn = document.getElementById("search");
|
||||||
|
unzoombtn = document.getElementById("unzoom");
|
||||||
|
matchedtxt = document.getElementById("matched");
|
||||||
|
svg = document.getElementsByTagName("svg")[0];
|
||||||
|
frames = document.getElementById("frames");
|
||||||
|
known_font_width = get_monospace_width(frames);
|
||||||
|
total_samples = parseInt(frames.attributes.total_samples.value);
|
||||||
|
searching = 0;
|
||||||
|
|
||||||
|
// Use GET parameters to restore a flamegraph's state.
|
||||||
|
var restore_state = function() {
|
||||||
|
var params = get_params();
|
||||||
|
if (params.x && params.y)
|
||||||
|
zoom(find_group(document.querySelector('[*|x="' + params.x + '"][y="' + params.y + '"]')));
|
||||||
|
if (params.s)
|
||||||
|
search(params.s);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (fluiddrawing) {
|
||||||
|
// Make width dynamic so the SVG fits its parent's width.
|
||||||
|
svg.removeAttribute("width");
|
||||||
|
// Edge requires us to have a viewBox that gets updated with size changes.
|
||||||
|
var isEdge = /Edge\/\d./i.test(navigator.userAgent);
|
||||||
|
if (!isEdge) {
|
||||||
|
svg.removeAttribute("viewBox");
|
||||||
|
}
|
||||||
|
var update_for_width_change = function() {
|
||||||
|
if (isEdge) {
|
||||||
|
svg.attributes.viewBox.value = "0 0 " + svg.width.baseVal.value + " " + svg.height.baseVal.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep consistent padding on left and right of frames container.
|
||||||
|
frames.attributes.width.value = svg.width.baseVal.value - xpad * 2;
|
||||||
|
|
||||||
|
// Text truncation needs to be adjusted for the current width.
|
||||||
|
update_text_for_elements(frames.children);
|
||||||
|
|
||||||
|
// Keep search elements at a fixed distance from right edge.
|
||||||
|
var svgWidth = svg.width.baseVal.value;
|
||||||
|
searchbtn.attributes.x.value = svgWidth - xpad;
|
||||||
|
matchedtxt.attributes.x.value = svgWidth - xpad;
|
||||||
|
};
|
||||||
|
window.addEventListener('resize', function() {
|
||||||
|
update_for_width_change();
|
||||||
|
});
|
||||||
|
// This needs to be done asynchronously for Safari to work.
|
||||||
|
setTimeout(function() {
|
||||||
|
unzoom();
|
||||||
|
update_for_width_change();
|
||||||
|
restore_state();
|
||||||
|
}, 0);
|
||||||
|
} else {
|
||||||
|
restore_state();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// event listeners
|
||||||
|
window.addEventListener("click", function(e) {
|
||||||
|
var target = find_group(e.target);
|
||||||
|
if (target) {
|
||||||
|
if (target.nodeName == "a") {
|
||||||
|
if (e.ctrlKey === false) return;
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
|
if (target.classList.contains("parent")) unzoom();
|
||||||
|
zoom(target);
|
||||||
|
|
||||||
|
// set parameters for zoom state
|
||||||
|
var el = target.querySelector("rect");
|
||||||
|
if (el && el.attributes && el.attributes.y && el.attributes["fg:x"]) {
|
||||||
|
var params = get_params()
|
||||||
|
params.x = el.attributes["fg:x"].value;
|
||||||
|
params.y = el.attributes.y.value;
|
||||||
|
history.replaceState(null, null, parse_params(params));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (e.target.id == "unzoom") {
|
||||||
|
unzoom();
|
||||||
|
|
||||||
|
// remove zoom state
|
||||||
|
var params = get_params();
|
||||||
|
if (params.x) delete params.x;
|
||||||
|
if (params.y) delete params.y;
|
||||||
|
history.replaceState(null, null, parse_params(params));
|
||||||
|
}
|
||||||
|
else if (e.target.id == "search") search_prompt();
|
||||||
|
}, false)
|
||||||
|
// mouse-over for info
|
||||||
|
// show
|
||||||
|
window.addEventListener("mouseover", function(e) {
|
||||||
|
var target = find_group(e.target);
|
||||||
|
if (target) details.nodeValue = nametype + " " + g_to_text(target);
|
||||||
|
}, false)
|
||||||
|
// clear
|
||||||
|
window.addEventListener("mouseout", function(e) {
|
||||||
|
var target = find_group(e.target);
|
||||||
|
if (target) details.nodeValue = ' ';
|
||||||
|
}, false)
|
||||||
|
// ctrl-F for search
|
||||||
|
window.addEventListener("keydown",function (e) {
|
||||||
|
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
|
||||||
|
e.preventDefault();
|
||||||
|
search_prompt();
|
||||||
|
}
|
||||||
|
}, false)
|
||||||
|
// functions
|
||||||
|
function get_params() {
|
||||||
|
var params = {};
|
||||||
|
var paramsarr = window.location.search.substr(1).split('&');
|
||||||
|
for (var i = 0; i < paramsarr.length; ++i) {
|
||||||
|
var tmp = paramsarr[i].split("=");
|
||||||
|
if (!tmp[0] || !tmp[1]) continue;
|
||||||
|
params[tmp[0]] = decodeURIComponent(tmp[1]);
|
||||||
|
}
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
function parse_params(params) {
|
||||||
|
var uri = "?";
|
||||||
|
for (var key in params) {
|
||||||
|
uri += key + '=' + encodeURIComponent(params[key]) + '&';
|
||||||
|
}
|
||||||
|
if (uri.slice(-1) == "&")
|
||||||
|
uri = uri.substring(0, uri.length - 1);
|
||||||
|
if (uri == '?')
|
||||||
|
uri = window.location.href.split('?')[0];
|
||||||
|
return uri;
|
||||||
|
}
|
||||||
|
function find_child(node, selector) {
|
||||||
|
var children = node.querySelectorAll(selector);
|
||||||
|
if (children.length) return children[0];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
function find_group(node) {
|
||||||
|
var parent = node.parentElement;
|
||||||
|
if (!parent) return;
|
||||||
|
if (parent.id == "frames") return node;
|
||||||
|
return find_group(parent);
|
||||||
|
}
|
||||||
|
function orig_save(e, attr, val) {
|
||||||
|
if (e.attributes["fg:orig_" + attr] != undefined) return;
|
||||||
|
if (e.attributes[attr] == undefined) return;
|
||||||
|
if (val == undefined) val = e.attributes[attr].value;
|
||||||
|
e.setAttribute("fg:orig_" + attr, val);
|
||||||
|
}
|
||||||
|
function orig_load(e, attr) {
|
||||||
|
if (e.attributes["fg:orig_"+attr] == undefined) return;
|
||||||
|
e.attributes[attr].value = e.attributes["fg:orig_" + attr].value;
|
||||||
|
e.removeAttribute("fg:orig_" + attr);
|
||||||
|
}
|
||||||
|
function g_to_text(e) {
|
||||||
|
var text = find_child(e, "title").firstChild.nodeValue;
|
||||||
|
return (text)
|
||||||
|
}
|
||||||
|
function g_to_func(e) {
|
||||||
|
var func = g_to_text(e);
|
||||||
|
// if there's any manipulation we want to do to the function
|
||||||
|
// name before it's searched, do it here before returning.
|
||||||
|
return (func);
|
||||||
|
}
|
||||||
|
function get_monospace_width(frames) {
|
||||||
|
// Given the id="frames" element, return the width of text characters if
|
||||||
|
// this is a monospace font, otherwise return 0.
|
||||||
|
text = find_child(frames.children[0], "text");
|
||||||
|
originalContent = text.textContent;
|
||||||
|
text.textContent = "!";
|
||||||
|
bangWidth = text.getComputedTextLength();
|
||||||
|
text.textContent = "W";
|
||||||
|
wWidth = text.getComputedTextLength();
|
||||||
|
text.textContent = originalContent;
|
||||||
|
if (bangWidth === wWidth) {
|
||||||
|
return bangWidth;
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function update_text_for_elements(elements) {
|
||||||
|
// In order to render quickly in the browser, you want to do one pass of
|
||||||
|
// reading attributes, and one pass of mutating attributes. See
|
||||||
|
// https://web.dev/avoid-large-complex-layouts-and-layout-thrashing/ for details.
|
||||||
|
|
||||||
|
// Fall back to inefficient calculation, if we're variable-width font.
|
||||||
|
// TODO This should be optimized somehow too.
|
||||||
|
if (known_font_width === 0) {
|
||||||
|
for (var i = 0; i < elements.length; i++) {
|
||||||
|
update_text(elements[i]);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var textElemNewAttributes = [];
|
||||||
|
for (var i = 0; i < elements.length; i++) {
|
||||||
|
var e = elements[i];
|
||||||
|
var r = find_child(e, "rect");
|
||||||
|
var t = find_child(e, "text");
|
||||||
|
var w = parseFloat(r.attributes.width.value) * frames.attributes.width.value / 100 - 3;
|
||||||
|
var txt = find_child(e, "title").textContent.replace(/\([^(]*\)$/,"");
|
||||||
|
var newX = format_percent((parseFloat(r.attributes.x.value) + (100 * 3 / frames.attributes.width.value)));
|
||||||
|
|
||||||
|
// Smaller than this size won't fit anything
|
||||||
|
if (w < 2 * known_font_width) {
|
||||||
|
textElemNewAttributes.push([newX, ""]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fit in full text width
|
||||||
|
if (txt.length * known_font_width < w) {
|
||||||
|
textElemNewAttributes.push([newX, txt]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var substringLength = Math.floor(w / known_font_width) - 2;
|
||||||
|
if (truncate_text_right) {
|
||||||
|
// Truncate the right side of the text.
|
||||||
|
textElemNewAttributes.push([newX, txt.substring(0, substringLength) + ".."]);
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
// Truncate the left side of the text.
|
||||||
|
textElemNewAttributes.push([newX, ".." + txt.substring(txt.length - substringLength, txt.length)]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.assert(textElemNewAttributes.length === elements.length, "Resize failed, please file a bug at https://github.com/jonhoo/inferno/");
|
||||||
|
|
||||||
|
// Now that we know new textContent, set it all in one go so we don't refresh a bazillion times.
|
||||||
|
for (var i = 0; i < elements.length; i++) {
|
||||||
|
var e = elements[i];
|
||||||
|
var values = textElemNewAttributes[i];
|
||||||
|
var t = find_child(e, "text");
|
||||||
|
t.attributes.x.value = values[0];
|
||||||
|
t.textContent = values[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function update_text(e) {
|
||||||
|
var r = find_child(e, "rect");
|
||||||
|
var t = find_child(e, "text");
|
||||||
|
var w = parseFloat(r.attributes.width.value) * frames.attributes.width.value / 100 - 3;
|
||||||
|
var txt = find_child(e, "title").textContent.replace(/\([^(]*\)$/,"");
|
||||||
|
t.attributes.x.value = format_percent((parseFloat(r.attributes.x.value) + (100 * 3 / frames.attributes.width.value)));
|
||||||
|
|
||||||
|
// Smaller than this size won't fit anything
|
||||||
|
if (w < 2 * fontsize * fontwidth) {
|
||||||
|
t.textContent = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
t.textContent = txt;
|
||||||
|
// Fit in full text width
|
||||||
|
if (t.getComputedTextLength() < w)
|
||||||
|
return;
|
||||||
|
if (truncate_text_right) {
|
||||||
|
// Truncate the right side of the text.
|
||||||
|
for (var x = txt.length - 2; x > 0; x--) {
|
||||||
|
if (t.getSubStringLength(0, x + 2) <= w) {
|
||||||
|
t.textContent = txt.substring(0, x) + "..";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Truncate the left side of the text.
|
||||||
|
for (var x = 2; x < txt.length; x++) {
|
||||||
|
if (t.getSubStringLength(x - 2, txt.length) <= w) {
|
||||||
|
t.textContent = ".." + txt.substring(x, txt.length);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.textContent = "";
|
||||||
|
}
|
||||||
|
// zoom
|
||||||
|
function zoom_reset(e) {
|
||||||
|
if (e.tagName == "rect") {
|
||||||
|
e.attributes.x.value = format_percent(100 * parseInt(e.attributes["fg:x"].value) / total_samples);
|
||||||
|
e.attributes.width.value = format_percent(100 * parseInt(e.attributes["fg:w"].value) / total_samples);
|
||||||
|
}
|
||||||
|
if (e.childNodes == undefined) return;
|
||||||
|
for(var i = 0, c = e.childNodes; i < c.length; i++) {
|
||||||
|
zoom_reset(c[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function zoom_child(e, x, zoomed_width_samples) {
|
||||||
|
if (e.tagName == "text") {
|
||||||
|
var parent_x = parseFloat(find_child(e.parentNode, "rect[x]").attributes.x.value);
|
||||||
|
e.attributes.x.value = format_percent(parent_x + (100 * 3 / frames.attributes.width.value));
|
||||||
|
} else if (e.tagName == "rect") {
|
||||||
|
e.attributes.x.value = format_percent(100 * (parseInt(e.attributes["fg:x"].value) - x) / zoomed_width_samples);
|
||||||
|
e.attributes.width.value = format_percent(100 * parseInt(e.attributes["fg:w"].value) / zoomed_width_samples);
|
||||||
|
}
|
||||||
|
if (e.childNodes == undefined) return;
|
||||||
|
for(var i = 0, c = e.childNodes; i < c.length; i++) {
|
||||||
|
zoom_child(c[i], x, zoomed_width_samples);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function zoom_parent(e) {
|
||||||
|
if (e.attributes) {
|
||||||
|
if (e.attributes.x != undefined) {
|
||||||
|
e.attributes.x.value = "0.0%";
|
||||||
|
}
|
||||||
|
if (e.attributes.width != undefined) {
|
||||||
|
e.attributes.width.value = "100.0%";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (e.childNodes == undefined) return;
|
||||||
|
for(var i = 0, c = e.childNodes; i < c.length; i++) {
|
||||||
|
zoom_parent(c[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function zoom(node) {
|
||||||
|
var attr = find_child(node, "rect").attributes;
|
||||||
|
var width = parseInt(attr["fg:w"].value);
|
||||||
|
var xmin = parseInt(attr["fg:x"].value);
|
||||||
|
var xmax = xmin + width;
|
||||||
|
var ymin = parseFloat(attr.y.value);
|
||||||
|
unzoombtn.classList.remove("hide");
|
||||||
|
var el = frames.children;
|
||||||
|
var to_update_text = [];
|
||||||
|
for (var i = 0; i < el.length; i++) {
|
||||||
|
var e = el[i];
|
||||||
|
var a = find_child(e, "rect").attributes;
|
||||||
|
var ex = parseInt(a["fg:x"].value);
|
||||||
|
var ew = parseInt(a["fg:w"].value);
|
||||||
|
// Is it an ancestor
|
||||||
|
if (!inverted) {
|
||||||
|
var upstack = parseFloat(a.y.value) > ymin;
|
||||||
|
} else {
|
||||||
|
var upstack = parseFloat(a.y.value) < ymin;
|
||||||
|
}
|
||||||
|
if (upstack) {
|
||||||
|
// Direct ancestor
|
||||||
|
if (ex <= xmin && (ex+ew) >= xmax) {
|
||||||
|
e.classList.add("parent");
|
||||||
|
zoom_parent(e);
|
||||||
|
to_update_text.push(e);
|
||||||
|
}
|
||||||
|
// not in current path
|
||||||
|
else
|
||||||
|
e.classList.add("hide");
|
||||||
|
}
|
||||||
|
// Children maybe
|
||||||
|
else {
|
||||||
|
// no common path
|
||||||
|
if (ex < xmin || ex >= xmax) {
|
||||||
|
e.classList.add("hide");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
zoom_child(e, xmin, width);
|
||||||
|
to_update_text.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
update_text_for_elements(to_update_text);
|
||||||
|
}
|
||||||
|
function unzoom() {
|
||||||
|
unzoombtn.classList.add("hide");
|
||||||
|
var el = frames.children;
|
||||||
|
for(var i = 0; i < el.length; i++) {
|
||||||
|
el[i].classList.remove("parent");
|
||||||
|
el[i].classList.remove("hide");
|
||||||
|
zoom_reset(el[i]);
|
||||||
|
}
|
||||||
|
update_text_for_elements(el);
|
||||||
|
}
|
||||||
|
// search
|
||||||
|
function reset_search() {
|
||||||
|
var el = document.querySelectorAll("#frames rect");
|
||||||
|
for (var i = 0; i < el.length; i++) {
|
||||||
|
orig_load(el[i], "fill")
|
||||||
|
}
|
||||||
|
var params = get_params();
|
||||||
|
delete params.s;
|
||||||
|
history.replaceState(null, null, parse_params(params));
|
||||||
|
}
|
||||||
|
function search_prompt() {
|
||||||
|
if (!searching) {
|
||||||
|
var term = prompt("Enter a search term (regexp " +
|
||||||
|
"allowed, eg: ^ext4_)", "");
|
||||||
|
if (term != null) {
|
||||||
|
search(term)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
reset_search();
|
||||||
|
searching = 0;
|
||||||
|
searchbtn.classList.remove("show");
|
||||||
|
searchbtn.firstChild.nodeValue = "Search"
|
||||||
|
matchedtxt.classList.add("hide");
|
||||||
|
matchedtxt.firstChild.nodeValue = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function search(term) {
|
||||||
|
var re = new RegExp(term);
|
||||||
|
var el = frames.children;
|
||||||
|
var matches = new Object();
|
||||||
|
var maxwidth = 0;
|
||||||
|
for (var i = 0; i < el.length; i++) {
|
||||||
|
var e = el[i];
|
||||||
|
// Skip over frames which are either not visible, or below the zoomed-to frame
|
||||||
|
if (e.classList.contains("hide") || e.classList.contains("parent")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
var func = g_to_func(e);
|
||||||
|
var rect = find_child(e, "rect");
|
||||||
|
if (func == null || rect == null)
|
||||||
|
continue;
|
||||||
|
// Save max width. Only works as we have a root frame
|
||||||
|
var w = parseInt(rect.attributes["fg:w"].value);
|
||||||
|
if (w > maxwidth)
|
||||||
|
maxwidth = w;
|
||||||
|
if (func.match(re)) {
|
||||||
|
// highlight
|
||||||
|
var x = parseInt(rect.attributes["fg:x"].value);
|
||||||
|
orig_save(rect, "fill");
|
||||||
|
rect.attributes.fill.value = searchcolor;
|
||||||
|
// remember matches
|
||||||
|
if (matches[x] == undefined) {
|
||||||
|
matches[x] = w;
|
||||||
|
} else {
|
||||||
|
if (w > matches[x]) {
|
||||||
|
// overwrite with parent
|
||||||
|
matches[x] = w;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
searching = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!searching)
|
||||||
|
return;
|
||||||
|
var params = get_params();
|
||||||
|
params.s = term;
|
||||||
|
history.replaceState(null, null, parse_params(params));
|
||||||
|
|
||||||
|
searchbtn.classList.add("show");
|
||||||
|
searchbtn.firstChild.nodeValue = "Reset Search";
|
||||||
|
// calculate percent matched, excluding vertical overlap
|
||||||
|
var count = 0;
|
||||||
|
var lastx = -1;
|
||||||
|
var lastw = 0;
|
||||||
|
var keys = Array();
|
||||||
|
for (k in matches) {
|
||||||
|
if (matches.hasOwnProperty(k))
|
||||||
|
keys.push(k);
|
||||||
|
}
|
||||||
|
// sort the matched frames by their x location
|
||||||
|
// ascending, then width descending
|
||||||
|
keys.sort(function(a, b){
|
||||||
|
return a - b;
|
||||||
|
});
|
||||||
|
// Step through frames saving only the biggest bottom-up frames
|
||||||
|
// thanks to the sort order. This relies on the tree property
|
||||||
|
// where children are always smaller than their parents.
|
||||||
|
for (var k in keys) {
|
||||||
|
var x = parseInt(keys[k]);
|
||||||
|
var w = matches[keys[k]];
|
||||||
|
if (x >= lastx + lastw) {
|
||||||
|
count += w;
|
||||||
|
lastx = x;
|
||||||
|
lastw = w;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// display matched percent
|
||||||
|
matchedtxt.classList.remove("hide");
|
||||||
|
var pct = 100 * count / maxwidth;
|
||||||
|
if (pct != 100) pct = pct.toFixed(1);
|
||||||
|
matchedtxt.firstChild.nodeValue = "Matched: " + pct + "%";
|
||||||
|
}
|
||||||
|
function format_percent(n) {
|
||||||
|
return n.toFixed(4) + "%";
|
||||||
|
}
|
||||||
|
]]></script><rect x="0" y="0" width="100%" height="934" fill="url(#background)"/><text id="title" fill="rgb(0,0,0)" x="50.0000%" y="24.00">Flame Graph</text><text id="details" fill="rgb(0,0,0)" x="10" y="917.00"> </text><text id="unzoom" class="hide" fill="rgb(0,0,0)" x="10" y="24.00">Reset Zoom</text><text id="search" fill="rgb(0,0,0)" x="1190" y="24.00">Search</text><text id="matched" fill="rgb(0,0,0)" x="1190" y="917.00"> </text><svg id="frames" x="10" width="1180" total_samples="239"><g><title>[libGLX_nvidia.so.535.171.04] (2 samples, 0.84%)</title><rect x="0.0000%" y="789" width="0.8368%" height="15" fill="rgb(227,0,7)" fg:x="0" fg:w="2"/><text x="0.2500%" y="799.50"></text></g><g><title>[libnvidia-glcore.so.535.171.04] (1 samples, 0.42%)</title><rect x="0.4184%" y="773" width="0.4184%" height="15" fill="rgb(217,0,24)" fg:x="1" fg:w="1"/><text x="0.6684%" y="783.50"></text></g><g><title>[libnvidia-glcore.so.535.171.04] (1 samples, 0.42%)</title><rect x="0.4184%" y="757" width="0.4184%" height="15" fill="rgb(221,193,54)" fg:x="1" fg:w="1"/><text x="0.6684%" y="767.50"></text></g><g><title>[libnvidia-glcore.so.535.171.04] (3 samples, 1.26%)</title><rect x="0.0000%" y="821" width="1.2552%" height="15" fill="rgb(248,212,6)" fg:x="0" fg:w="3"/><text x="0.2500%" y="831.50"></text></g><g><title>[libnvidia-glcore.so.535.171.04] (3 samples, 1.26%)</title><rect x="0.0000%" y="805" width="1.2552%" height="15" fill="rgb(208,68,35)" fg:x="0" fg:w="3"/><text x="0.2500%" y="815.50"></text></g><g><title>[libnvidia-glcore.so.535.171.04] (1 samples, 0.42%)</title><rect x="0.8368%" y="789" width="0.4184%" height="15" fill="rgb(232,128,0)" fg:x="2" fg:w="1"/><text x="1.0868%" y="799.50"></text></g><g><title>__libc_calloc (1 samples, 0.42%)</title><rect x="0.8368%" y="773" width="0.4184%" height="15" fill="rgb(207,160,47)" fg:x="2" fg:w="1"/><text x="1.0868%" y="783.50"></text></g><g><title>[libc.so.6] (1 samples, 0.42%)</title><rect x="0.8368%" y="757" width="0.4184%" height="15" fill="rgb(228,23,34)" fg:x="2" fg:w="1"/><text x="1.0868%" y="767.50"></text></g><g><title>[libc.so.6] (1 samples, 0.42%)</title><rect x="0.8368%" y="741" width="0.4184%" height="15" fill="rgb(218,30,26)" fg:x="2" fg:w="1"/><text x="1.0868%" y="751.50"></text></g><g><title>[libc.so.6] (1 samples, 0.42%)</title><rect x="0.8368%" y="725" width="0.4184%" height="15" fill="rgb(220,122,19)" fg:x="2" fg:w="1"/><text x="1.0868%" y="735.50"></text></g><g><title>__mmap (1 samples, 0.42%)</title><rect x="0.8368%" y="709" width="0.4184%" height="15" fill="rgb(250,228,42)" fg:x="2" fg:w="1"/><text x="1.0868%" y="719.50"></text></g><g><title>[unknown] (1 samples, 0.42%)</title><rect x="0.8368%" y="693" width="0.4184%" height="15" fill="rgb(240,193,28)" fg:x="2" fg:w="1"/><text x="1.0868%" y="703.50"></text></g><g><title>[unknown] (1 samples, 0.42%)</title><rect x="0.8368%" y="677" width="0.4184%" height="15" fill="rgb(216,20,37)" fg:x="2" fg:w="1"/><text x="1.0868%" y="687.50"></text></g><g><title>[unknown] (1 samples, 0.42%)</title><rect x="0.8368%" y="661" width="0.4184%" height="15" fill="rgb(206,188,39)" fg:x="2" fg:w="1"/><text x="1.0868%" y="671.50"></text></g><g><title>[vkcf]_Analysis (5 samples, 2.09%)</title><rect x="0.0000%" y="869" width="2.0921%" height="15" fill="rgb(217,207,13)" fg:x="0" fg:w="5"/><text x="0.2500%" y="879.50">[..</text></g><g><title>[libc.so.6] (5 samples, 2.09%)</title><rect x="0.0000%" y="853" width="2.0921%" height="15" fill="rgb(231,73,38)" fg:x="0" fg:w="5"/><text x="0.2500%" y="863.50">[..</text></g><g><title>[libc.so.6] (5 samples, 2.09%)</title><rect x="0.0000%" y="837" width="2.0921%" height="15" fill="rgb(225,20,46)" fg:x="0" fg:w="5"/><text x="0.2500%" y="847.50">[..</text></g><g><title>[unknown] (2 samples, 0.84%)</title><rect x="1.2552%" y="821" width="0.8368%" height="15" fill="rgb(210,31,41)" fg:x="3" fg:w="2"/><text x="1.5052%" y="831.50"></text></g><g><title>[unknown] (2 samples, 0.84%)</title><rect x="1.2552%" y="805" width="0.8368%" height="15" fill="rgb(221,200,47)" fg:x="3" fg:w="2"/><text x="1.5052%" y="815.50"></text></g><g><title>[unknown] (1 samples, 0.42%)</title><rect x="1.6736%" y="789" width="0.4184%" height="15" fill="rgb(226,26,5)" fg:x="4" fg:w="1"/><text x="1.9236%" y="799.50"></text></g><g><title>[libc.so.6] (1 samples, 0.42%)</title><rect x="2.0921%" y="821" width="0.4184%" height="15" fill="rgb(249,33,26)" fg:x="5" fg:w="1"/><text x="2.3421%" y="831.50"></text></g><g><title>snprintf (1 samples, 0.42%)</title><rect x="2.0921%" y="805" width="0.4184%" height="15" fill="rgb(235,183,28)" fg:x="5" fg:w="1"/><text x="2.3421%" y="815.50"></text></g><g><title>[libc.so.6] (1 samples, 0.42%)</title><rect x="2.0921%" y="789" width="0.4184%" height="15" fill="rgb(221,5,38)" fg:x="5" fg:w="1"/><text x="2.3421%" y="799.50"></text></g><g><title>[libc.so.6] (1 samples, 0.42%)</title><rect x="2.0921%" y="773" width="0.4184%" height="15" fill="rgb(247,18,42)" fg:x="5" fg:w="1"/><text x="2.3421%" y="783.50"></tLine truncated
|
||||||
|
After Width: | Height: | Size: 201 KiB |
Binary file not shown.
@@ -0,0 +1,44 @@
|
|||||||
|
use nalgebra::{Point3, Rotation3, UnitVector3, Vector3};
|
||||||
|
|
||||||
|
const DEFAULT_ASPECT_RATIO: f32 = 16. / 9.;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct Camera {
|
||||||
|
pub pos: Point3<f32>,
|
||||||
|
pub orientation: Rotation3<f32>,
|
||||||
|
pub aspect: f32,
|
||||||
|
pub scale: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Camera {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
pos: Point3::origin(),
|
||||||
|
orientation: Rotation3::identity(),
|
||||||
|
aspect: DEFAULT_ASPECT_RATIO,
|
||||||
|
scale: 1.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Camera {
|
||||||
|
pub fn left(&self) -> UnitVector3<f32> {
|
||||||
|
self.orientation * -Vector3::x_axis()
|
||||||
|
}
|
||||||
|
pub fn right(&self) -> UnitVector3<f32> {
|
||||||
|
self.orientation * Vector3::x_axis()
|
||||||
|
}
|
||||||
|
pub fn down(&self) -> UnitVector3<f32> {
|
||||||
|
self.orientation * -Vector3::y_axis()
|
||||||
|
}
|
||||||
|
pub fn up(&self) -> UnitVector3<f32> {
|
||||||
|
self.orientation * Vector3::y_axis()
|
||||||
|
}
|
||||||
|
pub fn backward(&self) -> UnitVector3<f32> {
|
||||||
|
self.orientation * -Vector3::z_axis()
|
||||||
|
}
|
||||||
|
pub fn forward(&self) -> UnitVector3<f32> {
|
||||||
|
self.orientation * Vector3::z_axis()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
use bevy_ecs::bundle::Bundle;
|
||||||
|
|
||||||
|
use crate::world::{component::{Position, Rotation}, grid::TileGrid};
|
||||||
|
|
||||||
|
#[derive(Bundle)]
|
||||||
|
pub struct ClientGrid {
|
||||||
|
pub grid: TileGrid,
|
||||||
|
pub position: Position,
|
||||||
|
pub rotation: Rotation,
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use nalgebra::{Rotation3, Vector3};
|
||||||
|
use winit::{keyboard::KeyCode as Key, window::CursorGrabMode};
|
||||||
|
|
||||||
|
use super::Client;
|
||||||
|
|
||||||
|
impl Client<'_> {
|
||||||
|
pub fn handle_input(&mut self, dt: &Duration) {
|
||||||
|
let dt = dt.as_secs_f32();
|
||||||
|
let Client { input, state, .. } = self;
|
||||||
|
if input.just_pressed(Key::Escape) {
|
||||||
|
if let Some(window) = &self.window {
|
||||||
|
self.grabbed_cursor = !self.grabbed_cursor;
|
||||||
|
let mode = if self.grabbed_cursor {
|
||||||
|
window.set_cursor_visible(false);
|
||||||
|
CursorGrabMode::Locked
|
||||||
|
} else {
|
||||||
|
window.set_cursor_visible(true);
|
||||||
|
CursorGrabMode::None
|
||||||
|
};
|
||||||
|
window.set_cursor_grab(mode).expect("wah");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if self.grabbed_cursor {
|
||||||
|
let delta = input.mouse_delta;
|
||||||
|
if delta.x != 0.0 {
|
||||||
|
state.camera.orientation =
|
||||||
|
Rotation3::from_axis_angle(&state.camera.up(), delta.x * 0.003)
|
||||||
|
* state.camera.orientation;
|
||||||
|
}
|
||||||
|
if delta.y != 0.0 {
|
||||||
|
state.camera.orientation =
|
||||||
|
Rotation3::from_axis_angle(&state.camera.right(), delta.y * 0.003)
|
||||||
|
* state.camera.orientation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let rot_dist = 1.0 * dt;
|
||||||
|
if input.pressed(Key::KeyQ) {
|
||||||
|
state.camera.orientation =
|
||||||
|
Rotation3::from_axis_angle(&state.camera.forward(), rot_dist)
|
||||||
|
* state.camera.orientation;
|
||||||
|
}
|
||||||
|
if input.pressed(Key::KeyE) {
|
||||||
|
state.camera.orientation =
|
||||||
|
Rotation3::from_axis_angle(&state.camera.forward(), -rot_dist)
|
||||||
|
* state.camera.orientation;
|
||||||
|
}
|
||||||
|
if input.scroll_delta != 0.0 {
|
||||||
|
state.camera_scroll += input.scroll_delta;
|
||||||
|
state.camera.scale = (state.camera_scroll * 0.2).exp();
|
||||||
|
}
|
||||||
|
let move_dist = 10.0 * dt;
|
||||||
|
|
||||||
|
if input.pressed(Key::KeyW) {
|
||||||
|
state.camera.pos += *state.camera.forward() * move_dist;
|
||||||
|
}
|
||||||
|
if input.pressed(Key::KeyA) {
|
||||||
|
state.camera.pos += *state.camera.left() * move_dist;
|
||||||
|
}
|
||||||
|
if input.pressed(Key::KeyS) {
|
||||||
|
state.camera.pos += *state.camera.backward() * move_dist;
|
||||||
|
}
|
||||||
|
if input.pressed(Key::KeyD) {
|
||||||
|
state.camera.pos += *state.camera.right() * move_dist;
|
||||||
|
}
|
||||||
|
if input.pressed(Key::Space) {
|
||||||
|
state.camera.pos += *state.camera.up() * move_dist;
|
||||||
|
}
|
||||||
|
if input.pressed(Key::ShiftLeft) {
|
||||||
|
state.camera.pos += *state.camera.down() * move_dist;
|
||||||
|
}
|
||||||
|
if input.pressed(Key::KeyZ) {
|
||||||
|
state.camera_scroll += dt * 10.0;
|
||||||
|
state.camera.scale = (state.camera_scroll * 0.1).exp();
|
||||||
|
}
|
||||||
|
if input.pressed(Key::KeyX) {
|
||||||
|
state.camera_scroll -= dt * 10.0;
|
||||||
|
state.camera.scale = (state.camera_scroll * 0.1).exp();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use winit::{
|
||||||
|
event::{DeviceEvent, ElementState, MouseButton, MouseScrollDelta, WindowEvent},
|
||||||
|
keyboard::{KeyCode, PhysicalKey},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::util::math::{Pos2f, Vec2f};
|
||||||
|
|
||||||
|
pub struct Input {
|
||||||
|
pub mouse_pixel_pos: Pos2f,
|
||||||
|
pub mouse_delta: Vec2f,
|
||||||
|
|
||||||
|
pressed: HashSet<KeyCode>,
|
||||||
|
just_pressed: HashSet<KeyCode>,
|
||||||
|
|
||||||
|
mouse_pressed: HashSet<MouseButton>,
|
||||||
|
mouse_just_pressed: HashSet<MouseButton>,
|
||||||
|
mouse_just_released: HashSet<MouseButton>,
|
||||||
|
|
||||||
|
pub scroll_delta: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Input {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
mouse_pixel_pos: Pos2f::origin(),
|
||||||
|
mouse_delta: Vec2f::zeros(),
|
||||||
|
pressed: HashSet::new(),
|
||||||
|
just_pressed: HashSet::new(),
|
||||||
|
mouse_pressed: HashSet::new(),
|
||||||
|
mouse_just_pressed: HashSet::new(),
|
||||||
|
mouse_just_released: HashSet::new(),
|
||||||
|
scroll_delta: 0.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn update_device(&mut self, event: DeviceEvent) {
|
||||||
|
match event {
|
||||||
|
DeviceEvent::MouseWheel { delta } => {
|
||||||
|
self.scroll_delta = match delta {
|
||||||
|
MouseScrollDelta::LineDelta(_, v) => v,
|
||||||
|
MouseScrollDelta::PixelDelta(v) => (v.y / 2.0) as f32,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
DeviceEvent::MouseMotion { delta } => {
|
||||||
|
self.mouse_delta += Vec2f::new(delta.0 as f32, delta.1 as f32);
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_window(&mut self, event: WindowEvent) {
|
||||||
|
match event {
|
||||||
|
WindowEvent::KeyboardInput { event, .. } => {
|
||||||
|
let code = if let PhysicalKey::Code(code) = event.physical_key {
|
||||||
|
code
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match event.state {
|
||||||
|
ElementState::Pressed => {
|
||||||
|
self.just_pressed.insert(code);
|
||||||
|
self.pressed.insert(code);
|
||||||
|
}
|
||||||
|
ElementState::Released => {
|
||||||
|
self.pressed.remove(&code);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
WindowEvent::CursorLeft { .. } => {
|
||||||
|
self.pressed.clear();
|
||||||
|
self.mouse_pressed.clear();
|
||||||
|
}
|
||||||
|
WindowEvent::CursorMoved { position, .. } => {
|
||||||
|
self.mouse_pixel_pos = Pos2f::new(position.x as f32, position.y as f32);
|
||||||
|
}
|
||||||
|
WindowEvent::MouseInput { button, state, .. } => match state {
|
||||||
|
ElementState::Pressed => {
|
||||||
|
self.mouse_just_pressed.insert(button);
|
||||||
|
self.mouse_pressed.insert(button);
|
||||||
|
}
|
||||||
|
ElementState::Released => {
|
||||||
|
self.mouse_pressed.remove(&button);
|
||||||
|
self.mouse_just_released.insert(button);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn end(&mut self) {
|
||||||
|
self.scroll_delta = 0.0;
|
||||||
|
self.mouse_delta = Vec2f::zeros();
|
||||||
|
self.just_pressed.clear();
|
||||||
|
self.mouse_just_pressed.clear();
|
||||||
|
self.mouse_just_released.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn pressed(&self, key: KeyCode) -> bool {
|
||||||
|
self.pressed.contains(&key)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn just_pressed(&self, key: KeyCode) -> bool {
|
||||||
|
self.just_pressed.contains(&key)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn mouse_pressed(&self, button: MouseButton) -> bool {
|
||||||
|
self.mouse_pressed.contains(&button)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn mouse_just_pressed(&self, button: MouseButton) -> bool {
|
||||||
|
self.mouse_just_pressed.contains(&button)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn mouse_just_released(&self, button: MouseButton) -> bool {
|
||||||
|
self.mouse_just_released.contains(&button)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
mod camera;
|
||||||
|
mod handle_input;
|
||||||
|
mod input;
|
||||||
|
mod render;
|
||||||
|
mod rsc;
|
||||||
|
mod state;
|
||||||
|
mod window;
|
||||||
|
|
||||||
|
pub use state::*;
|
||||||
|
|
||||||
|
use self::{input::Input, render::Renderer, rsc::FRAME_TIME, ClientState};
|
||||||
|
use std::{
|
||||||
|
sync::Arc,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use winit::window::Window;
|
||||||
|
|
||||||
|
pub struct Client<'a> {
|
||||||
|
window: Option<Arc<Window>>,
|
||||||
|
renderer: Option<Renderer<'a>>,
|
||||||
|
frame_time: Duration,
|
||||||
|
state: ClientState,
|
||||||
|
exit: bool,
|
||||||
|
input: Input,
|
||||||
|
target: Instant,
|
||||||
|
prev_frame: Instant,
|
||||||
|
prev_update: Instant,
|
||||||
|
grabbed_cursor: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client<'_> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
window: None,
|
||||||
|
renderer: None,
|
||||||
|
exit: false,
|
||||||
|
frame_time: FRAME_TIME,
|
||||||
|
state: ClientState::new(),
|
||||||
|
input: Input::new(),
|
||||||
|
prev_frame: Instant::now(),
|
||||||
|
prev_update: Instant::now(),
|
||||||
|
target: Instant::now(),
|
||||||
|
grabbed_cursor: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start(&mut self) {}
|
||||||
|
|
||||||
|
pub fn update(&mut self) -> bool {
|
||||||
|
let now = Instant::now();
|
||||||
|
let dt = now - self.prev_update;
|
||||||
|
self.prev_update = now;
|
||||||
|
|
||||||
|
self.handle_input(&dt);
|
||||||
|
self.input.end();
|
||||||
|
|
||||||
|
if now >= self.target {
|
||||||
|
self.target += self.frame_time;
|
||||||
|
self.prev_frame = now;
|
||||||
|
|
||||||
|
let renderer = self.renderer.as_mut().unwrap();
|
||||||
|
renderer.update(&self.state);
|
||||||
|
renderer.draw();
|
||||||
|
}
|
||||||
|
|
||||||
|
self.exit
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
use std::marker::PhantomData;
|
||||||
|
use wgpu::{BufferAddress, BufferUsages};
|
||||||
|
|
||||||
|
pub struct ArrBuf<T: bytemuck::Pod> {
|
||||||
|
len: usize,
|
||||||
|
buffer: wgpu::Buffer,
|
||||||
|
label: String,
|
||||||
|
typ: PhantomData<T>,
|
||||||
|
usage: BufferUsages,
|
||||||
|
moves: Vec<BufMove>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: bytemuck::Pod> ArrBuf<T> {
|
||||||
|
pub fn update(
|
||||||
|
&mut self,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
encoder: &mut wgpu::CommandEncoder,
|
||||||
|
belt: &mut wgpu::util::StagingBelt,
|
||||||
|
size: usize,
|
||||||
|
updates: &[ArrBufUpdate<T>],
|
||||||
|
) -> bool {
|
||||||
|
let mut resized = false;
|
||||||
|
if size != self.len || !self.moves.is_empty() {
|
||||||
|
let new = Self::init_buf(device, &self.label, size, self.usage);
|
||||||
|
let cpy_len = self.len.min(size);
|
||||||
|
encoder.copy_buffer_to_buffer(
|
||||||
|
&self.buffer,
|
||||||
|
0,
|
||||||
|
&new,
|
||||||
|
0,
|
||||||
|
(cpy_len * std::mem::size_of::<T>()) as u64,
|
||||||
|
);
|
||||||
|
for m in &self.moves {
|
||||||
|
encoder.copy_buffer_to_buffer(
|
||||||
|
&self.buffer,
|
||||||
|
(m.source * std::mem::size_of::<T>()) as BufferAddress,
|
||||||
|
&new,
|
||||||
|
(m.dest * std::mem::size_of::<T>()) as BufferAddress,
|
||||||
|
(m.size * std::mem::size_of::<T>()) as BufferAddress,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
resized = true;
|
||||||
|
self.moves.clear();
|
||||||
|
self.len = size;
|
||||||
|
self.buffer = new;
|
||||||
|
}
|
||||||
|
if self.len == 0 {
|
||||||
|
return resized;
|
||||||
|
}
|
||||||
|
for update in updates {
|
||||||
|
let mut view = belt.write_buffer(
|
||||||
|
encoder,
|
||||||
|
&self.buffer,
|
||||||
|
(update.offset * std::mem::size_of::<T>()) as BufferAddress,
|
||||||
|
unsafe {
|
||||||
|
std::num::NonZeroU64::new_unchecked(
|
||||||
|
(update.data.len() * std::mem::size_of::<T>()) as u64,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
device,
|
||||||
|
);
|
||||||
|
view.copy_from_slice(bytemuck::cast_slice(&update.data));
|
||||||
|
}
|
||||||
|
resized
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init(device: &wgpu::Device, label: &str, usage: BufferUsages) -> Self {
|
||||||
|
let label = &(label.to_owned() + " Buffer");
|
||||||
|
Self {
|
||||||
|
len: 0,
|
||||||
|
buffer: Self::init_buf(device, label, 0, usage),
|
||||||
|
label: label.to_string(),
|
||||||
|
typ: PhantomData,
|
||||||
|
usage,
|
||||||
|
moves: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init_buf(
|
||||||
|
device: &wgpu::Device,
|
||||||
|
label: &str,
|
||||||
|
mut size: usize,
|
||||||
|
usage: BufferUsages,
|
||||||
|
) -> wgpu::Buffer {
|
||||||
|
if usage.contains(BufferUsages::STORAGE) && size == 0 {
|
||||||
|
size = 1;
|
||||||
|
}
|
||||||
|
device.create_buffer(&wgpu::BufferDescriptor {
|
||||||
|
label: Some(label),
|
||||||
|
usage: usage | BufferUsages::COPY_DST | BufferUsages::COPY_SRC,
|
||||||
|
size: (size * std::mem::size_of::<T>()) as u64,
|
||||||
|
mapped_at_creation: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn buffer(&self) -> &wgpu::Buffer {
|
||||||
|
&self.buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mov(&mut self, mov: BufMove) {
|
||||||
|
self.moves.push(mov);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ArrBufUpdate<T> {
|
||||||
|
pub offset: usize,
|
||||||
|
pub data: Vec<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct BufMove {
|
||||||
|
pub source: usize,
|
||||||
|
pub dest: usize,
|
||||||
|
pub size: usize,
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
use wgpu::{BufferUsages, VertexAttribute};
|
||||||
|
|
||||||
|
use super::buf::{ArrBuf, ArrBufUpdate, BufMove};
|
||||||
|
|
||||||
|
pub struct Instances<T: bytemuck::Pod> {
|
||||||
|
buf: ArrBuf<T>,
|
||||||
|
location: u32,
|
||||||
|
attrs: [VertexAttribute; 1],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: bytemuck::Pod> Instances<T> {
|
||||||
|
pub fn update(
|
||||||
|
&mut self,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
encoder: &mut wgpu::CommandEncoder,
|
||||||
|
belt: &mut wgpu::util::StagingBelt,
|
||||||
|
size: usize,
|
||||||
|
updates: &[ArrBufUpdate<T>],
|
||||||
|
) -> bool {
|
||||||
|
self.buf.update(device, encoder, belt, size, updates)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init(
|
||||||
|
device: &wgpu::Device,
|
||||||
|
label: &str,
|
||||||
|
location: u32,
|
||||||
|
format: wgpu::VertexFormat,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
buf: ArrBuf::init(
|
||||||
|
device,
|
||||||
|
&(label.to_owned() + " Instance"),
|
||||||
|
BufferUsages::VERTEX,
|
||||||
|
),
|
||||||
|
location,
|
||||||
|
attrs: [wgpu::VertexAttribute {
|
||||||
|
format,
|
||||||
|
offset: 0,
|
||||||
|
shader_location: location,
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_in<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
|
||||||
|
render_pass.set_vertex_buffer(self.location, self.buf.buffer().slice(..));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn desc(&self) -> wgpu::VertexBufferLayout {
|
||||||
|
wgpu::VertexBufferLayout {
|
||||||
|
array_stride: std::mem::size_of::<T>() as wgpu::BufferAddress,
|
||||||
|
step_mode: wgpu::VertexStepMode::Instance,
|
||||||
|
attributes: &self.attrs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mov(&mut self, mov: BufMove) {
|
||||||
|
self.buf.mov(mov);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
mod buf;
|
||||||
|
mod instance;
|
||||||
|
mod renderer;
|
||||||
|
mod storage;
|
||||||
|
pub mod voxel;
|
||||||
|
mod uniform;
|
||||||
|
|
||||||
|
pub use renderer::*;
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use super::voxel::VoxelPipeline;
|
||||||
|
use crate::client::{rsc::CLEAR_COLOR, ClientState};
|
||||||
|
use winit::{
|
||||||
|
dpi::PhysicalSize,
|
||||||
|
window::{Fullscreen, Window},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct Renderer<'a> {
|
||||||
|
size: PhysicalSize<u32>,
|
||||||
|
surface: wgpu::Surface<'a>,
|
||||||
|
device: wgpu::Device,
|
||||||
|
queue: wgpu::Queue,
|
||||||
|
config: wgpu::SurfaceConfiguration,
|
||||||
|
adapter: wgpu::Adapter,
|
||||||
|
encoder: Option<wgpu::CommandEncoder>,
|
||||||
|
staging_belt: wgpu::util::StagingBelt,
|
||||||
|
voxel_pipeline: VoxelPipeline,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Renderer<'a> {
|
||||||
|
pub fn new(window: Arc<Window>, fullscreen: bool) -> Self {
|
||||||
|
if fullscreen {
|
||||||
|
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let size = window.inner_size();
|
||||||
|
|
||||||
|
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||||
|
backends: wgpu::Backends::PRIMARY,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
let surface = instance
|
||||||
|
.create_surface(window)
|
||||||
|
.expect("Could not create window surface!");
|
||||||
|
|
||||||
|
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||||
|
power_preference: wgpu::PowerPreference::default(),
|
||||||
|
compatible_surface: Some(&surface),
|
||||||
|
force_fallback_adapter: false,
|
||||||
|
}))
|
||||||
|
.expect("Could not get adapter!");
|
||||||
|
|
||||||
|
let (device, queue) = pollster::block_on(adapter.request_device(
|
||||||
|
&wgpu::DeviceDescriptor {
|
||||||
|
label: None,
|
||||||
|
required_features: wgpu::Features::empty(),
|
||||||
|
required_limits: wgpu::Limits::default(),
|
||||||
|
},
|
||||||
|
None, // Trace path
|
||||||
|
))
|
||||||
|
.expect("Could not get device!");
|
||||||
|
|
||||||
|
// TODO: use a logger
|
||||||
|
let info = adapter.get_info();
|
||||||
|
println!("Adapter: {}", info.name);
|
||||||
|
println!("Backend: {:?}", info.backend);
|
||||||
|
|
||||||
|
let surface_caps = surface.get_capabilities(&adapter);
|
||||||
|
// Set surface format to srbg
|
||||||
|
let surface_format = surface_caps
|
||||||
|
.formats
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.find(|f| f.is_srgb())
|
||||||
|
.unwrap_or(surface_caps.formats[0]);
|
||||||
|
|
||||||
|
// create surface config
|
||||||
|
let config = wgpu::SurfaceConfiguration {
|
||||||
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||||
|
format: surface_format,
|
||||||
|
width: size.width,
|
||||||
|
height: size.height,
|
||||||
|
present_mode: surface_caps.present_modes[0],
|
||||||
|
alpha_mode: surface_caps.alpha_modes[0],
|
||||||
|
view_formats: vec![],
|
||||||
|
desired_maximum_frame_latency: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
surface.configure(&device, &config);
|
||||||
|
// not exactly sure what this number should be,
|
||||||
|
// doesn't affect performance much and depends on "normal" zoom
|
||||||
|
let staging_belt = wgpu::util::StagingBelt::new(4096 * 4);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
size,
|
||||||
|
voxel_pipeline: VoxelPipeline::new(&device, &config.format),
|
||||||
|
encoder: None,
|
||||||
|
staging_belt,
|
||||||
|
surface,
|
||||||
|
device,
|
||||||
|
adapter,
|
||||||
|
config,
|
||||||
|
queue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_encoder(&mut self) -> wgpu::CommandEncoder {
|
||||||
|
self.device
|
||||||
|
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||||
|
label: Some("Render Encoder"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw(&mut self) {
|
||||||
|
let output = self.surface.get_current_texture().unwrap();
|
||||||
|
let view = output
|
||||||
|
.texture
|
||||||
|
.create_view(&wgpu::TextureViewDescriptor::default());
|
||||||
|
let mut encoder = self.encoder.take().unwrap_or(self.create_encoder());
|
||||||
|
{
|
||||||
|
let render_pass = &mut encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||||
|
label: Some("Render Pass"),
|
||||||
|
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||||
|
view: &view,
|
||||||
|
resolve_target: None,
|
||||||
|
ops: wgpu::Operations {
|
||||||
|
load: wgpu::LoadOp::Clear(CLEAR_COLOR),
|
||||||
|
store: wgpu::StoreOp::Store,
|
||||||
|
},
|
||||||
|
})],
|
||||||
|
depth_stencil_attachment: None,
|
||||||
|
timestamp_writes: None,
|
||||||
|
occlusion_query_set: None,
|
||||||
|
});
|
||||||
|
self.voxel_pipeline.draw(render_pass);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.staging_belt.finish();
|
||||||
|
self.queue.submit(std::iter::once(encoder.finish()));
|
||||||
|
output.present();
|
||||||
|
self.staging_belt.recall();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&mut self, state: &ClientState) {
|
||||||
|
let mut encoder = self
|
||||||
|
.device
|
||||||
|
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||||
|
label: Some("Render Encoder"),
|
||||||
|
});
|
||||||
|
self.voxel_pipeline.update(
|
||||||
|
&self.device,
|
||||||
|
&mut encoder,
|
||||||
|
&mut self.staging_belt,
|
||||||
|
&mut self.queue,
|
||||||
|
&RenderUpdateData {
|
||||||
|
state,
|
||||||
|
size: &self.size,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
self.encoder = Some(encoder);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resize(&mut self, size: PhysicalSize<u32>) {
|
||||||
|
self.size = size;
|
||||||
|
self.config.width = size.width;
|
||||||
|
self.config.height = size.height;
|
||||||
|
self.surface.configure(&self.device, &self.config);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn size(&self) -> &PhysicalSize<u32> {
|
||||||
|
&self.size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RenderUpdateData<'a> {
|
||||||
|
pub state: &'a ClientState,
|
||||||
|
pub size: &'a PhysicalSize<u32>,
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
use super::buf::{ArrBuf, ArrBufUpdate, BufMove};
|
||||||
|
use wgpu::BufferUsages;
|
||||||
|
|
||||||
|
pub struct Storage<T: bytemuck::Pod + PartialEq> {
|
||||||
|
binding: u32,
|
||||||
|
buf: ArrBuf<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: PartialEq + bytemuck::Pod> Storage<T> {
|
||||||
|
pub fn init(device: &wgpu::Device, label: &str, binding: u32) -> Self {
|
||||||
|
Self {
|
||||||
|
buf: ArrBuf::init(
|
||||||
|
device,
|
||||||
|
&(label.to_owned() + " Storage"),
|
||||||
|
BufferUsages::STORAGE,
|
||||||
|
),
|
||||||
|
binding,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: PartialEq + bytemuck::Pod> Storage<T> {
|
||||||
|
pub fn bind_group_layout_entry(&self) -> wgpu::BindGroupLayoutEntry {
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: self.binding,
|
||||||
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Buffer {
|
||||||
|
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||||
|
has_dynamic_offset: false,
|
||||||
|
min_binding_size: None,
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn bind_group_entry(&self) -> wgpu::BindGroupEntry {
|
||||||
|
return wgpu::BindGroupEntry {
|
||||||
|
binding: self.binding,
|
||||||
|
resource: self.buf.buffer().as_entire_binding(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
pub fn update(
|
||||||
|
&mut self,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
encoder: &mut wgpu::CommandEncoder,
|
||||||
|
belt: &mut wgpu::util::StagingBelt,
|
||||||
|
size: usize,
|
||||||
|
updates: &[ArrBufUpdate<T>],
|
||||||
|
) -> bool {
|
||||||
|
self.buf.update(device, encoder, belt, size, updates)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mov(&mut self, mov: BufMove) {
|
||||||
|
self.buf.mov(mov);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
use wgpu::util::DeviceExt;
|
||||||
|
|
||||||
|
use super::RenderUpdateData;
|
||||||
|
|
||||||
|
pub trait UniformData {
|
||||||
|
fn update(&mut self, data: &RenderUpdateData) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Uniform<T: bytemuck::Pod + PartialEq + UniformData> {
|
||||||
|
data: T,
|
||||||
|
buffer: wgpu::Buffer,
|
||||||
|
binding: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Default + PartialEq + bytemuck::Pod + UniformData> Uniform<T> {
|
||||||
|
pub fn init(device: &wgpu::Device, name: &str, binding: u32) -> Self {
|
||||||
|
let data = T::default();
|
||||||
|
Self {
|
||||||
|
data,
|
||||||
|
buffer: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some(&(name.to_owned() + " Uniform Buf")),
|
||||||
|
contents: bytemuck::cast_slice(&[data]),
|
||||||
|
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||||
|
}),
|
||||||
|
binding,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: PartialEq + bytemuck::Pod + UniformData> Uniform<T> {
|
||||||
|
pub fn bind_group_layout_entry(&self) -> wgpu::BindGroupLayoutEntry {
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: self.binding,
|
||||||
|
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Buffer {
|
||||||
|
ty: wgpu::BufferBindingType::Uniform,
|
||||||
|
has_dynamic_offset: false,
|
||||||
|
min_binding_size: None,
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn bind_group_entry(&self) -> wgpu::BindGroupEntry {
|
||||||
|
return wgpu::BindGroupEntry {
|
||||||
|
binding: self.binding,
|
||||||
|
resource: self.buffer.as_entire_binding(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
pub fn update(
|
||||||
|
&mut self,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
encoder: &mut wgpu::CommandEncoder,
|
||||||
|
belt: &mut wgpu::util::StagingBelt,
|
||||||
|
update_data: &RenderUpdateData,
|
||||||
|
) {
|
||||||
|
if self.data.update(update_data) {
|
||||||
|
let slice = &[self.data];
|
||||||
|
let mut view = belt.write_buffer(
|
||||||
|
encoder,
|
||||||
|
&self.buffer,
|
||||||
|
0,
|
||||||
|
unsafe {
|
||||||
|
std::num::NonZeroU64::new_unchecked(
|
||||||
|
(slice.len() * std::mem::size_of::<T>()) as u64,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
device,
|
||||||
|
);
|
||||||
|
view.copy_from_slice(bytemuck::cast_slice(slice));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
#[repr(C)]
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, bytemuck::Zeroable, bytemuck::Pod)]
|
||||||
|
pub struct VoxelColor {
|
||||||
|
pub r: u8,
|
||||||
|
pub g: u8,
|
||||||
|
pub b: u8,
|
||||||
|
pub a: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VoxelColor {
|
||||||
|
pub fn none() -> Self {
|
||||||
|
Self {
|
||||||
|
r: 0,
|
||||||
|
g: 0,
|
||||||
|
b: 0,
|
||||||
|
a: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn black() -> Self {
|
||||||
|
Self {
|
||||||
|
r: 0,
|
||||||
|
g: 0,
|
||||||
|
b: 0,
|
||||||
|
a: 255,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn white() -> Self {
|
||||||
|
Self {
|
||||||
|
r: 255,
|
||||||
|
g: 255,
|
||||||
|
b: 255,
|
||||||
|
a: 255,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
use nalgebra::Matrix4x3;
|
||||||
|
|
||||||
|
// this has cost me more than a couple of hours trying to figure out alignment :skull:
|
||||||
|
// putting transform at the beginning so I don't have to deal with its alignment
|
||||||
|
// I should probably look into encase (crate)
|
||||||
|
#[repr(C, align(16))]
|
||||||
|
#[derive(Clone, Copy, PartialEq, bytemuck::Zeroable)]
|
||||||
|
pub struct GridInfo {
|
||||||
|
pub transform: Matrix4x3<f32>,
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl bytemuck::Pod for GridInfo {}
|
||||||
|
|
||||||
|
impl Default for GridInfo {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
transform: Matrix4x3::identity(),
|
||||||
|
width: 0,
|
||||||
|
height: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
mod grid;
|
||||||
|
mod view;
|
||||||
|
mod pipeline;
|
||||||
|
mod color;
|
||||||
|
|
||||||
|
pub use pipeline::*;
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
use super::{color::VoxelColor, view::View};
|
||||||
|
use crate::client::render::{
|
||||||
|
buf::ArrBufUpdate, storage::Storage, uniform::Uniform, RenderUpdateData,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct VoxelPipeline {
|
||||||
|
pipeline: wgpu::RenderPipeline,
|
||||||
|
view: Uniform<View>,
|
||||||
|
bind_group_layout: wgpu::BindGroupLayout,
|
||||||
|
bind_group: wgpu::BindGroup,
|
||||||
|
texture: wgpu::Texture,
|
||||||
|
voxels: Storage<VoxelColor>,
|
||||||
|
arst: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
const WIDTH: u32 = 300;
|
||||||
|
const HEIGHT: u32 = 300;
|
||||||
|
|
||||||
|
impl VoxelPipeline {
|
||||||
|
pub fn new(device: &wgpu::Device, format: &wgpu::TextureFormat) -> Self {
|
||||||
|
// shaders
|
||||||
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||||
|
label: Some("Tile Shader"),
|
||||||
|
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
|
||||||
|
});
|
||||||
|
|
||||||
|
let view = Uniform::<View>::init(device, "View", 0);
|
||||||
|
let texture_size = wgpu::Extent3d {
|
||||||
|
width: WIDTH,
|
||||||
|
height: HEIGHT,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
};
|
||||||
|
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||||
|
size: texture_size,
|
||||||
|
mip_level_count: 1,
|
||||||
|
sample_count: 1,
|
||||||
|
dimension: wgpu::TextureDimension::D2,
|
||||||
|
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||||
|
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||||
|
label: Some("diffuse_texture"),
|
||||||
|
view_formats: &[],
|
||||||
|
});
|
||||||
|
let voxels = Storage::init(device, "voxels", 3);
|
||||||
|
|
||||||
|
let diffuse_texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||||
|
let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||||
|
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||||
|
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||||
|
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||||
|
mag_filter: wgpu::FilterMode::Linear,
|
||||||
|
min_filter: wgpu::FilterMode::Nearest,
|
||||||
|
mipmap_filter: wgpu::FilterMode::Nearest,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
// bind groups
|
||||||
|
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
|
entries: &[
|
||||||
|
view.bind_group_layout_entry(),
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 1,
|
||||||
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Texture {
|
||||||
|
multisampled: false,
|
||||||
|
view_dimension: wgpu::TextureViewDimension::D2,
|
||||||
|
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 2,
|
||||||
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||||
|
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
voxels.bind_group_layout_entry(),
|
||||||
|
],
|
||||||
|
label: Some("tile_bind_group_layout"),
|
||||||
|
});
|
||||||
|
|
||||||
|
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
|
layout: &bind_group_layout,
|
||||||
|
entries: &[
|
||||||
|
view.bind_group_entry(),
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 1,
|
||||||
|
resource: wgpu::BindingResource::TextureView(&diffuse_texture_view),
|
||||||
|
},
|
||||||
|
wgpu::BindGroupEntry {
|
||||||
|
binding: 2,
|
||||||
|
resource: wgpu::BindingResource::Sampler(&diffuse_sampler),
|
||||||
|
},
|
||||||
|
voxels.bind_group_entry(),
|
||||||
|
],
|
||||||
|
label: Some("tile_bind_group"),
|
||||||
|
});
|
||||||
|
|
||||||
|
// pipeline
|
||||||
|
let render_pipeline_layout =
|
||||||
|
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||||
|
label: Some("Tile Pipeline Layout"),
|
||||||
|
bind_group_layouts: &[&bind_group_layout],
|
||||||
|
push_constant_ranges: &[],
|
||||||
|
});
|
||||||
|
|
||||||
|
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
|
label: Some("Voxel Pipeline"),
|
||||||
|
layout: Some(&render_pipeline_layout),
|
||||||
|
vertex: wgpu::VertexState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "vs_main",
|
||||||
|
buffers: &[],
|
||||||
|
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||||
|
},
|
||||||
|
fragment: Some(wgpu::FragmentState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "fs_main",
|
||||||
|
targets: &[Some(wgpu::ColorTargetState {
|
||||||
|
format: *format,
|
||||||
|
blend: Some(wgpu::BlendState::REPLACE),
|
||||||
|
write_mask: wgpu::ColorWrites::ALL,
|
||||||
|
})],
|
||||||
|
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||||
|
}),
|
||||||
|
primitive: wgpu::PrimitiveState {
|
||||||
|
topology: wgpu::PrimitiveTopology::TriangleStrip,
|
||||||
|
strip_index_format: None,
|
||||||
|
front_face: wgpu::FrontFace::Ccw,
|
||||||
|
cull_mode: None,
|
||||||
|
polygon_mode: wgpu::PolygonMode::Fill,
|
||||||
|
unclipped_depth: false,
|
||||||
|
conservative: false,
|
||||||
|
},
|
||||||
|
depth_stencil: None,
|
||||||
|
multisample: wgpu::MultisampleState {
|
||||||
|
count: 1,
|
||||||
|
mask: !0,
|
||||||
|
alpha_to_coverage_enabled: true,
|
||||||
|
},
|
||||||
|
multiview: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
Self {
|
||||||
|
pipeline: render_pipeline,
|
||||||
|
view,
|
||||||
|
bind_group,
|
||||||
|
bind_group_layout,
|
||||||
|
texture,
|
||||||
|
voxels,
|
||||||
|
arst: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(
|
||||||
|
&mut self,
|
||||||
|
device: &wgpu::Device,
|
||||||
|
encoder: &mut wgpu::CommandEncoder,
|
||||||
|
belt: &mut wgpu::util::StagingBelt,
|
||||||
|
queue: &mut wgpu::Queue,
|
||||||
|
update_data: &RenderUpdateData,
|
||||||
|
) {
|
||||||
|
let texture_size = wgpu::Extent3d {
|
||||||
|
width: WIDTH,
|
||||||
|
height: HEIGHT,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
};
|
||||||
|
if !self.arst {
|
||||||
|
queue.write_texture(
|
||||||
|
// Tells wgpu where to copy the pixel data
|
||||||
|
wgpu::ImageCopyTexture {
|
||||||
|
texture: &self.texture,
|
||||||
|
mip_level: 0,
|
||||||
|
origin: wgpu::Origin3d::ZERO,
|
||||||
|
aspect: wgpu::TextureAspect::All,
|
||||||
|
},
|
||||||
|
// The actual pixel data
|
||||||
|
&[0xff, 0x00, 0xff, 0xff].repeat((WIDTH * HEIGHT) as usize),
|
||||||
|
// The layout of the texture
|
||||||
|
wgpu::ImageDataLayout {
|
||||||
|
offset: 0,
|
||||||
|
bytes_per_row: Some(4 * WIDTH),
|
||||||
|
rows_per_image: Some(HEIGHT),
|
||||||
|
},
|
||||||
|
texture_size,
|
||||||
|
);
|
||||||
|
let l = 10;
|
||||||
|
let size = l * l * l;
|
||||||
|
let mut data: Vec<_> = vec![VoxelColor::none(); size];
|
||||||
|
data[0] = VoxelColor::white();
|
||||||
|
data[size - 1] = VoxelColor::white();
|
||||||
|
self.voxels.update(
|
||||||
|
device,
|
||||||
|
encoder,
|
||||||
|
belt,
|
||||||
|
data.len(),
|
||||||
|
&[ArrBufUpdate { offset: 0, data }],
|
||||||
|
);
|
||||||
|
self.arst = true;
|
||||||
|
}
|
||||||
|
self.view.update(device, encoder, belt, update_data);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
|
||||||
|
render_pass.set_pipeline(&self.pipeline);
|
||||||
|
render_pass.set_bind_group(0, &self.bind_group, &[]);
|
||||||
|
render_pass.draw(0..4, 0..1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// Vertex shader
|
||||||
|
|
||||||
|
struct VertexOutput {
|
||||||
|
@builtin(position) clip_position: vec4<f32>,
|
||||||
|
@location(0) tex_coords: vec2<f32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct View {
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
zoom: f32,
|
||||||
|
padding: u32,
|
||||||
|
transform: mat4x4<f32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
@group(0) @binding(0)
|
||||||
|
var<uniform> view: View;
|
||||||
|
@group(0) @binding(1)
|
||||||
|
var t_diffuse: texture_2d<f32>;
|
||||||
|
@group(0) @binding(2)
|
||||||
|
var s_diffuse: sampler;
|
||||||
|
@group(0) @binding(3)
|
||||||
|
var<storage, read> voxels: array<u32>;
|
||||||
|
|
||||||
|
@vertex
|
||||||
|
fn vs_main(
|
||||||
|
@builtin(vertex_index) vi: u32,
|
||||||
|
@builtin(instance_index) ii: u32,
|
||||||
|
) -> VertexOutput {
|
||||||
|
var out: VertexOutput;
|
||||||
|
|
||||||
|
var pos = vec2<f32>(
|
||||||
|
f32(vi % 2u) * 2.0 - 1.0,
|
||||||
|
f32(vi / 2u) * 2.0 - 1.0,
|
||||||
|
);
|
||||||
|
out.clip_position = vec4<f32>(pos.x, pos.y, 0.0, 1.0);
|
||||||
|
out.tex_coords = pos;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fragment shader
|
||||||
|
|
||||||
|
@fragment
|
||||||
|
fn fs_main(
|
||||||
|
in: VertexOutput,
|
||||||
|
) -> @location(0) vec4<f32> {
|
||||||
|
let aspect = f32(view.height) / f32(view.width);
|
||||||
|
var pixel_pos = vec3<f32>(in.clip_position.x / f32(view.width), 1.0 - in.clip_position.y / f32(view.height), 1.0);
|
||||||
|
pixel_pos.x -= 0.5;
|
||||||
|
pixel_pos.y -= 0.5;
|
||||||
|
pixel_pos.x *= 2.0;
|
||||||
|
pixel_pos.y *= 2.0;
|
||||||
|
pixel_pos.y *= aspect;
|
||||||
|
|
||||||
|
pixel_pos = (view.transform * vec4<f32>(pixel_pos, 1.0)).xyz;
|
||||||
|
let origin = (view.transform * vec4<f32>(0.0, 0.0, 0.0, 1.0)).xyz;
|
||||||
|
let dir = normalize(pixel_pos - origin);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
let voxel_pos = vec3<f32>(-5.0, -5.0, 30.0);
|
||||||
|
var t = 0;
|
||||||
|
for(t = 0; t < 1000; t += 1) {
|
||||||
|
let pos = pixel_pos + f32(t) * 0.1 * dir - voxel_pos;
|
||||||
|
let rel_coords = vec3<i32>(pos.xyz);
|
||||||
|
if rel_coords.x < 0 || rel_coords.y < 0 || rel_coords.z < 0 || rel_coords.x > 10 || rel_coords.y > 10 || rel_coords.z > 10 {
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
let i = rel_coords.x + rel_coords.y * 10 + rel_coords.z * 100;
|
||||||
|
let color = unpack4x8unorm(voxels[i]);
|
||||||
|
if voxels[i] != 0 {
|
||||||
|
return vec4<f32>(1.0);
|
||||||
|
} else {
|
||||||
|
let pos = vec3<f32>(rel_coords);
|
||||||
|
return vec4<f32>(pos.x / 10.0, pos.y / 10.0, pos.z / 10.0, 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return vec4<f32>(0.0, 0.0, 0.0, 1.0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
use nalgebra::{Transform3, Translation3};
|
||||||
|
|
||||||
|
use crate::client::render::uniform::UniformData;
|
||||||
|
|
||||||
|
#[repr(C, align(16))]
|
||||||
|
#[derive(Clone, Copy, PartialEq, bytemuck::Zeroable)]
|
||||||
|
pub struct View {
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub zoom: f32,
|
||||||
|
pub padding: u32,
|
||||||
|
pub transform: Transform3<f32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl bytemuck::Pod for View {}
|
||||||
|
|
||||||
|
impl Default for View {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
width: 1,
|
||||||
|
height: 1,
|
||||||
|
zoom: 1.0,
|
||||||
|
padding: 0,
|
||||||
|
transform: Transform3::identity(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UniformData for View {
|
||||||
|
fn update(&mut self, data: &crate::client::render::RenderUpdateData) -> bool {
|
||||||
|
let camera = data.state.camera;
|
||||||
|
let new = Transform3::identity() * Translation3::from(camera.pos) * camera.orientation;
|
||||||
|
if new == self.transform
|
||||||
|
&& data.size.width == self.width
|
||||||
|
&& data.size.height == self.height
|
||||||
|
&& camera.scale == self.zoom
|
||||||
|
{
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
*self = Self {
|
||||||
|
width: data.size.width,
|
||||||
|
height: data.size.height,
|
||||||
|
zoom: camera.scale,
|
||||||
|
padding: 0,
|
||||||
|
transform: new,
|
||||||
|
};
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
pub const FPS: u32 = 30;
|
||||||
|
pub const FRAME_TIME: Duration = Duration::from_millis(1000 / FPS as u64);
|
||||||
|
|
||||||
|
pub const CLEAR_COLOR: wgpu::Color = wgpu::Color {
|
||||||
|
r: 0.1,
|
||||||
|
g: 0.1,
|
||||||
|
b: 0.1,
|
||||||
|
a: 1.0,
|
||||||
|
};
|
||||||
|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
use super::camera::Camera;
|
||||||
|
|
||||||
|
pub struct ClientState {
|
||||||
|
pub camera: Camera,
|
||||||
|
pub camera_scroll: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientState {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
camera: Camera::default(),
|
||||||
|
camera_scroll: 0.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use winit::{
|
||||||
|
application::ApplicationHandler, event::WindowEvent, event_loop::ControlFlow,
|
||||||
|
window::WindowAttributes,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{render::Renderer, Client};
|
||||||
|
|
||||||
|
impl ApplicationHandler for Client<'_> {
|
||||||
|
fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
|
||||||
|
if self.window.is_none() {
|
||||||
|
let window = Arc::new(
|
||||||
|
event_loop
|
||||||
|
.create_window(WindowAttributes::default())
|
||||||
|
.expect("Failed to create window"),
|
||||||
|
);
|
||||||
|
self.renderer = Some(Renderer::new(window.clone(), false));
|
||||||
|
self.window = Some(window);
|
||||||
|
self.start();
|
||||||
|
}
|
||||||
|
event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(
|
||||||
|
&mut self,
|
||||||
|
_event_loop: &winit::event_loop::ActiveEventLoop,
|
||||||
|
_window_id: winit::window::WindowId,
|
||||||
|
event: WindowEvent,
|
||||||
|
) {
|
||||||
|
let renderer = self.renderer.as_mut().unwrap();
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested => self.exit = true,
|
||||||
|
WindowEvent::Resized(size) => renderer.resize(size),
|
||||||
|
WindowEvent::RedrawRequested => renderer.draw(),
|
||||||
|
_ => self.input.update_window(event),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device_event(
|
||||||
|
&mut self,
|
||||||
|
_event_loop: &winit::event_loop::ActiveEventLoop,
|
||||||
|
_device_id: winit::event::DeviceId,
|
||||||
|
event: winit::event::DeviceEvent,
|
||||||
|
) {
|
||||||
|
self.input.update_device(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn about_to_wait(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
|
||||||
|
if self.update() {
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
use client::Client;
|
||||||
|
use winit::event_loop::EventLoop;
|
||||||
|
|
||||||
|
mod client;
|
||||||
|
mod util;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let event_loop = EventLoop::new().expect("Failed to create event loop");
|
||||||
|
event_loop
|
||||||
|
.run_app(&mut Client::new())
|
||||||
|
.expect("Failed to run event loop");
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
use nalgebra::{Matrix4x3, Point2, Projective2, Transform2, Vector2, Vector3};
|
||||||
|
|
||||||
|
pub type Vec2f = Vector2<f32>;
|
||||||
|
pub type Vec3f = Vector3<f32>;
|
||||||
|
pub type Pos2f = Point2<f32>;
|
||||||
|
pub type Vec2us = Vector2<usize>;
|
||||||
|
|
||||||
|
// hahaha.. HAHAHAAAAAAAAAAA... it's over now, surely I'll remember this lesson
|
||||||
|
pub trait Bruh<T> {
|
||||||
|
fn gpu_mat3(&self) -> Matrix4x3<T>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Bruh<f32> for Transform2<f32> {
|
||||||
|
fn gpu_mat3(&self) -> Matrix4x3<f32> {
|
||||||
|
let mut a = Matrix4x3::identity();
|
||||||
|
// I LOVE GPU DATA STRUCTURE ALIGNMENT (it makes sense tho)
|
||||||
|
a.view_mut((0,0), (3,3)).copy_from(self.matrix());
|
||||||
|
a
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Bruh<f32> for Projective2<f32> {
|
||||||
|
fn gpu_mat3(&self) -> Matrix4x3<f32> {
|
||||||
|
let mut a = Matrix4x3::identity();
|
||||||
|
// I LOVE GPU DATA STRUCTURE ALIGNMENT (it makes sense tho)
|
||||||
|
a.view_mut((0,0), (3,3)).copy_from(self.matrix());
|
||||||
|
a
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod swap_buf;
|
||||||
|
pub mod math;
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
use std::ops::{Deref, DerefMut, Add};
|
||||||
|
|
||||||
|
pub struct SwapBuffer<T> {
|
||||||
|
read: Vec<T>,
|
||||||
|
write: Vec<T>,
|
||||||
|
modify: Vec<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Default + Copy + Clone + Add<Output = T>> SwapBuffer<T> {
|
||||||
|
pub fn new(size: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
read: vec![T::default(); size],
|
||||||
|
write: vec![T::default(); size],
|
||||||
|
modify: vec![T::default(); size],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn swap(&mut self) {
|
||||||
|
std::mem::swap(&mut self.read, &mut self.write);
|
||||||
|
for (m, r) in self.modify.iter_mut().zip(&mut self.read) {
|
||||||
|
*r = *r + *m;
|
||||||
|
*m = T::default();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rwm(&mut self) -> (&mut Vec<T>, &mut Vec<T>, &mut Vec<T>) {
|
||||||
|
(&mut self.read, &mut self.write, &mut self.modify)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Deref for SwapBuffer<T> {
|
||||||
|
type Target = Vec<T>;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.read
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> DerefMut for SwapBuffer<T> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.read
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
use crate::util::math::Vec2us;
|
||||||
|
use bevy_ecs::component::Component;
|
||||||
|
use nalgebra::{DMatrix, DimRange, Dyn};
|
||||||
|
use std::ops::{Deref, Range};
|
||||||
|
|
||||||
|
pub type GridRegion = (Range<usize>, Range<usize>);
|
||||||
|
pub type GridView<'a, T> = nalgebra::Matrix<
|
||||||
|
T,
|
||||||
|
Dyn,
|
||||||
|
Dyn,
|
||||||
|
nalgebra::ViewStorageMut<'a, T, Dyn, Dyn, nalgebra::Const<1>, Dyn>,
|
||||||
|
>;
|
||||||
|
|
||||||
|
#[derive(Clone, Component)]
|
||||||
|
pub struct TrackedGrid<T> {
|
||||||
|
data: DMatrix<T>,
|
||||||
|
changes: Vec<GridRegion>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> TrackedGrid<T> {
|
||||||
|
pub fn new(data: DMatrix<T>) -> Self {
|
||||||
|
Self {
|
||||||
|
data,
|
||||||
|
changes: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn width(&self) -> usize {
|
||||||
|
self.data.ncols()
|
||||||
|
}
|
||||||
|
pub fn height(&self) -> usize {
|
||||||
|
self.data.nrows()
|
||||||
|
}
|
||||||
|
pub fn view_range_mut<RowRange: DimRange<Dyn>, ColRange: DimRange<Dyn>>(
|
||||||
|
&mut self,
|
||||||
|
x_range: ColRange,
|
||||||
|
y_range: RowRange,
|
||||||
|
) -> GridView<'_, T> {
|
||||||
|
let shape = self.data.shape();
|
||||||
|
let r = Dyn(shape.0);
|
||||||
|
let rows = y_range.begin(r)..y_range.end(r);
|
||||||
|
let c = Dyn(shape.1);
|
||||||
|
let cols = x_range.begin(c)..x_range.end(c);
|
||||||
|
self.changes.push((rows.clone(), cols.clone()));
|
||||||
|
self.data.view_range_mut(rows, cols)
|
||||||
|
}
|
||||||
|
pub fn take_changes(&mut self) -> Vec<GridRegion> {
|
||||||
|
std::mem::replace(&mut self.changes, Vec::new())
|
||||||
|
}
|
||||||
|
pub fn change(&mut self, index: Vec2us) -> Option<&mut T> {
|
||||||
|
if let Some(d) = self.data.get_mut((index.y, index.x)) {
|
||||||
|
self.changes
|
||||||
|
.push((index.y..index.y + 1, index.x..index.x + 1));
|
||||||
|
Some(d)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Deref for TrackedGrid<T> {
|
||||||
|
type Target = DMatrix<T>;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pub fn tile_pos(&self, pos: Pos2f) -> Option<Vec2us> {
|
||||||
|
// let mut pos = self.orientation.inverse() * pos;
|
||||||
|
// pos += Vec2f::new(
|
||||||
|
// (self.size.x / 2) as f32 + 0.5,
|
||||||
|
// (self.size.y / 2) as f32 + 0.5,
|
||||||
|
// );
|
||||||
|
// if pos.x < 0.0 || pos.y < 0.0 {
|
||||||
|
// return None;
|
||||||
|
// }
|
||||||
|
// let truncated = Vec2us::new(pos.x as usize, pos.y as usize);
|
||||||
|
// if truncated.x > self.size.x - 1 || truncated.y > self.size.y - 1 {
|
||||||
|
// return None;
|
||||||
|
// }
|
||||||
|
// Some(truncated)
|
||||||
|
// }
|
||||||
Reference in new issue
Block a user