branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>
<?php
echo "Muthiana";
echo "qualquer coisa";
echo "Shelia";
echo "hello testing";
<!--
/*
* Author:<NAME>
* Author URI: http://coders.muthiana.org
* Company:Muthiana;
* Company URI:http://muthiana.org
* Description:Application for domestic violence
* Copyright:2017 (c)
*/
?>
-->
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="utf-8">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible", content="IE=edge">
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css">
<link rel="stylesheet" type="text/css" href="static/stylesheet/libraries/bootstrap/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="static/stylesheet/main.css">
<!-- leafletjs map css -->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="<KEY>
crossorigin=""/>
<!-- leafletjs map css -->
<!-- stylesheets -->
<!-- scripts -->
<!-- leafletjs map javascript -->
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="<KEY>
crossorigin=""></script>
<!-- leafletjs map javascript -->
<script type="text/javascript" src="../../static/javascript/app.js"></script>
<!-- scripts -->
<title>Home</title>
</head>
<body>
<header>
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Muthianas</a>
<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
<ul class="nav navbar-nav navbar-right">
<li class="nav-item">
<a class="nav-link" href="#">ajuda</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">sobre</a>
</li>
</ul>
</div>
</nav>
</header>
<nav>
<ul class="sub-menu">
<button type="button" class="float-left btn btn-primary"><a href="">denucia</a></button>
<button type="button" class="float-right btn btn-primary"><a href="views/pages/violencia.php">ver violencia</a></button>
</nav>
<div id="mapid"></div>
</body>
</html>
|
e91cff9420a25b59bc29791179ee751d2a7b5eb9
|
[
"PHP"
] | 1 |
PHP
|
rodinha/vcmApp
|
9b9369949e063d161041ae8e27d48dafc9b95245
|
2fb8601f77aafe54fd0f724716c91795125b8088
|
refs/heads/master
|
<repo_name>SonarSystems/Frogger-SFML-OOP-Example<file_sep>/Code/Tutorial 004 - Becoming OOP Part 3 - Inheritance/Truck.cpp
#include "Truck.hpp"
Truck::Truck(sf::Vector2u size, float posX, float posY)
{
shape.setSize(sf::Vector2f(120, 60));
shape.setFillColor(sf::Color::Red);
shape.setPosition(sf::Vector2f(posX, posY));
originalPosX = posX;
originalPosY = posY;
}
Truck::~Truck()
{
}
void Truck::Move(sf::Vector2u size)
{
shape.move(0.2, 0);
if (shape.getPosition().x > size.x)
{
shape.setPosition(sf::Vector2f(0 - shape.getSize().x, originalPosY));
}
}
<file_sep>/Code/Tutorial 004 - Becoming OOP Part 3 - Inheritance/Game.cpp
#include "Game.hpp"
Game::Game()
{
window = new sf::RenderWindow(sf::VideoMode(640, 480), "SFML Starter Template");
frog = new Frog(window->getSize());
truck = new Truck(window->getSize(), 0, window->getSize().y / 2);
}
Game::~Game()
{
}
void Game::Loop()
{
while (window->isOpen())
{
// handle events
sf::Event event;
while (window->pollEvent(event))
{
switch (event.type)
{
case sf::Event::KeyReleased:
frog->Move(event);
break;
default:
break;
}
}
// update
truck->Move(window->getSize());
if (frog->GetShape().getGlobalBounds().intersects(truck->GetShape().getGlobalBounds()))
{
window->close();
}
window->clear();
// draw SFML content
frog->Draw(*window);
truck->Draw(*window);
window->display();
}
}
<file_sep>/Code/Tutorial 005 - Removing Magic Numbers and Hard Coded Values/DEFINITIONS.hpp
#pragma once
#define FROG_MOVEMENT_AMOUNT 80
#define FROG_SIZE_WIDTH 80
#define FROG_SIZE_HEIGHT 80
#define TRUCK_MOVEMENT_SPEED 0.2
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
#define WINDOW_TITLE "SFML Starter Template"
<file_sep>/Code/Tutorial 002 - Becoming OOP Part 1 - Class Introduction/Truck.hpp
#pragma once
#include <SFML/Graphics.hpp>
class Truck
{
public:
Truck(sf::Vector2u size, float posX, float posY);
~Truck();
void Draw(sf::RenderWindow &window);
void Move(sf::Vector2u size);
sf::RectangleShape GetShape();
private:
sf::RectangleShape truck;
float originalPosX, originalPosY;
};
<file_sep>/README.md
# Frogger SFML OOP Example
This is a simple example of creating the classic Frogger game and making it Object Oriented.<br />
<file_sep>/Code/Tutorial 002 - Becoming OOP Part 1 - Class Introduction/main.cpp
#include <SFML/Graphics.hpp>
#include "Frog.hpp"
#include "Truck.hpp"
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML Starter Template");
Frog frog(window.getSize());
Truck truck(window.getSize(), 0, window.getSize().y / 2);
while (window.isOpen())
{
// handle events
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::KeyReleased:
frog.Move(event);
break;
default:
break;
}
}
// update
truck.Move(window.getSize());
if (frog.GetShape().getGlobalBounds().intersects(truck.GetShape().getGlobalBounds()))
{
window.close();
}
window.clear();
// draw SFML content
frog.Draw(window);
truck.Draw(window);
window.display();
}
return EXIT_SUCCESS;
}
<file_sep>/Code/Tutorial 005 - Removing Magic Numbers and Hard Coded Values/BaseObject.cpp
#include "BaseObject.hpp"
BaseObject::BaseObject()
{
}
BaseObject::~BaseObject()
{
}
void BaseObject::Draw(sf::RenderWindow &window)
{
window.draw(shape);
}
sf::RectangleShape BaseObject::GetShape()
{
return shape;
}<file_sep>/Code/Tutorial 004 - Becoming OOP Part 3 - Inheritance/BaseObject.hpp
#pragma once
#include <SFML/Graphics.hpp>
class BaseObject
{
public:
BaseObject();
~BaseObject();
void Draw(sf::RenderWindow &window);
sf::RectangleShape GetShape();
protected:
sf::RectangleShape shape;
};
<file_sep>/Code/Tutorial 005 - Removing Magic Numbers and Hard Coded Values/Frog.cpp
#include "Frog.hpp"
Frog::Frog(sf::Vector2u size)
{
shape.setSize(sf::Vector2f(FROG_SIZE_WIDTH, FROG_SIZE_HEIGHT));
shape.setPosition(sf::Vector2f(shape.getPosition().x, size.y - shape.getSize().y));
}
Frog::~Frog()
{
}
void Frog::Move(sf::Event event)
{
if (sf::Keyboard::Key::Left == event.key.code)
{
shape.move(-FROG_MOVEMENT_AMOUNT, 0);
}
else if (sf::Keyboard::Key::Right == event.key.code)
{
shape.move(FROG_MOVEMENT_AMOUNT, 0);
}
else if (sf::Keyboard::Key::Up == event.key.code)
{
shape.move(0, -FROG_MOVEMENT_AMOUNT);
}
else if (sf::Keyboard::Key::Down == event.key.code)
{
shape.move(0, FROG_MOVEMENT_AMOUNT);
}
}
<file_sep>/Code/Tutorial 005 - Removing Magic Numbers and Hard Coded Values/Frog.hpp
#pragma once
#include <SFML/Graphics.hpp>
#include "BaseObject.hpp"
#include "DEFINITIONS.hpp"
class Frog : public BaseObject
{
public:
Frog(sf::Vector2u size);
~Frog();
void Move(sf::Event event);
private:
};
<file_sep>/Code/Tutorial 001 - Basic Single File Example/main.cpp
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML Starter Template");
sf::RectangleShape frog;
frog.setSize(sf::Vector2f(80, 80));
frog.setPosition(sf::Vector2f(frog.getPosition().x, window.getSize().y - frog.getSize().y));
sf::RectangleShape truck;
truck.setSize(sf::Vector2f(120, 60));
truck.setFillColor(sf::Color::Red);
truck.setPosition(sf::Vector2f(truck.getPosition().x, window.getSize().y / 2 - truck.getSize().y));
while (window.isOpen())
{
// handle events
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::KeyReleased:
if (sf::Keyboard::Key::Left == event.key.code)
{
frog.move(-80, 0);
}
else if (sf::Keyboard::Key::Right == event.key.code)
{
frog.move(80, 0);
}
else if (sf::Keyboard::Key::Up == event.key.code)
{
frog.move(0, -80);
}
else if (sf::Keyboard::Key::Down == event.key.code)
{
frog.move(0, 80);
}
}
}
// update
truck.move(0.2, 0);
if (truck.getPosition().x > window.getSize().x)
{
truck.setPosition(sf::Vector2f(-truck.getSize().x, window.getSize().y / 2 - truck.getSize().y));
}
if (frog.getGlobalBounds().intersects(truck.getGlobalBounds()))
{
window.close();
}
window.clear();
// draw SFML content
window.draw(frog);
window.draw(truck);
window.display();
}
return EXIT_SUCCESS;
}
<file_sep>/Code/Tutorial 002 - Becoming OOP Part 1 - Class Introduction/Frog.hpp
#pragma once
#include <SFML/Graphics.hpp>
class Frog
{
public:
Frog(sf::Vector2u size);
~Frog();
void Draw(sf::RenderWindow &window);
void Move(sf::Event event);
sf::RectangleShape GetShape();
private:
sf::RectangleShape frog;
};
<file_sep>/Code/Tutorial 003 - Becoming OOP Part 2 - Game Class/Truck.cpp
#include "Truck.hpp"
Truck::Truck(sf::Vector2u size, float posX, float posY)
{
truck.setSize(sf::Vector2f(120, 60));
truck.setFillColor(sf::Color::Red);
truck.setPosition(sf::Vector2f(posX, posY));
originalPosX = posX;
originalPosY = posY;
}
Truck::~Truck()
{
}
void Truck::Draw(sf::RenderWindow &window)
{
window.draw(truck);
}
void Truck::Move(sf::Vector2u size)
{
truck.move(0.2, 0);
if (truck.getPosition().x > size.x)
{
truck.setPosition(sf::Vector2f(0 - truck.getSize().x, originalPosY));
}
}
sf::RectangleShape Truck::GetShape()
{
return truck;
}
<file_sep>/Code/Tutorial 004 - Becoming OOP Part 3 - Inheritance/Truck.hpp
#pragma once
#include <SFML/Graphics.hpp>
#include "BaseObject.hpp"
class Truck : public BaseObject
{
public:
Truck(sf::Vector2u size, float posX, float posY);
~Truck();
void Move(sf::Vector2u size);
private:
float originalPosX, originalPosY;
};
<file_sep>/Code/Tutorial 004 - Becoming OOP Part 3 - Inheritance/Frog.cpp
#include "Frog.hpp"
Frog::Frog(sf::Vector2u size)
{
shape.setSize(sf::Vector2f(80, 80));
shape.setPosition(sf::Vector2f(shape.getPosition().x, size.y - shape.getSize().y));
}
Frog::~Frog()
{
}
void Frog::Move(sf::Event event)
{
if (sf::Keyboard::Key::Left == event.key.code)
{
shape.move(-80, 0);
}
else if (sf::Keyboard::Key::Right == event.key.code)
{
shape.move(80, 0);
}
else if (sf::Keyboard::Key::Up == event.key.code)
{
shape.move(0, -80);
}
else if (sf::Keyboard::Key::Down == event.key.code)
{
shape.move(0, 80);
}
}
<file_sep>/Code/Tutorial 005 - Removing Magic Numbers and Hard Coded Values/Game.hpp
#pragma once
#include <SFML/Graphics.hpp>
#include "Frog.hpp"
#include "Truck.hpp"
#include "DEFINITIONS.hpp"
class Game
{
public:
Game();
~Game();
void Loop();
private:
sf::RenderWindow *window;
Frog *frog;
Truck *truck;
};
|
9e66542e5247d0eabe4b0d06895f06def88d3bd5
|
[
"Markdown",
"C++"
] | 16 |
C++
|
SonarSystems/Frogger-SFML-OOP-Example
|
93a5abc82d4e51cdb21149cb8cc8861206ce6041
|
f8b81965d0b6018e498e91ddcaed3327ec2250a8
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Case extends Component {
render() {
const { caseNum } = this.props.case;
return this.props.initialCaseNum !== caseNum
&& !this.props.caseOpened ?
<button
onClick={this.props.chooseCase.bind(this, caseNum)}>
{this.props.caseNum}
</button>
:
<button>
{' '}
</button>
}
}
Case.propTypes = {
case: PropTypes.object.isRequired,
// Required for displaying the cases in order. this.props.case
// is from the SHUFFLED cases array in App, so relying on that
// to display the cases will result in the cases being in a random order.
caseNum: PropTypes.number.isRequired,
chooseCase: PropTypes.func.isRequired,
initialCaseNum: PropTypes.number.isRequired,
caseOpened: PropTypes.bool.isRequired,
};
export default Case;
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
class TurnInfo extends Component {
render() {
if (this.props.initialCaseNum === 0) {
return (
<div className="turn-info">
<h2>Please choose the case you wish to keep.</h2>
</div>
);
}
if (this.props.numCasesToChoose !== 0) {
return (
<div className="turn-info">
<h2>Your case: {this.props.initialCaseNum}</h2>
<p>Please choose {this.props.numCasesToChoose} more case(s)</p>
</div>
);
}
if (this.props.finalOfferMade
&& this.props.numCasesRemaining === 1) {
return (
<div className="turn-info">
<h2>Would you like to keep your case (case #{this.props.initialCaseNum}),
or would you like to swap your case for the last remaining case?
</h2>
<button onClick={this.props.keepCase}>Keep</button> <button onClick={this.props.swapCase}>Swap</button>
</div>
);
}
return (
<div className="turn-info">
<h2>Offer: {this.props.formatMoney(this.props.offer)}</h2>
<button onClick={this.props.acceptDeal}>Deal</button>or<button onClick={this.props.rejectDeal}>No Deal?</button>
</div>
);
}
}
TurnInfo.propTypes = {
numCasesToChoose: PropTypes.number.isRequired,
initialCaseNum: PropTypes.number.isRequired,
offer: PropTypes.string.isRequired,
acceptDeal: PropTypes.func.isRequired,
rejectDeal: PropTypes.func.isRequired,
numCasesRemaining: PropTypes.number.isRequired,
keepCase: PropTypes.func.isRequired,
swapCase: PropTypes.func.isRequired,
formatMoney: PropTypes.func.isRequired,
finalOfferMade: PropTypes.bool.isRequired,
};
export default TurnInfo;
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Case from './Case';
class Cases extends Component {
render() {
let caseElements = [];
for (let i = 0; i < this.props.cases.length; ++i) {
caseElements.push(<Case key={i}
case={this.props.cases[i]}
caseNum={i + 1}
chooseCase={this.props.chooseCase}
initialCaseNum={this.props.initialCaseNum}
caseOpened={this.props.cases[i].opened} />);
if (i % 5 === 0 && i !== 0) {
caseElements.push(<br key={i * 10}/>);
}
}
return caseElements.map(element => element);
}
}
Cases.propTypes = {
cases: PropTypes.array.isRequired,
};
export default Cases;
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
class ValuesTableCell extends Component {
render() {
const caseValue = this.props.case.value;
let caseValueString = caseValue === 0.01 ?
"$0.01" : this.props.formatMoney(caseValue, 0);
return this.props.case.opened ?
<td className="values-table-cell" style={{backgroundColor: "#888"}}>
{caseValueString}
</td> :
<td className="values-table-cell" style={{backgroundColor: "#ff6"}}>
{caseValueString}
</td>
}
}
ValuesTableCell.propTypes = {
case: PropTypes.object.isRequired,
formatMoney: PropTypes.func.isRequired,
};
export default ValuesTableCell;
<file_sep>import React, { Component } from 'react';
import Cases from './components/Cases';
import ValuesTable from './components/ValuesTable';
import Header from './components/Header';
import TurnInfo from './components/TurnInfo';
import './App.css';
const CASE_VALUES = [0.01, 1, 5, 10, 25, 50, 75, 100,
200, 300, 400, 500, 750, 1000, 5000, 10000, 25000, 50000,
75000, 100000, 200000, 300000, 400000, 500000, 750000, 1000000];
const ORIGINAL_NUM_CHOICES = 6;
function shuffle(array) {
// Copied from Stack Overflow
// https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
--counter;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
cases: this.createCases(),
initialCaseChosen: false,
initialCase: '',
initialCaseNum: 0,
numCasesToChoose: ORIGINAL_NUM_CHOICES,
caseChosenNormally: '',
offer: 0,
turnNum: 1,
numCasesRemaining: 26,
finalOfferMade: false,
}
}
createCases = () => {
let cases = [];
let randomCaseValues = shuffle([...CASE_VALUES]);
randomCaseValues.forEach((value, index) => {
cases.push({
value,
caseNum: index + 1,
opened: false,
});
});
return cases;
}
chooseCase = (caseNum) => {
if (!this.state.initialCaseChosen) {
this.setState({
initialCaseChosen: true,
initialCase: this.state.cases[caseNum - 1],
initialCaseNum: caseNum,
});
}
else {
this.state.cases[caseNum - 1].opened = true;
this.setState({
numCasesToChoose: this.state.numCasesToChoose - 1,
caseChosenNormally: this.state.cases[caseNum - 1],
});
}
this.setState({
numCasesRemaining: this.state.numCasesRemaining - 1,
});
if (this.state.numCasesToChoose - 1 === 0) {
this.calculateOffer();
}
}
calculateOffer = () => {
// Using a rough formula from this link:
// https://answers.yahoo.com/question/index?qid=20061106173902AAc48qj
const nonOpenedCases = [...this.state.cases.filter(c => !c.opened)];
const valueOfCases = nonOpenedCases.reduce(
(accumulator, c) => {
return accumulator + c.value;
}, 0);
const averageValueOfCases = valueOfCases / nonOpenedCases.length;
const newOffer =
(averageValueOfCases * (this.state.turnNum / 10)).toFixed(2);
this.setState({
offer: newOffer,
});
}
acceptDeal = () => {
alert("You won " + this.formatMoney(this.state.offer) + "!"
+ "\nThank you for playing Deal or No Deal!");
}
rejectDeal = () => {
const newChoiceNum = ORIGINAL_NUM_CHOICES - this.state.turnNum;
const newNumCasesToChoose = newChoiceNum > 1 ?
newChoiceNum : 1;
this.setState({
turnNum: this.state.turnNum + 1,
numCasesToChoose: newNumCasesToChoose,
});
if (this.state.numCasesRemaining === 1) {
this.setState({
numCasesToChoose: 0,
finalOfferMade: true,
})
}
}
keepCase = () => {
this.state.offer = this.state.initialCase.value;
this.acceptDeal();
}
swapCase = () => {
const lastCase = [...this.state.cases.filter(c => {
return c !== this.state.initialCase && !c.opened;
})][0];
this.state.offer = lastCase.value;
this.acceptDeal();
}
formatMoney = (amount, decimalCount = 2, decimal = ".", thousands = ",") => {
// Mostly copied from
// https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-dollars-currency-string-in-javascript
try {
decimalCount = Math.abs(decimalCount);
decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
let j = (i.length > 3) ? i.length % 3 : 0;
return "$" + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
} catch (e) {
console.log(e);
}
}
render() {
return (
<div className="App">
<Header />
<TurnInfo
initialCaseNum={this.state.initialCaseNum}
numCasesToChoose={this.state.numCasesToChoose}
offer={this.state.offer}
acceptDeal={this.acceptDeal}
rejectDeal={this.rejectDeal}
numCasesRemaining={this.state.numCasesRemaining}
keepCase={this.keepCase}
swapCase={this.swapCase}
formatMoney={this.formatMoney}
finalOfferMade={this.state.finalOfferMade}/>
<div className="game-cases-info" style={{
display: 'flex',
}}>
<div className="cases">
<Cases cases={this.state.cases}
chooseCase={this.chooseCase}
initialCaseNum={this.state.initialCaseNum} />
</div>
<li className="spacer" style={{
visibility: 'hidden',
flexGrow: '5',
}} />
<ValuesTable
cases={this.state.cases}
formatMoney={this.formatMoney}/>
</div>
</div>
);
}
}
export default App;
<file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ValuesTableCell from './ValuesTableCell';
class ValuesTable extends Component {
render() {
let casesSortedByValue = [...this.props.cases];
casesSortedByValue.sort((firstCase, secondCase) => {
return firstCase.value >= secondCase.value;
});
let tableElements = [];
for (let i = 0; i < 13; ++i) {
tableElements.push(
<tr key={i + 1}>
<ValuesTableCell
case={casesSortedByValue[i]}
formatMoney={this.props.formatMoney}/>
<ValuesTableCell
case={casesSortedByValue[i + 13]}
formatMoney={this.props.formatMoney}/>
</tr>
);
}
return (
<table className="values-table">
<tbody>
{tableElements}
</tbody>
</table>
);
}
}
ValuesTable.propTypes = {
cases: PropTypes.array.isRequired,
formatMoney: PropTypes.func.isRequired,
};
export default ValuesTable;
|
c4bb45fce73c9e2cb3db5b9d1031a706a17a51c4
|
[
"JavaScript"
] | 6 |
JavaScript
|
SirIsaacNeutron/deal-or-no-deal
|
f5a5f1d472900c69e8936285622f1e8305c062b1
|
f503c33c1a8f023b840f1f93d0655644e824a72e
|
refs/heads/main
|
<repo_name>burkozel/dj-hw<file_sep>/pagination/stations/views.py
from django.shortcuts import render, redirect
from django.urls import reverse
def index(request):
return redirect(reverse('bus_stations'))
def bus_stations(request):
# получите текущую страницу и передайте ее в контекст
# также передайте в контекст список станций на странице
context = {
# 'bus_stations': ...,
# 'page': ...,
}
return render(request, 'stations/index.html', context)
|
2e3f41a02d32011878a5cd49519fbc5d431c1546
|
[
"Python"
] | 1 |
Python
|
burkozel/dj-hw
|
bf2f0cdc771333123f112f141e68bb74bf0ef9bb
|
f5ba7d90595d59e527948fc07dec9596ec4b173f
|
refs/heads/master
|
<repo_name>psnehas/Two-Pointers-2<file_sep>/RemoveDuplicatesFromSortedArray2.py
class Solution:
def removeDuplicates(self, nums):
count, wi = 1, 1
prevch = nums[0]
for i in range(1, len(nums)):
if nums[i] != prevch:
count = 1
if nums[i] == nums[i-1]:
count += 1
if count > 2:
continue
nums[wi] = nums[i]
prevch = nums[wi]
wi += 1
return wi
<file_sep>/MergeSortedArray.py
# Time complexity: O(n) (m==n) here
# Space complexity: O(1)
# edge case: there is a possibility that there are no elements in nums1 but only enough space to fill it with nums2 values.
# At the end of the iteration make sure to add another loop to traverse through nums2 remaining elements
class Solution:
def merge(self, nums1, m, nums2, n):
"""
Do not return anything, modify nums1 in-place instead.
"""
p1, p2, p3 = m-1, n-1, m+n-1
while p1 >= 0 and p2 >= 0:
if nums1[p1] > nums2[p2]:
nums1[p3] = nums1[p1]
p1 -= 1
else:
nums1[p3] = nums2[p2]
p2 -= 1
p3 -= 1
while p2 >= 0:
nums1[p3] = nums2[p2]
p2 -= 1
p3 -= 1
return nums1
solution = Solution()
print(solution.merge([1, 2, 3, 0, 0, 0], 3, [4, 5, 6], 3))
print(solution.merge([0, 0, 0], 0, [4, 5, 6], 3))
<file_sep>/SearchIn2DMatrix2.py
# Time complexity: O(log n)
# Space complexity: O(1)
def searchMatrix(matrix, target):
rowLen = len(matrix)
colLen = len(matrix[0])
row, col = rowLen-1, 0
while row >= 0 and col < colLen:
if target == matrix[row][col]:
return True
elif target < matrix[row][col]:
row -= 1
else:
col += 1
return False
print(searchMatrix([[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [
3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], 5))
print(searchMatrix([[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [
3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], 0))
|
fcb68de7c16910dbe65cd349a2c7de6876f3c4d4
|
[
"Python"
] | 3 |
Python
|
psnehas/Two-Pointers-2
|
21b0154d285d9945245615d3167f117954ebf3f4
|
9ebf2a78274669ed9e92272664836cb336d659d3
|
refs/heads/master
|
<repo_name>carolinlabinski/intro_javascript<file_sep>/script_7.js
input = prompt("Saisir une phrase:");
switch(true) {
case input.slice(-1) === "?":
console.log("Ouais Ouais...");
break;
case input === input.toUpperCase() && input != "":
console.log("Pwa, calme-toi...");
break;
case input.includes("Fortnite"):
console.log("on s' fait une partie soum-soum ?");
break;
case input === "":
console.log("t'es en PLS ?");
break
default:
console.log("balek");
break;
}<file_sep>/script_2.js
let nbr = prompt("De quel nombre veux-tu calculer la factorielle ?");
if (nbr == 0 || nbr == 1){
console.log ("Le résultat est : 1")
}
else{
let i = nbr;
while(nbr > 1){
nbr--
i = nbr * i
}
let answer = `Le résultat est : ${i}`
console.log(answer)
// var nombre = prompt("De quel nombre veux-tu calculer la factorielle ?");
// console.log("Nombre choisi:" + " " + nombre);
// function factorial(nombre)
// {
// if (nombre === 0)
// {
// return 1;
// }
// return nombre * factorial(nombre-1);
// }
// console.log("Le résultat est:" + " " + factorial(nombre));
<file_sep>/script_1.js
let greet = "Bon<NAME> !";
console.log(greet);
let nom = "";
nom = prompt("Quel est ton prénom");
console.log("Bonjour," + " "+ nom +"!")
|
c78e616c8f4fc9a02989f7e1990175c060202a05
|
[
"JavaScript"
] | 3 |
JavaScript
|
carolinlabinski/intro_javascript
|
dd413faf31bbff7f6b0826c50faabb7dca067f99
|
510dc2e382e7e3dacd069735fe3701c02aca5195
|
refs/heads/master
|
<repo_name>boyeoffice/php-mysql-crud<file_sep>/ajax/updateUserDetails.php
<?php
include('../db/connection.php');
if (isset($_POST)) :
$id = $_POST['id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$query = "UPDATE users SET first_name = '$first_name', last_name = '$last_name', email = '$email' WHERE id = '$id'";
if (!$result = mysqli_query($con, $query)) :
exit(mysqli_error($con));
endif;
endif;
?>
<file_sep>/ajax/readRecord.php
<?php
include('../db/connection.php');
$query = 'SELECT * FROM users ORDER BY id DESC';
if (!$result = mysqli_query($con, $query)) :
exit(mysqli_error($con));
endif;
if (mysqli_num_rows($result)) :
$number = 1;
while ($row = mysqli_fetch_assoc($result)) :
$data = '<tr>
<td>'.$number.'</td>
<td>'.$row['first_name'].'</td>
<td>'.$row['last_name'].'</td>
<td>'.$row['email'].'</td>
<td>
<button class="btn btn-primary btn-sm" onclick="getUserDetails('.$row['id'].')">Edit</button>
<button class="btn btn-danger btn-sm" onclick="deleteUser('.$row['id'].')">Delete</button>
</td>
</tr>';
echo $data;
endwhile;
else :
$data = '<tr><td>Recods not found!</td></tr>';
echo $data;
endif;
<file_sep>/ajax/addRecord.php
<?php
if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email'])) :
include('../db/connection.php');
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$query = "INSERT INTO users(first_name, last_name, email) VALUES('$first_name', '$last_name', '$email')";
if (!$result = mysqli_query($con, $query)) :
exit(mysqli_error($con));
endif;
echo '1 Record Added!';
endif;
?>
<file_sep>/db/php-crud.sql
CREATE TABLE `users` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`first_name` VARCHAR( 40 ) NOT NULL ,
`last_name` VARCHAR( 40 ) NOT NULL ,
`email` VARCHAR( 50 ) NOT NULL
) ENGINE = MYISAM ;
<file_sep>/ajax/deleteUser.php
<?php
if (isset($_POST['id'])) :
include('../db/connection.php');
$user_id = $_POST['id'];
$query = "DELETE FROM users WHERE id = '$user_id'";
if (!$result = mysqli_query($con, $query)) :
exit(mysqli_error($con));
endif;
endif;
?>
<file_sep>/README.md
# PHP Mysql CRUD
PHP MySQL CRUD is all about INSERT, UPDATE, DELETE and SELECT SQL queries using PHP , it will help beginners to know about PHP and MySQL operations.
|
557b7ea370c3841bd39e5db79292963bcee860e4
|
[
"Markdown",
"SQL",
"PHP"
] | 6 |
PHP
|
boyeoffice/php-mysql-crud
|
f40cdae91cd99fc53fc38a4716539d3d2302b4f3
|
1ccacc661bb1379fbc75f08403144b18ad4a517a
|
refs/heads/main
|
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { startQuiz } from '../actions'
import Question from './Question'
import QuizResult from './QuizResult'
/**
* The quiz component is responsible for starting a new quiz, and checking
* for quiz completion. Quizzes are considered complete when the value of
* currentAnswer exceeds the length of the quizzes' questions
*/
class Quiz extends Component {
constructor(props) {
super(props)
// We'll always start with the first quiz, if available
if (this.props.quizzes.length) {
this.props.startQuiz(0)
}
}
getQuiz() {
return this.props.quizzes[this.props.currentQuiz]
}
isQuizFinished() {
const activeQuiz = this.getQuiz()
if (this.props.currentQuestion && activeQuiz) {
return this.props.currentQuestion >= activeQuiz.questions.length
} else {
return undefined
}
}
shouldComponentUpdate(nextProps, nextState) {
return this.props !== nextProps
}
render() {
const activeQuiz = this.getQuiz()
if (activeQuiz) {
const quizBody = this.isQuizFinished() ?
(<QuizResult key={this.props.currentQuiz} />) : (<Question key={this.props.currentQuestion} />)
return (
<div key={activeQuiz.title}>
<h1>{activeQuiz.title}</h1>
{quizBody}
</div>
)
} else {
return (
<h2>Loading quiz...</h2>
)
}
}
}
const mapDispatchToProps = (dispatch) => {
return {
startQuiz: quiz => dispatch(startQuiz(quiz))
}
}
const mapStateToProps = (state, ownProps) => {
return {
currentQuiz: state.currentQuiz,
currentQuestion: state.currentQuestion,
quizzes: state.quizzes,
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Quiz)
<file_sep>/**
* answerLetter takes an integer offset and returns
* a character offset starting from "A", i.e
* answerLetter(1) should return "B"
*/
const answerLetter = (offset) => {
return String.fromCharCode('A'.charCodeAt(0) + offset)
}
/**
* Check answer takes in a question and an answer and tells you if it's correct
* @param {object} question
* @param {string} answer
* @return {boolean}
*/
const checkAnswer = (question, answer) => {
return true
}
/**
* Given a quiz and a question index, fetches that question from a quiz
* @param {object} quiz
* @param {integer} questionIndex
* @return {object} the question (or null)
*/
const getQuestion = (quiz, questionIndex) => {
if (quiz.questions.length > questionIndex && questionIndex >= 0) {
return quiz.questions[questionIndex]
} else {
return null
}
}
/**
* shuffleAnswers takes in an array of answers and returns
* an array of randomly sorted answers. Uses the Knuth Shuffle!
*/
const shuffleAnswers = ( answers ) => {
let currentIndex = answers.length, temporaryValue, randomIndex
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex -= 1
// And swap it with the current element.
temporaryValue = answers[currentIndex]
answers[currentIndex] = answers[randomIndex]
answers[randomIndex] = temporaryValue
}
return answers
}
export {
answerLetter,
checkAnswer,
getQuestion,
shuffleAnswers
}
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getQuizzes } from './data/quizzes'
import { initializeQuizzes } from './actions'
import Quiz from './components/Quiz'
/**
* The App component is responsible for loading available quizzes, then
* rendering the Quiz component
*/
class App extends Component {
constructor(props) {
super(props)
getQuizzes().then((quizzes) => {
// Load the quizzes into our state "asynchronously"
this.props.initializeQuizzes(quizzes)
})
}
render() {
if (this.props.quizzes.length) {
// Render the first quiz, if we have it
return (
<div className="app">
<Quiz />
</div>
)
} else {
// Render a loading message
return (
<div className="app">
<p>One second, loading data...</p>
</div>
)
}
}
}
const mapDispatchToProps = (dispatch) => {
return {
initializeQuizzes: quizzes => dispatch(initializeQuizzes(quizzes))
}
}
const mapStateToProps = (state, ownProps) => {
return {
quizzes: state.quizzes
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { answerLetter, getQuestion, shuffleAnswers } from '../util/questionUtils'
import { incrementQuestion } from '../actions'
import Choice from './Choice'
/**
* The question component is responsible for rendering a question's text and
* a randomized list of potential answers.
*/
class Question extends Component {
constructor(props) {
super(props)
// This component's state will be initialized with the current question
// and randomized answers (choices). Choices are stored in the component state so that
// order can be preserved after answering
const quiz = this.props.quizzes[this.props.currentQuiz]
const question = getQuestion(quiz, this.props.currentQuestion)
const choices = shuffleAnswers([
question.correctAnswer,
...question.incorrectAnswers
])
// Question is stored in the state mostly for convenience. In a world where
// we're making real asynchronous calls, persisting the question here could
// improve performance
this.state = {
question: question,
choices: choices,
}
this.incrementQuestion = this.incrementQuestion.bind(this)
}
/**
* Determines if a user has answered the question
* @return {object} the answer, or undefined
*/
getAnswer() {
if (this.props.currentAnswers) {
return this.props.currentAnswers.find((a) => {
return a.question === this.state.question.text
})
} else {
return undefined
}
}
/**
* Given a user's answer (choice) to a question, determines whether to show
* the choice as correct (true), incorrect (false), or neither (undefined)
* @param {string} selectedChoice The user's selected choice
* @return {boolean} The relevant classnames for the choice
*/
getChoiceStatus(selectedChoice, choice) {
if (choice === this.state.question.correctAnswer) {
return true
} else if (selectedChoice === choice) {
return false
} else {
return undefined
}
}
/**
* checks if a userAnswer is correct
* @param {object} userAnswer
* @return {Boolean}
*/
isCorrect(userAnswer) {
return userAnswer.choice === this.state.question.correctAnswer
}
/**
* Conditionally renders question results
* @param {object} userAnswer
* @return {jsx}
*/
maybeRenderQuestionResult(userAnswer) {
if (userAnswer) {
return (
<div>
<p className='question__result'>
{this.isCorrect(userAnswer) ? 'Correct!' : 'Incorrect...'}
</p>
<button className="button" onClick={this.incrementQuestion}>Next</button>
</div>
)
}
}
incrementQuestion() {
this.props.incrementQuestion()
}
render() {
const userAnswer = this.getAnswer()
return (
<div>
<p>{this.state.question.text}</p>
<ul className="choice__list">
{this.state.choices.map((choice, index) => {
const resultStyle = userAnswer ? this.getChoiceStatus(userAnswer.choice, choice) : undefined
const letter = answerLetter(index)
return (
<Choice
key={letter}
letter={letter}
choice={choice}
questionTitle={this.state.question.text}
resultStyle={resultStyle} />
)
})}
</ul>
{ this.maybeRenderQuestionResult(userAnswer) }
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
incrementQuestion: () => dispatch(incrementQuestion())
}
}
const mapStateToProps = (state, ownProps) => {
return {
currentAnswers: state.currentAnswers,
currentQuestion: state.currentQuestion,
currentQuiz: state.currentQuiz,
quizzes: state.quizzes
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Question)
<file_sep>import React, { Component } from 'react'
/**
* The result item component is responsible for rendering a single answer result
*/
class ResultItem extends Component {
render() {
const classes = `results__answer results__answer--${this.props.correct ? 'correct' : 'incorrect'}`
return (
<li className="results__item">
<i>{this.props.question}</i> <span className={classes}>{this.props.choice}</span>
</li>
)
}
}
export default ResultItem
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { answerQuestion } from '../actions'
/**
* The question component is responsible for rendering a question's text and
* a randomized list of potential answers
*/
class Choice extends Component {
constructor(props) {
super(props)
this.selectChoice = this.selectChoice.bind(this)
}
selectChoice() {
this.props.answerQuestion({
question: this.props.questionTitle,
choice: this.props.choice
})
}
render() {
let classes = "choice"
if (this.props.resultStyle === true) {
classes += " choice--correct"
} else if (this.props.resultStyle === false) {
classes += " choice--incorrect"
}
return (
<li className={classes} onClick={this.selectChoice}>
<b>{this.props.letter}:</b> {this.props.choice}
</li>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
answerQuestion: userAnswer => dispatch(answerQuestion(userAnswer))
}
}
const mapStateToProps = (state, ownProps) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Choice)
<file_sep>const answerQuestion = (payload) => {
return { type: "ANSWER_QUESTION", payload}
}
const incrementQuestion = () => {
return { type: "INCREMENT_QUESTION" }
}
const initializeQuizzes = (payload) => {
return { type: "LOAD_QUIZZES", payload }
}
const startQuiz = (payload) => {
return { type: "START_QUIZ", payload }
}
const updateReportCard = (payload) => {
return { type: "UPDATE_REPORT_CARD", payload }
}
export {
answerQuestion,
incrementQuestion,
initializeQuizzes,
startQuiz,
updateReportCard
}
<file_sep># Documentation
Hi! 👋
Thanks for taking a look at this homework assignment.
## Running the code
This will go up on codesandbox, as assigned, but if you're forking this from github you can spin up the app with:
```
npm run start
```
## Implementation Details
### Redux Store / Managing Data
For this exercise, I used redux to manage the application's state. I haven't yet gotten a chance to mess around with hooks in react, but it's on my to-do list of things to learn!
You'll find that there are a lot of data manipulation functions that rely on quiz title. In leiu of unique IDs for objects, I had to rely on the assumption that titles for quizzes and questions were unique.
Another interesting detail about the way the store is set up is that I've chosen to store references to the array positions of questions and quizzes, in order to keep track of which quizzes and questions are active. This is a bit of a naive solution. When working with larger data sets, real databases, and real APIs, I might have chosen to combine several data structures into a de-normalized, document-based model. For example, each user could have an array of "remaining questions" to answer for a quiz, and changing states would be as simple as popping an answer off of the stack. Implementing the "array position" method, I was able to navigate quizzes and questions without duplicating too much data in memory, or editing the basic data itself.
### Delighters
I implemented delighters B and C. I found that with the way I structured my code, the application's redux store, and the various utility functions, it was easy to extend the code to allow test retakes, as well as show past answers.
### Comments
I've documented points of interest, as much as possible, in the code. You'll find informal documentation there about each component's responsibilities, potential edge cases, assumptions,and more.
## Future Improvements
Of course, there's a lot of things I'd like to do differently given more time:
- Implement answers/choices as accessible form elements
- More type checking and defensive programming, using proptypes or similar
- Specifying ComponentShouldUpdate for each component, for performance reasons
- Creating more granular, "dumber" components.
- Many of the components need to know a lot about the app's state, we can tighten that up
- Not all components need to extend React.component, and writing purely functional components can be a big performance booster
- There's a bug where you can create an invalid state by rapidly clicking choices on a single question.
|
1c7fd9de8aa441c2273fbc218edcf3ee1957a1df
|
[
"JavaScript",
"Markdown"
] | 8 |
JavaScript
|
gopperman/codecademy-takehome
|
2aae6ad93f968229e085294953c4cc368425c965
|
2d176570a187d99e841d5ff3a14f1736cdb21750
|
refs/heads/master
|
<file_sep>#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <ngx_md5.h>
#define NR_VNODE 160
#define HASH_DATA_LENGTH 32
typedef struct {
ngx_uint_t peer_index;
ngx_uint_t next;
uint32_t point;
} q_chash_vnode_t;
typedef struct {
q_chash_vnode_t *vnodes;
ngx_uint_t nr_vnodes;
ngx_uint_t nr_valid_peers;
} ngx_http_upstream_q_chash_ring;
typedef struct {
ngx_array_t *values;
ngx_array_t *lengths;
ngx_http_upstream_q_chash_ring *q_chash_ring;
} ngx_http_upstream_q_chash_srv_conf_t;
typedef struct {
/* rrp must be first */
ngx_http_upstream_rr_peer_data_t rrp;
ngx_http_upstream_q_chash_ring *q_chash_ring;
uint32_t point;
ngx_uint_t vnode_index;
ngx_uint_t tries;
ngx_uint_t ignore;
ngx_event_get_peer_pt get_rr_peer;
unsigned rr_mode:1;
} ngx_http_upstream_q_chash_peer_data_t;
static void *ngx_http_upstream_q_chash_create_srv_conf(ngx_conf_t *cf);
static char *ngx_http_upstream_q_chash(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static ngx_int_t ngx_http_upstream_init_q_chash(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *us);
static ngx_int_t ngx_http_upstream_init_q_chash_peer(ngx_http_request_t *r, ngx_http_upstream_srv_conf_t *us);
static ngx_int_t ngx_http_upstream_get_q_chash_peer(ngx_peer_connection_t *pc, void *data);
static int compare_vnodes_point(const q_chash_vnode_t *n1, const q_chash_vnode_t *n2);
static uint32_t q_chash_find(const ngx_http_upstream_q_chash_ring *q_chash_ring, uint32_t point);
static ngx_http_upstream_rr_peer_t *q_chash_get_peer(ngx_http_upstream_q_chash_peer_data_t *qchp, ngx_log_t *log);
static ngx_command_t ngx_http_upstream_q_chash_commands[] = {
{ ngx_string("q_chash"),
NGX_HTTP_UPS_CONF|NGX_CONF_TAKE1,
ngx_http_upstream_q_chash,
0,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_upstream_q_chash_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
ngx_http_upstream_q_chash_create_srv_conf, /* create server configuration */
NULL, /* merge server configuration */
NULL, /* create location configuration */
NULL /* merge location configuration */
};
ngx_module_t ngx_http_upstream_q_chash_module = {
NGX_MODULE_V1,
&ngx_http_upstream_q_chash_module_ctx, /* module context */
ngx_http_upstream_q_chash_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *ngx_http_upstream_q_chash_create_srv_conf(ngx_conf_t *cf)
{
ngx_http_upstream_q_chash_srv_conf_t *conf;
conf = ngx_pcalloc(cf->pool,
sizeof(ngx_http_upstream_q_chash_srv_conf_t));
if (conf == NULL) {
return NULL;
}
/*
* set by ngx_pcalloc():
*
* conf->lengths = NULL;
* conf->values = NULL;
*/
return conf;
}
static uint32_t q_chash_find(const ngx_http_upstream_q_chash_ring *q_chash_ring, uint32_t point) {
ngx_uint_t mid = 0;
ngx_uint_t lo = 0;
ngx_uint_t hi = q_chash_ring->nr_vnodes - 1;
while(1) {
if(point <= q_chash_ring->vnodes[lo].point || point > q_chash_ring->vnodes[hi].point) {
return lo;
}
/* test middle point */
mid = lo + (hi - lo) / 2;
/* perfect match */
if (point <= q_chash_ring->vnodes[mid].point &&
point > (mid ? q_chash_ring->vnodes[mid-1].point : 0)) {
return mid;
}
/* too low, go up */
if (q_chash_ring->vnodes[mid].point < point) {
lo = mid + 1;
}
else {
hi = mid - 1;
}
}
}
static ngx_http_upstream_rr_peer_t *q_chash_get_peer(ngx_http_upstream_q_chash_peer_data_t *qchp, ngx_log_t *log) {
ngx_http_upstream_q_chash_ring *q_chash_ring = qchp->q_chash_ring;
ngx_http_upstream_rr_peer_data_t *rrp = &(qchp->rrp);
ngx_http_upstream_rr_peers_t *peers = rrp->peers;
ngx_http_upstream_rr_peer_t *peer = NULL;
ngx_uint_t i, n;
uintptr_t m;
time_t now;
now = ngx_time();
if(q_chash_ring->nr_valid_peers == 1 && qchp->tries < 1) {
for(i = 0; i < peers->number; i++) {
peer = &peers->peer[i];
if(!peer->down) {
n = i / (8 * sizeof(uintptr_t));
m = (uintptr_t) 1 << i % (8 * sizeof(uintptr_t));
break;
}
}
}
else if(q_chash_ring->nr_valid_peers > 1) {
for(; qchp->tries + qchp->ignore < q_chash_ring-> nr_valid_peers; qchp->vnode_index = q_chash_ring->vnodes[qchp->vnode_index].next) {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, log, 0, "q_chash check vnode_index %ui", qchp->vnode_index);
i = q_chash_ring->vnodes[qchp->vnode_index].peer_index;
n = i / (8 * sizeof(uintptr_t));
m = (uintptr_t) 1 << i % (8 * sizeof(uintptr_t));
if (rrp->tried[n] & m) {
continue;
}
if(peers->peer[i].max_fails
&& peers->peer[i].fails >= peers->peer[i].max_fails
&& now - peers->peer[i].checked <= peers->peer[i].fail_timeout) {
rrp->tried[n] |= m;
qchp->ignore ++;
continue;
}
qchp->vnode_index = q_chash_ring->vnodes[qchp->vnode_index].next;
peer = &peers->peer[i];
break;
}
}
if(peer == NULL)
return NULL;
rrp->current = i;
rrp->tried[n] |= m;
peer->checked = now;
qchp->tries ++;
return peer;
}
static ngx_int_t ngx_http_upstream_get_q_chash_peer(ngx_peer_connection_t *pc, void *data)
{
ngx_http_upstream_q_chash_peer_data_t *qchp = data;
ngx_http_upstream_q_chash_ring *q_chash_ring = qchp->q_chash_ring;
ngx_http_upstream_rr_peer_data_t *rrp = &(qchp->rrp);
ngx_http_upstream_rr_peers_t *peers = rrp->peers;
ngx_http_upstream_rr_peer_t *peer;
ngx_uint_t i, n;
ngx_int_t rc;
ngx_log_debug(NGX_LOG_DEBUG_HTTP, pc->log, 0, "q_chash try %ui ignore %ui, valid %ui, pc->tries %ui", qchp->tries, qchp->ignore, q_chash_ring->nr_valid_peers, pc->tries);
if(!qchp->rr_mode) {
peer = q_chash_get_peer(qchp, pc->log);
if (peer == NULL) {
if(peers->next) {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, pc->log, 0, "return to rr");
goto return_to_rr;
}
else {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, pc->log, 0, "return to busy");
goto return_to_busy;
}
}
pc->sockaddr = peer->sockaddr;
pc->socklen = peer->socklen;
pc->name = &peer->name;
ngx_log_debug(NGX_LOG_DEBUG_HTTP, pc->log, 0, "q_chash peer, current: %ui, %V", rrp->current, pc->name);
if (pc->tries == 1 && rrp->peers->next) {
pc->tries += rrp->peers->next->number;
}
return NGX_OK;
}
return_to_rr:
qchp->rr_mode = 1;
if(peers->next) {
rrp->peers = peers->next;
pc->tries = rrp->peers->number;
n = (rrp->peers->number + (8 * sizeof(uintptr_t) - 1))
/ (8 * sizeof(uintptr_t));
for (i = 0; i < n; i++) {
rrp->tried[i] = 0;
}
}
rc = qchp->get_rr_peer(pc, rrp);
if (rc != NGX_BUSY) {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, pc->log, 0, "rr peer, backup current: %ui, %V", rrp->current, pc->name);
return rc;
}
return_to_busy:
// all peers failed, mark them as live for quick recovery
ngx_log_debug(NGX_LOG_DEBUG_HTTP, pc->log, 0, "clear fails");
for (i = 0; i < peers->number; i++) {
peers->peer[i].fails = 0;
}
pc->name = peers->name;
return NGX_BUSY;
}
static ngx_int_t ngx_http_upstream_init_q_chash_peer(ngx_http_request_t *r, ngx_http_upstream_srv_conf_t *us)
{
ngx_int_t rc;
ngx_http_upstream_q_chash_srv_conf_t *uchscf;
ngx_http_upstream_q_chash_peer_data_t *qchp;
ngx_http_upstream_q_chash_ring *q_chash_ring;
ngx_str_t evaluated_key_to_hash;
uchscf = ngx_http_conf_upstream_srv_conf(us, ngx_http_upstream_q_chash_module);
if (uchscf == NULL) {
return NGX_ERROR;
}
q_chash_ring = uchscf->q_chash_ring;
qchp = ngx_pcalloc(r->pool, sizeof(*qchp));
if(qchp == NULL)
return NGX_ERROR;
r->upstream->peer.data = &qchp->rrp;
qchp->q_chash_ring = q_chash_ring;
qchp->get_rr_peer = ngx_http_upstream_get_round_robin_peer;
qchp->tries = 0;
qchp->ignore = 0;
qchp->rr_mode = 0;
rc = ngx_http_upstream_init_round_robin_peer(r, us);
if(rc != NGX_OK)
return NGX_ERROR;
r->upstream->peer.get = ngx_http_upstream_get_q_chash_peer;
// calculate the vnode_index
if(q_chash_ring->nr_valid_peers > 1) {
if (ngx_http_script_run(r, &evaluated_key_to_hash, uchscf->lengths->elts, 0, uchscf->values->elts) == NULL)
return NGX_ERROR;
qchp->point = (uint32_t)ngx_crc32_long(evaluated_key_to_hash.data, evaluated_key_to_hash.len);
qchp->vnode_index = q_chash_find(q_chash_ring, qchp->point);
ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "q_chash key %V, point %uD, vnode_index %ui", &evaluated_key_to_hash, qchp->point, qchp->vnode_index);
}
return NGX_OK;
}
static int compare_vnodes_point(const q_chash_vnode_t *n1, const q_chash_vnode_t *n2) {
if(n1->point < n2->point)
return -1;
else if(n1->point > n2->point)
return 1;
return 0;
}
static ngx_int_t ngx_http_upstream_init_q_chash(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *us)
{
unsigned char hash_data[HASH_DATA_LENGTH] = {};
ngx_http_upstream_q_chash_ring *q_chash_ring;
ngx_http_upstream_q_chash_srv_conf_t *uchscf;
ngx_http_upstream_rr_peers_t *peers;
ngx_uint_t vnode_num, i, j, k, fill_next;
ngx_int_t si;
uint32_t point;
uchscf = ngx_http_conf_upstream_srv_conf(us, ngx_http_upstream_q_chash_module);
if (uchscf == NULL) {
return NGX_ERROR;
}
q_chash_ring = ngx_pcalloc(cf->pool, sizeof(*q_chash_ring));
if(q_chash_ring == NULL)
return NGX_ERROR;
if (ngx_http_upstream_init_round_robin(cf, us) != NGX_OK) {
return NGX_ERROR;
}
us->peer.init = ngx_http_upstream_init_q_chash_peer;
uchscf->q_chash_ring = q_chash_ring;
peers = us->peer.data;
for(i = 0; i < peers->number; i++) {
if(!peers->peer[i].down)
q_chash_ring->nr_valid_peers ++;
}
// old_cycle's log_level is NGX_LOG_NOTICE
//ngx_log_debug(NGX_LOG_DEBUG_HTTP, cf->log, 0, "upstream %V nr_valid_peers %ui", peers->name, q_chash_ring->nr_valid_peers);
// no need to hash
if(q_chash_ring->nr_valid_peers <= 1) {
return NGX_OK;
}
// create vnodes, peer_index field, sort
q_chash_ring->vnodes = ngx_palloc(cf->pool, sizeof(q_chash_vnode_t) * peers->total_weight * NR_VNODE);
if(q_chash_ring->vnodes == NULL) {
return NGX_ERROR;
}
for(i = 0; i < peers->number; i++) {
if(peers->peer[i].down) {
continue;
}
vnode_num = peers->peer[i].weight * NR_VNODE;
for(j = 0; j < vnode_num / 4; j++) {
ngx_snprintf(hash_data, HASH_DATA_LENGTH, "%V-%ui%Z", &peers->peer[i].name, j);
u_char md5[16];
ngx_md5_t ctx;
ngx_md5_init(&ctx);
ngx_md5_update(&ctx, hash_data, ngx_strlen(hash_data));
ngx_md5_final(md5, &ctx);
for(k = 0; k < 4; k++) {
point = *(uint32_t *)&md5[k * 4];
q_chash_ring->vnodes[q_chash_ring->nr_vnodes].peer_index = i;
q_chash_ring->vnodes[q_chash_ring->nr_vnodes].point = point;
q_chash_ring->nr_vnodes ++;
}
}
}
// old_cycle's log_level is NGX_LOG_NOTICE
//ngx_log_debug(NGX_LOG_DEBUG_HTTP, cf->log, 0, "upstream %V nr_vnodes %ui", peers->name, q_chash_ring->nr_vnodes);
ngx_qsort(q_chash_ring->vnodes, q_chash_ring->nr_vnodes, sizeof(q_chash_vnode_t), (const void *)compare_vnodes_point);
// fill vnode's next field
for(i = 1; ; i ++) {
if(q_chash_ring->vnodes[0].peer_index == q_chash_ring->vnodes[i].peer_index)
continue;
q_chash_ring->vnodes[0].next = i;
break;
}
fill_next = 0;
for(si = q_chash_ring->nr_vnodes - 1; si >= 0; si--) {
if(q_chash_ring->vnodes[si].peer_index == q_chash_ring->vnodes[fill_next].peer_index) {
q_chash_ring->vnodes[si].next = q_chash_ring->vnodes[fill_next].next;
}
else {
q_chash_ring->vnodes[si].next = fill_next;
fill_next = si;
}
}
// old_cycle's log_level is NGX_LOG_NOTICE
/*
for(i = 0; i < q_chash_ring->nr_vnodes; i++) {
ngx_log_debug(NGX_LOG_DEBUG_HTTP, cf->log, 0, "%ui, next %ui peer_index %ui point %uD", i, q_chash_ring->vnodes[i].next, q_chash_ring->vnodes[i].peer_index, q_chash_ring->vnodes[i].point);
}
*/
// calculate peer ratio for debug ~
ngx_uint_t *statistic_array = ngx_pcalloc(cf->pool, sizeof(uint32_t) * peers->number);
if(statistic_array == NULL)
return NGX_OK;
uint32_t before_point = 0;
for(i = 1; i < q_chash_ring->nr_vnodes; i++) {
statistic_array[q_chash_ring->vnodes[i].peer_index] += q_chash_ring->vnodes[i].point - before_point;
before_point = q_chash_ring->vnodes[i].point;
}
statistic_array[q_chash_ring->vnodes[0].peer_index] += 0xFFFFFFFF - before_point;
for(i = 0; i < peers->number; i++) {
if(peers->peer[i].down)
continue;
ngx_log_error(NGX_LOG_NOTICE, cf->log, 0, "upstream %V %V weight %ui actually ratio %.2f%%", peers->name, &peers->peer[i].name, peers->peer[i].weight, 100 * (double)statistic_array[i] / 0xFFFFFFFF);
}
ngx_pfree(cf->pool, statistic_array);
return NGX_OK;
}
static char *ngx_http_upstream_q_chash(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_upstream_srv_conf_t *uscf;
ngx_http_upstream_q_chash_srv_conf_t *uchscf;
ngx_str_t *value;
ngx_http_script_compile_t sc;
uscf = ngx_http_conf_get_module_srv_conf(cf, ngx_http_upstream_module);
uchscf = ngx_http_conf_upstream_srv_conf(uscf, ngx_http_upstream_q_chash_module);
value = cf->args->elts;
ngx_memzero(&sc, sizeof(ngx_http_script_compile_t));
sc.cf = cf;
sc.source = &value[1];
sc.lengths = &uchscf->lengths;
sc.values = &uchscf->values;
sc.complete_lengths = 1;
sc.complete_values = 1;
if (ngx_http_script_compile(&sc) != NGX_OK) {
return NGX_CONF_ERROR;
}
uscf->peer.init_upstream = ngx_http_upstream_init_q_chash;
uscf->flags = NGX_HTTP_UPSTREAM_CREATE
| NGX_HTTP_UPSTREAM_WEIGHT
| NGX_HTTP_UPSTREAM_MAX_FAILS
| NGX_HTTP_UPSTREAM_FAIL_TIMEOUT
| NGX_HTTP_UPSTREAM_DOWN
| NGX_HTTP_UPSTREAM_BACKUP;
return NGX_CONF_OK;
}
|
b2210d568e925d03637467e85ca85cc8d20c68b2
|
[
"C"
] | 1 |
C
|
spacexnasa/ngx_http_q_chash
|
1c29aec80cc0b472ebb2cd6b0523bca2c1fc285a
|
7576818ad90d3e6527025bd031b09f4ef4d30983
|
refs/heads/master
|
<repo_name>gdg-work/SkillFactory__SDA5__Case_A8<file_sep>/02_user_paths_analysis.md
# Анализ уникальных пользовательских путей

Как видно из схемы (а ранее из запросов в базу), после выбора уровня сложности всё просто и линейно, но до этого этапа возможны различные пути.
Позже мы увидим, что и это не совсем так, и между шестью этапами пользователи могут перемещаться многими различныме способами.
Внесём данные о количестве пользователей на разных этапах. Число внутри блока (этапа) показывает количество уникальных пользователей, которые
этот этап проходили, число рядом со стрелкой — количество пользователей, которые выполнили этот переход. Поскольку некоторые пользователи могли
проходить этапы более одного раза, суммы чисел на стрелках не всегда будет соответствовать числам внутри блоков:
~~~graphviz
digraph user_paths {
# stages (or states of our finite automata)
rankdir="LR";
node [shape=box fontname="DejaVu Sans-10"];
edge [fontname="DejaVu Sans-8"];
REG [label="Регистрация\n 19926", color="red", fontcolor="red"];
TUTB [label="Начато\nобучение\n 11858", color="green", fontcolor="green"];
TUTE [label="Закончено\nобучение\n 10250", color="blue", fontcolor="blue"];
SLVL [label="Выбор уровня\nсложности\n 8342", color="orange", fontcolor="orange"];
SFREE [label="Выбор набора\nбесплатных\nтренировок\n 5737", color="violet", fontcolor="violet"];
BUY [label="Покупка\nплатных\nтренировок\n 1600", color="black", fontcolor="black"]
# Transitions
REG -> TUTB [color="red", fontcolor="red"];
REG -> SLVL [label="98", color="red", fontcolor="red"];
TUTB -> TUTE [label=10250, color="green", fontcolor="green"];
TUTB -> SLVL [label=743, color="green", fontcolor="green"];
TUTE -> TUTB [color="blue", fontcolor="blue"];
TUTE -> SLVL [label=7501, color="blue", fontcolor="blue"];
SLVL -> SFREE [color="orange", fontcolor="orange"];
SFREE -> BUY [color="violet", fontcolor="violet"];
}
~~~
> Для начала давайте объединим датафрейм с событиями вместе с датафреймом по
> оплатам. Это позволит анализировать все эти события в рамках одной структуры
> данных.
> Сначала добавим в датафрейм `purchase_df` столбец `event_type`, который будет содержать
> одно значение `purchase`. Это нужно, чтобы в объединенном датафрейме однозначно
> выделить события оплаты.
Нет особого резона тащить лишние поля, поэтому оставлю от каждой таблицы три колонки: `user_id`,
`event_type` и `start_time` (`timestamp`), после чего объединю таблицы и посмотрю, что делать дальше.
```
create view events17_by_uid_time as
select user_id as uid, event_type as event, start_time as tstamp from evts17
union all
select user_id as uid, 'purchase' as event, start_time as tstamp from purs17
order by uid, tstamp;
dgolub=> select count(*) from events17_by_uid_time ;
count
-------
68559
```
В представлении `events17_by_uid_time` у нас собралась выборка событий, отсортированная по пользователю и времени.
Теперь нужно агрегировать список событий в путь.
Попробуем для этого [функцию STRING_AGG](https://www.postgresql.org/docs/11/sql-expressions.html#SYNTAX-AGGREGATES) из PostreSQL.
```
dgolub=> select STRING_AGG(event, '>' order by tstamp) from events17_by_uid_time group by uid limit 5;
string_agg
--------------------------------------------------------------------------
registration
registration>tutorial_start>tutorial_finish
registration>tutorial_start>tutorial_finish
registration>tutorial_start>tutorial_finish>level_choice>training_choice
registration>tutorial_start>tutorial_start>tutorial_finish
```
Получается. Теперь нужно сгруппировать эти последовательности событий и выделить самые часто встречающиеся.
```
select
count(p.path) as count,
p.path
from (
select STRING_AGG(event, '>' order by tstamp) as path
from events17_by_uid_time group by uid
) as p
group by p.path
order by count desc;
```
> Сколько пользователей совершили наиболее популярный путь, ведущий к событию purchase?
> (для ответа используйте данные пользователей, зарегистрировавшихся в 2017 году)
```
select
count(p.path) as count, p.path
from
(select STRING_AGG(event, '>' order by tstamp) as path
from events17_by_uid_time
group by uid) as p
where right(p.path,9) = '>purchase'
group by p.path
order by count desc limit 5;
count | path
-------+------------------------------------------------------------------------------------------------------------------
1083 | registration>tutorial_start>tutorial_finish>level_choice>training_choice>purchase
124 | registration>tutorial_start>level_choice>training_choice>purchase
101 | registration>tutorial_start>tutorial_finish>level_choice>training_choice>tutorial_start>tutorial_finish>purchase
52 | registration>tutorial_start>tutorial_finish>tutorial_start>tutorial_finish>level_choice>training_choice>purchase
26 | registration>tutorial_start>tutorial_start>tutorial_finish>level_choice>training_choice>purchase
```
> Итак, видно, что большинство последовательностей, которые содержат в себе оплату, также содержат старт обучения
Глазам мы верить не будем, а посчитаем. Для начала сохраним результаты предыдущего этапа во временной
таблице (можно использовать view, но зачем снова и снова запрашивать то, что можно сохранить, объём данных здесь невелик).
```
dgolub=> create temporary table purchase_paths as
select
count(p.path) as count, p.path
from
(select STRING_AGG(event, '>' order by tstamp) as path
from events17_by_uid_time
group by uid) as p
where right(p.path,9) = '>purchase'
group by p.path
order by count desc;
SELECT 115
```
Проверяем, что количество покупок сходится:
```
dgolub=> select sum(count) from purchase_paths;
sum
------
1597
```
Где-то потерялись три пользователя. Возможно, у них покупка была не последним событием?
```
dgolub=> create temporary table purchase_paths_2 as
select
count(p.path) as count, p.path
from
(select STRING_AGG(event, '>' order by tstamp) as path
from events17_by_uid_time
group by uid) as p
-- position returns non-zero if substring present in string --
where position('>purchase' in p.path) > 0
group by p.path
order by count desc;
SELECT 118
dgolub=> select sum(count) from purchase_paths_2 ;
sum
------
1600
```
Потерянные пользователи нашлись. Значит, после покупки тоже могут быть события, например, прохождения тренировок.
Удалил временную таблицу `purchase_paths_2` и `purchase_paths`, создал новую `purchase_paths` вторым способом
(через `position`).
Интересно посмотреть пути этих трёх пользователей:
```
dgolub=> select
count(p.path) as count, p.path
from
(select STRING_AGG(event, '>' order by tstamp) as path
from events17_by_uid_time
group by uid) as p
where position('>purchase' in p.path) > 0 and not right(p.path, 9) = '>purchase'
group by p.path
order by count desc;
count | path
-------+--------------------------------------------------------------------------------------------
1 | registration>tutorial_start>tutorial_finish>level_choice>training_choice>tutorial_start>tutorial_finish>tutorial_start>tutorial_finish>purchase>tutorial_start
1 | registration>tutorial_start>tutorial_finish>tutorial_start>tutorial_finish>level_choice>training_choice>tutorial_start>tutorial_finish>tutorial_start>tutorial_finish>purchase>tutorial_start>tutorial_finis
h
1 | registration>tutorial_start>tutorial_finish>tutorial_start>tutorial_finish>level_choice>training_choice>tutorial_start>tutorial_finish>tutorial_start>tutorial_start>tutorial_finish>tutorial_start>tutorial
_finish>purchase>tutorial_start>tutorial_finish>tutorial_start>tutorial_finish
```
Уточним нашу схему:
~~~graphviz
digraph user_paths {
# stages (or states of our finite automata)
rankdir="LR";
node [shape=box fontname="DejaVu Sans-10"];
edge [fontname="DejaVu Sans-8"];
REG [label="Регистрация\n 19926", color="red", fontcolor="red"];
TUTB [label="Начато\nобучение\n 11858", color="green", fontcolor="green"];
TUTE [label="Закончено\nобучение\n 10250", color="blue", fontcolor="blue"];
SLVL [label="Выбор уровня\nсложности\n 8342", color="orange", fontcolor="orange"];
SFREE [label="Выбор набора\nбесплатных\nтренировок\n 5737", color="violet", fontcolor="violet"];
BUY [label="Покупка\nплатных\nтренировок\n 1600", color="black", fontcolor="black"]
# Transitions
REG -> TUTB [color="red"];
REG -> SLVL [label="98", color="red", fontcolor="red"];
TUTB -> TUTE [label=10250, color="green", fontcolor="green"];
TUTB -> SLVL [label=743, color="green", fontcolor="green"];
TUTE -> TUTB [color="blue", fontcolor="blue"];
TUTE -> SLVL [label=7501, color="blue", fontcolor="blue"];
SLVL -> SFREE [color="orange"];
SFREE -> TUTB [color="violet"];
SFREE -> BUY [color="violet"];
BUY -> TUTB [label=3, color="black"];
}
~~~
Интересно посчитать, сколько пользователей двигались по тем или иным стрелкам в нашей схеме. Например, сколько закончивших обучение сразу повторяли его?
Для этого нужно искать определённые фрагменты в путях пользователей. Но для общей схемы таблица `purchase_paths` не годится, так как в ней речь идёт только
о покупателях. Создам общую таблицу путей пользователей в системе, включая пути без покупок.
```
create temporary table user_paths as
select
count(p.path) as count, p.path
from
(select STRING_AGG(event, '>' order by tstamp) as path
from events17_by_uid_time
group by uid) as p
group by p.path
order by count desc;
SELECT 626
```
Пользователи изобретательны: между 6 возможными событиями они прошли 626-ю разными путями (включая регистрацию, за которой ничего не следует).
А сколько пользователей прошло по каждому вектору?
```
select sum(count) from user_paths where position('tutorial_finish>tutorial_start' in path) > 0;
```
Количество пользователей по остальным переходам получается аналогично.
Уточнённый граф:
~~~graphviz
digraph user_paths {
# stages (or states of our finite automata)
rankdir="LR";
node [shape=box fontname="DejaVu Sans-10"];
edge [fontname="DejaVu Sans-8"];
REG [label="Регистрация\n 19926", color="red", fontcolor="red"];
TUTB [label="Начато\nобучение\n 11858", color="green", fontcolor="green"];
TUTE [label="Закончено\nобучение\n 10250", color="blue", fontcolor="blue"];
SLVL [label="Выбор уровня\nсложности\n 8342", color="orange", fontcolor="orange"];
SFREE [label="Выбор набора\nбесплатных\nтренировок\n 5737", color="violet", fontcolor="violet"];
BUY [label="Покупка\nплатных\nтренировок\n 1600"]
# Transitions
REG -> TUTB [label="11858", color="red", fontcolor="red"];
REG -> SLVL [label="98", color="red", fontcolor="red"];
TUTB -> TUTE [label="10250", color="green", fontcolor="green"];
TUTB -> SLVL [label="899", color="green", fontcolor="green"];
TUTB -> SFREE [label=23, color="green", fontcolor="green"];
TUTB -> BUY [label=51, color="green", fontcolor="green"];
TUTE -> TUTB [label="1776", color="blue", fontcolor="blue"];
TUTE -> SLVL [label="7345", color="blue", fontcolor="blue"];
TUTE -> SFREE [label="20", color="blue", fontcolor="blue"];
TUTE -> BUY [label="213", color="blue", fontcolor="blue"];
SLVL -> TUTB [label="490", color="orange", fontcolor="orange"];
SLVL -> TUTE [label=18, color="orange", fontcolor="orange"];
SLVL -> SFREE [label="5694", color="orange", fontcolor="orange"];
SFREE -> TUTB [label=903, color="violet", fontcolor="violet"];
SFREE -> TUTE [label=18, color="violet", fontcolor="violet"];
SFREE -> BUY [label=1336, color="violet", fontcolor="violet"];
BUY -> TUTB [label=3];
}
~~~
Если ограничиться только покупателями и смотреть переходы в таблице `purchase_paths`, станут виднее
пути, которые ведут к покупке тренировок:
~~~graphviz
digraph user_paths {
# stages (or states of our finite automata)
rankdir="LR";
node [shape=box fontname="DejaVu Sans-10"];
edge [fontname="DejaVu Sans-8"];
REG [label="Регистрация\n 1600", color="red", fontcolor="red"];
TUTB [label="Начато\nобучение\n1578", color="green", fontcolor="green"];
TUTE [label="Закончено\nобучение\n1447", color="blue", fontcolor="blue"];
SLVL [label="Выбор уровня\nсложности\n1600", color="orange", fontcolor="orange"];
SFREE [label="Выбор набора\nбесплатных\nтренировок\n1600 ", color="violet", fontcolor="violet"];
BUY [label="Покупка\nплатных\nтренировок\n 1600"]
# Transitions
REG -> TUTB [label="1578", color="red", fontcolor="red"];
REG -> SLVL [label="22", color="red", fontcolor="red"];
TUTB -> TUTE [label="1447", color="green", fontcolor="green"];
TUTB -> SLVL [label="159", color="green", fontcolor="green"];
TUTB -> BUY [label=51, color="green", fontcolor="green"];
TUTB -> SFREE [label="4", color="green", fontcolor="green"];
TUTE -> SLVL [label="1419", color="blue", fontcolor="blue"];
TUTE -> BUY [label="213", color="blue", fontcolor="blue"];
TUTE -> TUTB [label="195", color="blue", fontcolor="blue"];
TUTE -> SFREE [label="9", color="blue", fontcolor="blue"];
SLVL -> SFREE [label="1587", color="orange", fontcolor="orange"];
SLVL -> TUTB [label="9", color="orange", fontcolor="orange"];
SLVL -> TUTE [label="4", color="orange", fontcolor="orange"];
SFREE -> BUY [label=1336, color="violet", fontcolor="violet"];
SFREE -> TUTB [label="258", color="violet", fontcolor="violet"];
SFREE -> TUTE [label="6", color="violet", fontcolor="violet"];
BUY -> TUTB [label=3];
}
~~~
Что интересного видно из этих схем переходов?
* Прохождение обучения — важный этап на пути к покупке тренировок. Но на этапах от прохождения обучения до выбора
уровня сложности и особенно от выбора сложности до выбора бесплатных тренировк теряется много пользователей.
* Все покупатели выбирали уровень сложности и проходили бесплатные тренировки.
* Переход от регистрации сразу к выбору уровня сложности имеет аномально высокую конверсию: из 98 пользователей
выполнивших этот переход, образовалось 22 покупателя.
* Если пользователь дошёл до выбора бесплатных тренировок, есть высокий шанс покупки (около 28%). Важно пользователя до этого
этапа довести, не потерять по дороге.
<file_sep>/03_time_analysis.md
# Анализ времени прохождения этапов
## представление "время регистрации"
```
dgolub=> select user_id, start_time as registration_time from evts17 where event_type='registration' limit 4;
user_id | registration_time
---------+---------------------
27832 | 2017-01-01 03:48:40
27833 | 2017-01-01 04:07:25
27834 | 2017-01-01 08:35:10
27835 | 2017-01-01 11:54:47
```
Сохраняем в представлении:
```
dgolub=> create view c8_registration_ts as
dgolub-> select user_id, start_time as registration_ts from evts17 where event_type='registration';
CREATE VIEW
```
## Представление "начало обучения"
Аналогично для начала обучения. Тут нас ждёт подводный камень: многие пользователи начинают обучение больше одного раза.
Поэтому применим группировку по пользователям и выберем минимальную отметку времени (получится первое начало обучения).
```
dgolub=> select user_id, min(start_time) as tut_start_ts from evts17 where event_type='tutorial_start' group by user_id order by min(start_time) limit 4;
user_id | tut_start_ts
---------+---------------------
27836 | 2017-01-01 14:54:40
27835 | 2017-01-01 15:00:51
27833 | 2017-01-01 17:47:40
27839 | 2017-01-01 19:11:36
```
```
dgolub=> create view c8_tutorial_start_ts as
dgolub-> select user_id, min(start_time) as tut_start_ts from evts17 where event_type='tutorial_start' group by user_id order by min(start_time);
CREATE VIEW
```
Учебник рекомендует ещё сохранить `tutorial_id`, добавим его в представление, но как? При каждом начале обучения формируется новый `tutorial_id`.
Заметим, что эти ID возрастают. Пример запроса, в выдаче которого видно возрастание Tutorial ID:
```
dgolub=> select user_id, start_time as tut_start, tutorial_id from evts17
where event_type='tutorial_start' and
user_id in (
select user_id from evts17 where event_type='tutorial_start' group by user_id having count(tutorial_id) > 5
)
limit 40;
```
Значит, как и со временем начала обучения (`start_time`), для исключения многозначности достаточно будет взять минимальный `tutorial_id`;
```
drop view c8_tutorial_start_ts;
DROP VIEW
dgolub=> create view c8_tutorial_start_ts as
dgolub-> select user_id, min(start_time) as tut_start_ts, min(tutorial_id) as tut_id from evts17 where event_type='tutorial_start' group by user_id;
CREATE VIEW
dgolub=> select * from c8_tutorial_start_ts limit 6;
user_id | tut_start_ts | tut_id
---------+---------------------+--------
44127 | 2017-11-07 20:29:47 | 46257
39224 | 2017-07-26 06:33:18 | 41958
30052 | 2017-02-13 21:48:59 | 33554
37083 | 2017-06-14 05:49:57 | 39977
37876 | 2017-06-26 17:33:33 | 40757
31297 | 2017-03-06 22:19:58 | 34655
```
## Окончание обучения
Сначала поступим по-простому: выделим время окончания обучения для пользователей:
```
dgolub=> select user_id, start_time as tut_finish_ts from evts17 where event_type='tutorial_finish' limit 40;
user_id | tut_finish_ts
---------+---------------------
27835 | 2017-01-01 15:06:15
27836 | 2017-01-01 15:42:58
...
```
В получившемся списке видно, что по крайней мере некоторые пользователи заканчивали обучение больше одного раза,
ну и из предыдущего изучения `tutorial_start` это более-менее очевидно. А сколько раз можно было закончить
обучение?
```
dgolub=> select user_id, count(start_time) from evts17 where event_type='tutorial_finish' group by user_id order by count(start_time) desc limit 5;
user_id | count
---------+-------
43890 | 9
36305 | 9
44532 | 9
33775 | 9
35713 | 9
```
Просто взять самое раннее окончание обучения не получается, так как нам нужно расчитать время прохождения обучения. Но есть поле `tutorial_id`, и в созданном
ранее представлении `c8_tutorial_start_ts` тоже есть `tutorial_id`. Можем выделить тех пользователей, которые закончили первое начатое обучение,
сопоставляя `tutorial_id` в представлении `c8_tutorial_start_ts` и в `evts17`.
```
dgolub=> select user_id, start_time as tut_finish_ts, tutorial_id as tut_id from evts17 where event_type='tutorial_finish' and tutorial_id in (select tut_id from c8_tutorial_start_ts) limit 5;
user_id | tut_finish_ts | tut_id
---------+---------------------+--------
27835 | 2017-01-01 15:06:15 | 31506
27833 | 2017-01-01 17:50:08 | 31508
27839 | 2017-01-01 19:16:32 | 31509
27834 | 2017-01-01 19:48:01 | 31510
27845 | 2017-01-02 03:06:48 | 31512
```
Сравнивая количество пользователей в представлении `c8_tutorial_start_ts` (11858) и результатах получившегося запроса (9830), видна большая потеря пользователей.
Возможно, надо сопоставлять окончание обучения с его началом до группировки по пользователям? Проверим.
Сколько мы можем найти уникальных пользователей, у которых существует пройденное от начала до конца обучение?
```
dgolub=> select count(distinct tf.user_id) as uids
from
(select user_id, start_time as tut_start_ts, tutorial_id as tut_id from evts17 where event_type='tutorial_start' order by user_id, start_time) as ts
inner join
(select user_id, start_time as tut_finish_ts, tutorial_id as tut_id from evts17 where event_type='tutorial_finish' order by user_id, start_time) as tf
using (user_id, tut_id);
uids
-------
10250
```
Число согласуется с полученными ранее. А не уникальных (убрал `distinct`) получается 14904, поэтому снова применим группировку и выделение самого раннего
из пройденных обучений. Как и ранее, запишем результат во view:
```
create view c8_tutorial_time as
select tf.user_id as uid, min(ts.tut_start_ts) as tut_start_ts, min(tf.tut_finish_ts) as tut_finish_ts, (min(tf.tut_finish_ts) - min(ts.tut_start_ts)) as learn_time
from
(select user_id, start_time as tut_start_ts, tutorial_id as tut_id from evts17 where event_type='tutorial_start' order by user_id, start_time) as ts
inner join
(select user_id, start_time as tut_finish_ts, tutorial_id as tut_id from evts17 where event_type='tutorial_finish' order by user_id, start_time) as tf
using (user_id, tut_id)
group by uid
order by uid;
dgolub=> select * from c8_tutorial_time limit 5;
uid | tut_start_ts | tut_finish_ts | learn_time
-------+---------------------+---------------------+------------
27833 | 2017-01-01 17:47:40 | 2017-01-01 17:50:08 | 00:02:28
27834 | 2017-01-01 19:46:11 | 2017-01-01 19:48:01 | 00:01:50
27835 | 2017-01-01 15:00:51 | 2017-01-01 15:06:15 | 00:05:24
27836 | 2017-01-01 15:40:43 | 2017-01-01 15:42:58 | 00:02:15
27839 | 2017-01-01 19:11:36 | 2017-01-01 19:16:32 | 00:04:56
```
У нас образовалась колонка со временем прохождения обучения. Посчитаем по ней некоторые показатели:
```
dgolub=> select avg(learn_time) from c8_tutorial_time;
avg
-----------------
00:03:52.931512
dgolub=> select percentile_cont(0.5) within group (order by learn_time) from c8_tutorial_time;
percentile_cont
-----------------
00:03:42
dgolub=> select max(learn_time) from c8_tutorial_time;
max
----------
00:10:06
dgolub=> select min(learn_time) from c8_tutorial_time;
min
----------
00:00:16
dgolub=> select percentile_cont(0.8) within group (order by learn_time) from c8_tutorial_time;
percentile_cont
-----------------
00:05:26
```
Среднее время прохождения обучения и медианное время очень близки, и 80% пользователей проходят
обучение менее, чем за пять с половиной минут.
Каково же распределение времени обучения? Тут нам понадобится Python для создания гистограммы:

## А8.5.7 Самостоятельная работа:
> Определите для пользователей, зарегистрировавшихся в 2017 году, следующие параметры:
> * Сколько в среднем для всех пользователей проходит времени между событием выбора уровня сложности тренировки до события выбора набора бесплатных тренировок?
> * Сколько в среднем для всех пользователей проходит времени между событием выбора набора бесплатных тренировок и первой оплатой?
### Время от выбора уровня сложности до выбора набора бесплатных тренировок
```
dgolub=> select count(user_id) from evts17 where event_type='level_choice';
count
-------
8342
dgolub=> select count(distinct user_id) from evts17 where event_type='level_choice';
count
-------
8342
```
Один выбор — один пользователь. Прекрасно. Аналогично для выбора бесплатных тренировок:
```
dgolub=> select count(user_id) from evts17 where event_type='training_choice';
count
-------
5737
dgolub=> select count(distinct user_id) from evts17 where event_type='training_choice';
count
-------
5737
```
Снова соотношение 1:1, поэтому две выдачи можно соединять по user_id в качестве ключа.
```
dgolub=> select user_id, lc_ts, tc_ts, (tc_ts - lc_ts) as time_diff from
(select user_id, start_time as lc_ts from evts17 where event_type='level_choice') as lc
inner join
(select user_id, start_time as tc_ts from evts17 where event_type='training_choice') as tc
using (user_id) limit 5;
user_id | lc_ts | tc_ts | time_diff
---------+---------------------+---------------------+-----------
27835 | 2017-01-01 20:37:22 | 2017-01-01 20:38:43 | 00:01:21
27839 | 2017-01-01 22:37:50 | 2017-01-01 22:42:54 | 00:05:04
27845 | 2017-01-02 06:19:18 | 2017-01-02 06:25:12 | 00:05:54
27849 | 2017-01-02 11:53:11 | 2017-01-02 11:59:26 | 00:06:15
27843 | 2017-01-02 14:09:58 | 2017-01-02 14:14:51 | 00:04:53
```
Сохраню результат как представление и посчитаю среднее и квартили.
```
dgolub=> select avg(time_diff) from c8_tc_lc_time_diff;
avg
-----------------
00:05:17.128464
dgolub=> select percentile_cont(0.5) within group (order by time_diff) from c8_tc_lc_time_diff;
percentile_cont
-----------------
00:04:57
```
Судя по тому, что среднее слегка больше медианы, у распределения есть правый «хвост».
Представление нам больше не нужно.
```
dgolub=> drop view c8_tc_lc_time_diff;
DROP VIEW
```
### Время между выбором бесплатных тренировок и первой оплатой
```
dgolub=> select user_id, tc.tc_ts, purs.pur_ts, (purs.pur_ts - tc_ts) as time_diff from
(select user_id, start_time as tc_ts from evts17 where event_type='training_choice') as tc
join
(select user_id, start_time as pur_ts from purs17) as purs
using (user_id) limit 5;
user_id | tc_ts | pur_ts | time_diff
---------+---------------------+---------------------+-----------------
27845 | 2017-01-02 06:25:12 | 2017-01-03 18:53:43 | 1 day 12:28:31
27865 | 2017-01-04 06:03:20 | 2017-01-04 14:46:10 | 08:42:50
27884 | 2017-01-04 16:22:03 | 2017-01-08 19:37:34 | 4 days 03:15:31
27910 | 2017-01-05 12:05:28 | 2017-01-07 12:11:34 | 2 days 00:06:06
27911 | 2017-01-05 17:40:37 | 2017-01-07 08:19:12 | 1 day 14:38:35
```
Представление, конечно, можно не создавать, но запросы получаются громоздкими. Например, для среднего:
```
select avg(purs.pur_ts - tc_ts) as avg_time_diff, percentile_cont(0.5) within group (order by (purs.pur_ts - tc_ts)) as median_time_diff from
(select user_id, start_time as tc_ts from evts17 where event_type='training_choice') as tc
join
(select user_id, start_time as pur_ts from purs17) as purs
using (user_id);
avg_time_diff | median_time_diff
------------------------+-------------------
3 days 17:46:53.403125 | 3 days 12:51:25.5
```
Среднее снова немного больше медианы.
<file_sep>/a8.py
#!/usr/bin/env python
import pandas as pd
import psycopg2
# there are two modules with only constants defined: one for local DB
# and another for remote (SkillFactory) database. Only one to be enabled
# in any given time
# ---
# from SkillFactory_DB import DB_NAME, DB_USER, DB_HOST, DB_PORT, DB_PASSWD
from Local_DB import DB_NAME, DB_USER, DB_HOST, DB_PORT, DB_PASSWD
# constants
DB_CONNECT_STRING = "dbname={0} host={1} port={2} user={3} password={4}".format(
DB_NAME, DB_HOST, DB_PORT, DB_USER, DB_PASSWD
)
START_DATE = '2017-01-01' # this day will be included
END_DATE = '2018-01-01' # and this will be not
# template for SQL expression: all users registered btw two dates list
ALL_USERS_TMPL = """
SELECT DISTINCT user_id
FROM case8.events
WHERE event_type = 'registration'
AND start_time BETWEEN '{0}' AND '{1}'
"""
ALL_USERS = ALL_USERS_TMPL.format(START_DATE, END_DATE)
# Template for SQL query. Parameters:
# 0 - table alias,
# 1 - list of fields to get or '*'
# 2 - name of table to query
QUERY_TMPL = ("""
WITH
all_users as (
{0}
)
""".format(ALL_USERS) + "\n" +
""" SELECT {0}.{1}
FROM {2} as {0} join all_users using(user_id);
""")
purchases_query = QUERY_TMPL.format('p', '*', 'case8.purchase')
events_query = QUERY_TMPL.format('e','*','case8.events')
def init_connect(conn_string) -> psycopg2.extensions.cursor:
db_conn = psycopg2.connect(conn_string)
cursor = None
if db_conn:
db_conn.set_session(readonly=True,autocommit=True)
cursor = db_conn.cursor()
return cursor
if __name__ == "__main__":
cursor = init_connect(DB_CONNECT_STRING)
cursor.execute(purchases_query)
purchases = cursor.fetchall()
cursor.execute(events_query)
events = cursor.fetchall()
# Это немножко читерство: мы выбираем все действия всех пользователей, зарегистрированных в 2017 г.
events_df = pd.DataFrame(events, columns=('event_type', 'selected_level', 'start_time', 'tutorial_id', 'user_id', 'id'))
purchases_df = pd.DataFrame(purchases, columns=('user_id', 'start_time', 'amount', 'id'))
<file_sep>/05_level_analysis.md
# Исследование зависимости конверсии и платежей от выбранного уровня сложности
## Цель работы
### Гипотезы
проверить два предположения:
- Зависит ли вероятность оплаты от выбранного пользователем уровня сложности бесплатных тренировок?
- Существует ли разница во времени между выбором уровня сложности и оплатой между пользователями, выбирающими разные уровни сложности?
### Ограничения:
- результат должен быть в Jupyter Notebook.
- Данные пользователей, зарегистрированных в 2017 г.
Поскольку работаем в Jupyter, и база не моя, нельзя использовать представления и временные таблицы. Будем выкручиваться через CTE.
### Дополнительные условия
В учебной базе объём данных не слишком серьёзный. Но при обработке данных из БД
обычна ситуация, когда данных больше, чем может вместиться в памяти (особенно в
памяти персонального компьютера). К счастью, все данные и не нужно тащить в память —
у нас есть целая СУБД, которая сделает любые выборки, объединения и сортировки.
Нужно только правильно ей пользоваться.
## За работу!
Импорт библиотек:
```
import pandas as pd
import psycopg2
import matplotlib.pyplot as plt
```
Определение констант:
Чтобы не хранить пароли в ГитХабе (порочная практика :) ), записал их в отдельные
файлы и подключаю через импорт.
```
# there are two modules with only constants defined: one for local DB
# and another for remote (SkillFactory) database. Only one to be enabled
# in any given time
# ---
# from SkillFactory_DB import DB_NAME, DB_USER, DB_HOST, DB_PORT, DB_PASSWD
from Local_DB import DB_NAME, DB_USER, DB_HOST, DB_PORT, DB_PASSWD
# constants
DB_CONNECT_STRING = "dbname={0} host={1} port={2} user={3} password={4}".format(
DB_NAME, DB_HOST, DB_PORT, DB_USER, DB_PASSWD
)
```
Начальное и конечное время для исследования. Первое включается в диапазон, второе нет.
```
START_DATE = '2017-01-01' # this day will be included
END_DATE = '2018-01-01' # and this will be not
```
Далее множество шаблонов для CTE и SQL запросов.
```
# template for SQL expression: all users registered btw two dates list
ALL_USERS_TMPL = """
SELECT DISTINCT user_id
FROM case8.events
WHERE event_type = 'registration'
AND start_time BETWEEN '{0}' AND '{1}'
"""
# Только покупатели
BUYERS_TMPL = """
SELECT DISTINCT user_id
FROM case8.purchase
INTERSECT
SELECT DISTINCT user_id
FROM case8.events
WHERE event_type = 'registration'
AND start_time BETWEEN '{0}' AND '{1}'
"""
# Теперь выделим пользователей и покупателей заданного временного диапазона
USERS = ALL_USERS_TMPL.format(START_DATE, END_DATE)
BUYERS = BUYERS_TMPL.format(START_DATE, END_DATE)
# и запишем CTE для этих групп (Практически списков USER_ID - ов)
USERS17_CTE = """users_2017 as (
{}
)""".format(USERS)
BUYERS17_CTE = """buyers_2017 as (
{}
)""".format(BUYERS)
# Вместо представлений определим CTE для событий, производимых пользователями
# 2017 года регистрации, и их покупок
EVENTS17_CTE = """events_2017 as (
select * from case8.events
inner join
users_2017
using (user_id)
)"""
PURCHASES17_CTE = """purchases_2017 as (
select * from case8.purchase
inner join
users_2017
using (user_id)
)"""
```
## Зависит ли вероятность оплаты от выбранного пользователем уровня сложности бесплатных тренировок?
Вооружившись таким набором констант, соберём на стороне сервера CTE для списков пользователей, выбирающих разные уровни сложности
в приложении. Уровней у нас всего три: `hard`, `medium` и `easy`. Будут и три CTE: для трудного, среднего и лёгкого уровней,
общий формат имён CTE: `<level>_users_17`:
```
LVL_CTE_TMPL = """{0}_users_2017 as (
SELECT DISTINCT user_id
FROM events_2017
WHERE event_type = 'level_choice' AND
selected_level = '{0}'
)"""
HARD_USERS_CTE = LVL_CTE_TMPL.format('hard')
MEDIUM_USERS_CTE = LVL_CTE_TMPL.format('medium')
EASY_USERS_CTE = LVL_CTE_TMPL.format('easy')
```
Определю функцию, которая соединяется с базой, настраивает параметры соединения,
создаёт курсор и возвращает его.
```
def init_connect(conn_string: "PostgreSQL connection string") -> psycopg2.extensions.cursor:
"""Connect to DB using connection string from 1st parameter. Return the cursor"""
db_conn = psycopg2.connect(conn_string)
cursor = None
if db_conn:
db_conn.set_session(readonly=True,autocommit=True)
cursor = db_conn.cursor()
return cursor
```
И мы почти готовы посчитать конверсию по пользвователям разных уровней сложности:
```
curr_cte = 'with ' + ', '.join((USERS17_CTE, EVENTS17_CTE, PURCHASES17_CTE, HARD_USERS_CTE, MEDIUM_USERS_CTE, EASY_USERS_CTE))
lvl_req_template = """
select
count(user_id) as total_users,
count(amount) as buyers,
sum(amount) as revenue,
count(amount)*1.0/count(user_id) as "conversion",
avg(amount) as avg_check
from
{}_users_2017
left join
purchases_2017
using (user_id)
"""
##
## XXX Не проще ли тут использовать group by в запросе?
##
conversion_request = curr_cte + " " + " UNION ALL ".join([lvl_req_template.format(lvl) for lvl in ('hard', 'medium', 'easy')]) + ";"
print("Will execute SQL query:\n" + conversion_request)
cursor = init_connect(DB_CONNECT_STRING)
cursor.execute(conversion_request)
ret = cursor.fetchall()
conv_df = pd.DataFrame(ret, columns=('users', 'buyers', 'revenue', 'conversion', 'avg_check'), index=('hard', 'medium', 'easy'))
print(conv_df.to_string(formatters={'conversion': '{:.2%}'.format, 'avg_check': '{:.2f} р.'.format}))
```
В результате выводится табличка:
| level | users | buyers | revenue | conversion | avg_check |
|:---------|--------:|-----------:|----------:|-----------:|-----------:|
| hard | 1249 | 442 | 49235 | 35.39% | 111.60 р. |
| medium | 4645 | 969 | 106125 | 20.86% | 109.52 р. |
| easy | 2448 | 189 | 21725 | 7.72% | 114.95 р. |
### Вывод по первому вопросу:
Существует зависимость между уровнем сложности и конверсией. Пользователи, которые выбирают уровни
_hard_ и _medium_, чаще оплачивают тренировки. При этом больше всего прибыли приносят пользователи
уровня _medium_ за счёт большего числа таких пользователей.
Зависимости между средним чеком и уровнем сложности тренировок не обнаружено.
## Исследование временных промежутков между выбором уровня и оплатой.
Нужно построить представление, в котором будет колонки: `user_id`, `selected_level`,
`level_choice_time_stamp`, `purchase_time_stamp`, `time_difference`. Названия говорят
сами за себя. Для этого объединим CTE `events_2017` и `purchases_2017` через INNER JOIN
по полю `user_id`, тогда останутся только покупатели.
```
curr_cte = 'with ' + ', '.join((USERS17_CTE, EVENTS17_CTE, PURCHASES17_CTE))
cursor.execute(curr_cte + """
select
user_id,
selected_level,
lc.start_time as level_choice_ts,
pur.start_time as purchase_ts,
(pur.start_time - lc.start_time) as time_diff
from
events_2017 as lc
inner join
purchases_2017 as pur
using(user_id)
where lc.event_type='level_choice'
limit 20;
""")
ret = cursor.fetchall()
# И это немножко замороченное выражение печатает пример данных после фильтрации и объединения
# Проще было преобразовать результаты запроса в датафрейм и напечатать средствами Pandas.
print("{0:8s} {1:8s} {2:23s} {3:23s} {4:20s}\n{5}".format(
"User ID", "Level", "Lvl choice time", "Purchase time", "Interval", '-'*85
))
print('\n'.join(['\t'.join([str(f) for f in l]) for l in ret]))
```
Выражение, которое выбирает данные, построено, осталось их сгруппировать и посчитать
средние значения.
```
cursor.execute(curr_cte + """
select lc.selected_level, avg(pur.start_time - lc.start_time) as avg_time_diff
from
events_2017 as lc
inner join
purchases_2017 as pur
using(user_id)
where event_type='level_choice'
group by selected_level
order by avg_time_diff;
""")
ret = cursor.fetchall()
avg_intervals_by_lvl = pd.DataFrame.from_records(ret, columns=('Level', 'Avg. Interval'), index='Level')
print(avg_intervals_by_lvl)
```
Мы видим, что в среднем покупатель, выбравший уровень _medium_, думает над покупкой на 16 часов дольше,
чем выбравший уровень _hard_, а покупатели уровня _easy_ занимают промежуточное положение.
Среднее даёт нам ограниченную информацию, было бы интереснее сравнить распределение интервалов между
выбором уровня и покупкой для разных уровней. Для этого вспомним, что покупателей не так уж и много,
и сделаем выборку данных в таблице "уровень-интервал" для каждого из них.
Практически это предыдущий запрос, но без группировки.
```
cursor.execute(curr_cte + """
select lc.selected_level, (pur.start_time - lc.start_time) as avg_time_diff
from
events_2017 as lc
inner join
purchases_2017 as pur
using(user_id)
where event_type='level_choice';
""")
ret = cursor.fetchall()
tdiff_by_lvl = pd.DataFrame.from_records(ret, columns=('level', 'tdiff'))
tdiff_by_lvl.loc[:,'level'] = tdiff_by_lvl.level.astype('category')
print(tdiff_by_lvl.info())
```
Если бы данных было действительно много, можно было бы расчитать в СУБД персентили с интервалом, например, 5%,
и построить график по ним.
Данные собраны, осталось их визуализировать. Тут есть сложности, потому что тип данных `timedelta64[ns]`
не совсем числовой.
На [StackOverflow](https://stackoverflow.com/questions/23543909/plotting-pandas-timedelta) подсказывают,
что можно преобразовать интервалы в какую-нибудь единицу времени. Нам здесь не надо очень дробно, часов
вполне достаточно:
```
tdiff_by_lvl[tdiff_by_lvl.level == 'hard'].tdiff.astype('timedelta64[h]').plot.hist()
td = tdiff_by_lvl
td.loc[:,'tdiff'] = td.tdiff.astype('timedelta64[h]')
td.plot.box(by='level')
```
<file_sep>/04_training_relation_with_purchase.md
# Взаимосвязь прохождения обучения и покупки тренировок
## Разбиение пользователей на группы
### Прошли обучение
> Сначала определим пользователей, которые прошли обучение хотя бы раз
Это такие пользователи, у которых есть хотя бы одно событие `tutorial_finish`.
Эти пользователи получаются из базы селектом:
```
select distinct user_id from evts17 where event_type='tutorial_finish'
```
Мы уже знаем, что таких пользователей 10250.
### Начали обучение, но не прошли его ни разу.
У этих пользователей есть событие `tutorial_start`, но нет события `tutorial_finish`;
Как получается такая выборка?
```
select distinct user_id from evts17 where event_type='tutorial_start'
except
select distinct user_id from evts17 where event_type='tutorial_finish'
limit 5;
user_id
---------
39224
37083
34261
33957
37922
```
И сколько таких пользователей?
```
select count (user_id) from
(select distinct user_id from evts17 where event_type='tutorial_start'
except
select distinct user_id from evts17 where event_type='tutorial_finish'
) as t;
count
-------
1608
```
### Не начинали обучение вовсе
> последняя группа пользователей — те, кто ни разу не проходил обучение, а сразу же перешел к выбору уровня сложности тренировок.
> У таких пользователей отсутствует событие `tutorial_start`.
Замечу, что в большинстве своём это будет пользователи, которые зарегистрировались и ничего больше не делали.
```
select distinct user_id from evts17
except
select distinct user_id from evts17 where event_type='tutorial_start'
limit 5;
user_id
---------
47051
35634
40694
28031
42422
```
И таких пользователей...
```
dgolub=> select count(u.user_id) from (select distinct user_id from evts17
except
select distinct user_id from evts17 where event_type='tutorial_start') as u
;
count
-------
8068
```
Проверяем, что сумма сошлась. Это надо бы бы по-хорошему переписать.
```
select 'Registered:' as type, count(distinct user_id) as count from evts17
union all
select 'Finished Tutorial', count(distinct user_id) from evts17 where event_type='tutorial_finish'
union all
select 'Not finished tutorial', count(user_id) from (
select distinct user_id from evts17 where event_type='tutorial_start'
except
select distinct user_id from evts17 where event_type='tutorial_finish'
) as ts
union all
select 'Not started tutorial', count(user_id) as nots_count from (
select distinct user_id from evts17
except
select distinct user_id from evts17 where event_type='tutorial_start'
) as nots
;
type | count
-----------------------+-------
Registered: | 19926
Finished Tutorial | 10250
Not finished tutorial | 1608
Not started tutorial | 8068
```
Выражения получаются громоздкие, создам представления для каждого из вариантов:
```
dgolub=> create view c8_finished_tutorial as
dgolub-> select distinct user_id from evts17 where event_type='tutorial_finish';
CREATE VIEW
dgolub=> create view c8_started_tutorial as
dgolub-> select distinct user_id from evts17 where event_type='tutorial_start'
dgolub-> except
dgolub-> select distinct user_id from evts17 where event_type='tutorial_finish';
CREATE VIEW
dgolub=> create view c8_not_started_tutorial as
dgolub-> select distinct user_id from evts17
dgolub-> except
dgolub-> select distinct user_id from evts17 where event_type='tutorial_start';
CREATE VIEW
```
## Определение конверсии пользователей в покупателей по группам
Базовый запрос при поиске конверсии и среднего чека будет выглядеть примерно так. Для подсчёта числа покупателей достаточно
сосчитать значения в колонке 'id', или 'amount', или 'start_time'.
```
select * from
c8_finished_tutorial
left join
purs17
using(user_id)
limit 40;
user_id | start_time | amount | id
---------+---------------------+--------+-------
44127 | | |
..........
37878 | 2017-06-30 17:05:21 | 150 | 17668
47216 | 2017-12-22 06:30:31 | 25 | 18396
35532 | 2017-05-21 04:23:32 | 150 | 17475
41011 | | |
```
### Группа закончивших обучение:
Конверсия:
```
dgolub=> select round(count(id)*100.0/count(user_id),1) from
c8_finished_tutorial
left join
purs17
using(user_id);
round
-------
14.1
```
Средний чек:
```
dgolub=> select round(avg(amount), 2)
from c8_finished_tutorial
left join
purs17
using(user_id);
round
--------
110.99
```
Итак, в группе закончивших обучение конверсия 14.1% и средний чек 110 р.
### Группа начавших обучение
Совершенно аналогично:
```
dgolub=> select round(count(id)*100.0/count(user_id),1) from
c8_started_tutorial
left join
purs17
using(user_id);
round
-------
8.1
dgolub=> select round(avg(amount), 2) from c8_started_tutorial
left join
purs17
using(user_id);
round
--------
104.96
```
В группе начавших обучение конверсия 8.1% и средний чек 104 р.
### Группа не начнавших обучение
```
dgolub=> select round(count(id)*100.0/count(user_id),1) from
c8_not_started_tutorial
left join
purs17
using(user_id);
round
-------
0.3
dgolub=> select round(avg(amount), 2) from c8_not_started_tutorial
left join
purs17
using(user_id);
round
--------
128.41
```
Эта группа с очень маленькой конверсией (0.3%), но средний чек заметно выше, чем в первых двух группах.
#### Подгруппа: не начинавшие обучение, но сразу выбравшие уровень сложности
Для упрощения выражений тоже создам представление, назову его `c8_hurried_users`:
```
create view c8_hurried_users as
select user_id
from
c8_not_started_tutorial
join
evts17
using (user_id)
where event_type='level_choice';
```
При запуске этого запроса получаем:
```
CREATE VIEW
dgolub=> select count(*) from c8_hurried_users;
count
-------
98
```
Из схем переходов выше мы знаем, что именно это число пользователей выбрало уровень сложности сразу после регистрации.
Посчитаем конверсию в этой подгруппе:
```
select round(count(id)*100.0/count(user_id),1)
from
c8_hurried_users
left join
purs17
using(user_id);
```
При запуске получаем:
```
round
-------
22.4
```
И средний чек мы уже знаем:
```
dgolub=> select round(avg(amount),2)
from
c8_hurried_users
left join
purs17
using(user_id);
round
--------
128.41
```
Итак, получили подгруппу с аномально высокой конверсией (22.4%) и высоким средним чеком. Могу предположить, что это пользователи,
повторно устанавливающие приложение, например, после ремонта устройства. В обучении они уже не нуждаются, знают, чего хотят, и
готовы за это платить. Было бы полезно обратить внимание на эту подгруппу пользователей.
Возможно, есть смысл предусмотреть в приложении возможность сохранения состояния в «облако» и его восстановления.
### Итоги изучения конверсии и среднего чека по группам
Подсчёты конверсии и среднего чека по разным группам пользователей подтверждают, что прохождение обучения до конца благотворно
влияет на желание пользователя оплачивать тренировки.
| Группа пользователей | Конвесия % | Средний чек |
|:--------------------------------------------------|--------------:|------------:|
| Не проходили обучение | 0.3 | 128.41 |
| Начали обучение, но не закончили | 8.1 | 105 |
| Закончили обучение | 14.1 | 111 |
<file_sep>/01_tables_explore.md
# Анализ пользовательских событий (повторяю рассуждения из учебника, но использую по возможности SQL вместо Python).
Мотивация такого подхода: конечно, всё можно загрузить в Pandas и пользоваться его методами. Но ресурсы компьютера обычно
ограничены, а тут у нас есть под рукой целая база данных, которая какие надо выборки и сортировки великолепно делает.
> Сколько строк содержится в датафрейме events_df? (для ответа используйте данные за 2017 год)
```
dgolub=> select count(e.id)
from case8.events as e
where user_id in (select distinct user_id from case8.events where event_type='registration' and start_time between '2017-01-01' and '2018-01-01');
count
-------
66959
(1 row)
```
> Сколько непустых значений содержится в столбце selected_level? (для ответа используйте данные за 2017 год)
```
dgolub=> select count(e.selected_level)
from case8.events as e
where user_id in (select distinct user_id from case8.events where event_type='registration' and start_time between '2017-01-01' and '2018-01-01');
count
-------
8342
(1 row)
```
Аналогично можно поступить с CTE:
```
dgolub=> with all_users as (
SELECT DISTINCT user_id
FROM case8.events
WHERE event_type = 'registration'
AND start_time BETWEEN '2017-01-01' AND '2018-01-01'
)
select count(e.selected_level) from case8.events as e join all_users as u using (user_id);
count
-------
8342
dgolub=> with all_users as (
SELECT DISTINCT user_id
FROM case8.events
WHERE event_type = 'registration'
AND start_time BETWEEN '2017-01-01' AND '2018-01-01'
)
select count(*) from case8.events as e join all_users as u using (user_id);
count
-------
66959
```
Для удобства создал представление `evts17`, в котором только пользователи, зарегистрированные в 2017 году.
```
create view evts17 as
select * from case8.events
where user_id in
(select distinct user_id from case8.events
where event_type='registration'
and
start_time between '2017-01-01' and '2018-01-01'
);
CREATE VIEW
dgolub=> select count(*) from evts17;
count
-------
66959
```
Аналогично создал представление purs17, где покупки, совершённые зарегистрированными в 2017 пользователями:
```
create view purs17 as
select * from case8.purchase
where user_id in (
select distinct user_id
from case8.events
where
event_type='registration'
and
start_time between '2017-01-01' and '2018-01-01'
);
dgolub=> select count(*) from purs17;
count
-------
1600
```
Структура представления повторяет соответствующие таблицы (в представление выбраны все колонки):
```
dgolub=> \d evts17
View "public.evts17"
Column | Type | Collation | Nullable | Default
----------------+-----------------------------+-----------+----------+---------
event_type | text | | |
selected_level | text | | |
start_time | timestamp without time zone | | |
tutorial_id | integer | | |
user_id | integer | | |
id | integer | | |
dgolub=> \d purs17
View "public.purs17"
Column | Type | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+---------
user_id | integer | | |
start_time | timestamp without time zone | | |
amount | integer | | |
id | integer | | |
```
> К примеру, посмотрим на `events_df`, если оставить в нем только такие строки, где `event_type` = `level_choice`:
```
dgolub=> select
count(event_type) c_evtype,
count(selected_level) as c_sellvl,
count(start_time) as c_starttm,
count(tutorial_id) as c_tut_id,
count(user_id) as c_usr_id,
count(id) as c_id
from evts17
where event_type='level_choice';
c_evtype | c_sellvl | c_starttm | c_tut_id | c_usr_id | c_id
----------+----------+-----------+----------+----------+------
8342 | 8342 | 8342 | 0 | 8342 | 8342
```
> Как видно, этот срез датафрейма не содержит пропущенных значений в столбце `selected_level`,
> но зато содержит пропуски в `tutorial_id`. Это связано с тем, что для событий типа level_choice
> не предусмотрена запись параметра `tutorial_id`.
> Теперь проверим аналогичные данные, но при условии, что срез будет содержать
> данные о событиях `tutorial_start` и `tutorial_finish`.
```
dgolub=> select
count(event_type) c_evtype,
count(selected_level) c_sellvl,
count(start_time) c_starttm,
count (tutorial_id) c_tut_id,
count(user_id) c_usr_id,
count(id) c_id
from evts17
where event_type in ('tutorial_finish', 'tutorial_start');
c_evtype | c_sellvl | c_starttm | c_tut_id | c_usr_id | c_id
----------+----------+-----------+----------+----------+-------
32954 | 0 | 32954 | 32954 | 32954 | 32954
```
> Давайте оценим, какие уникальные события есть в колонках `event_type` и `selected_level`:
```
dgolub=> select distinct event_type from evts17;
event_type
-----------------
training_choice
tutorial_finish
level_choice
tutorial_start
registration
dgolub=> select distinct selected_level from evts17;
selected_level
----------------
hard
medium
easy
```
Обращаю внимание: во второй выдаче есть пропуск (NULL). Но везде, где событие = `level_choice` , поле `selected_level` заполнено:
```
dgolub=> select distinct selected_level from evts17 where event_type='level_choice';
selected_level
----------------
hard
medium
easy
```
> Также оценим, какое количество пользователей совершали события:
> ...
> Сколько уникальных пользователей совершали события в датафрейме `events_df`?
> (для ответа используйте данные за 2017 год)
```
dgolub=> select count(distinct user_id) from evts17;
count
-------
19926
```
Кстати, посмотрю сразу и покупки -- количество покупателей и количество покупок:
```
dgolub=> select count(distinct user_id) from purs17;
count
-------
1600
dgolub=> select count(*) from purs17;
count
-------
1600
```
Никаких других данных, кроме покупок, в представлении `purs17` не содержится, пользователи покупают
тренировки (когда покупают) по одному разу.
> Есть ли пропущенные значения в датафрейме `purchase_df`?
```
dgolub=> select count(user_id) c_uid, count(start_time) c_time, count(amount) as c_amt, count(id) as c_id from purs17;
c_uid | c_time | c_amt | c_id
-------+--------+-------+------
1600 | 1600 | 1600 | 1600
```
> Снова обратимся к методу `describe()` для того, чтобы оценить характеристики каждого столбца датафрейма `purchase_df`
Каждый столбец нам тут совершенно не нужен, к тому же `user_id` и `id`, хоть и как бы числовые значения, но на самом деле
просто идентификаторы. А вот содержимое колонки `amount` стоит посмотреть:
```
dgolub=> select round(avg(amount),2) as avg_amount from purs17;
avg_amount
------------
110.73
dgolub=> select distinct amount from purs17;
amount
--------
300
25
100
250
150
50
200
```
Поиск медианы: На сайте [leafo.net](https://leafo.net/guides/postgresql-calculating-percentile.html) описаны
функции `percentile_disc` и `percentile_cont`, которые добавлены в PostgreSQL начиная с версии 9.4.
```
dgolub=> select percentile_cont(0.5) within group (order by amount) from purs17;
percentile_cont
-----------------
100
```
Персентиль 50% и есть медиана.
## Анализ событий (таблица `events`)
> Для того, чтобы понимать, как пользователи переходят из этапа в этап, на каких этапах
> возникают сложности, мы должны определить конверсию на каждом из этапов воронки. То
> есть нам нужно понять, какой процент пользователей переходит с предыдущего этапа
> на следующий.
> Посмотрим на количество пользователей, которые совершают событие *registration*
Немного дурной вопрос, мы же пользователей и ищем по событию registration. Это будет
количество уникальных пользователей (и пользователей вообще, так как вряд ли кто-то регистрируется
более одного раза. Хотя надо проверить).
```
dgolub=> select count(distinct user_id) from evts17 where event_type='registration';
count
-------
19926
dgolub=> select count(user_id) from evts17 where event_type='registration';
count
-------
19926
```
Всё нормально, дважды зарегистрированных пользователей нет.
### Анализ событий `tutorial_start` и `tutorial_finish`
> Посмотрим на количество пользователей, которые совершают событие tutorial_start:
```
dgolub=> select count(id) from evts17 where event_type='tutorial_start';
count
-------
18050
dgolub=> select count(distinct user_id) from evts17 where event_type='tutorial_start';
count
-------
11858
```
Событий заметно больше, чем уникальных пользователей, которые их совершают.
Видимо, заметная доля пользователей начинает обучение более одного раза.
### Исследуем пользователей, перешедших к обучению
> Давайте определим процент пользователей, которые перешли к выполнению обучения
> Каков процент пользователей, начавших обучение (от общего числа
> зарегистрировавшихся)? (для ответа используйте данные за 2017 год; ответ дайте с
> округлением до двух знаков после точки-разделителя)
```
dgolub=> select round(ts.count*100.0/reg.count,2) as ts_pct
from
(select count(distinct user_id) from evts17 where event_type='tutorial_start') as ts,
(select count(distinct user_id) from evts17 where event_type='registration') as reg;
ts_pct
--------
59.51
```
### Пользователи, завершившие обучение
> Какой процент пользователей, завершивших обучение (от числа пользователей, начавших
> обучение)? (для ответа используйте данные за 2017 год; ответ дайте с округлением до
> двух знаков после точки-разделителя)
```
dgolub=> select round(te.count*100.0/ts.count,2) as te_ts_pct
from
(select count(distinct user_id) from evts17 where event_type='tutorial_start') as ts,
(select count(distinct user_id) from evts17 where event_type='tutorial_finish') as te;
te_ts_pct
-----------
86.44
```
> В нашем приложении достаточно хороший процент прохождения обучения. Но есть куда
> стремиться для его увеличения. Подумайте о том, как показатель прохождения может
> влиять на весь путь пользователя в дальнейшем.
Есть закономерность, согласно которой вложенные усилия (например, в обучение) повышают шанс на то,
что и в дальнейшем будут предприниматься усилия («не можем же мы сейчас, когда столько усилий затратили,
всё бросить! Нужно затратить больше усилий!»). Можно ожидать больших долей сделавших
выбор уровня сложности и покупателей среди прошедших тренинг пользователей.
### Анализ события level_choice
#### Количество пользователей, которые сделали выбор уровня сложности
```
dgolub=> select count(user_id) from evts17 where event_type='level_choice';
count
-------
8342
dgolub=> select count(distinct user_id) from evts17 where event_type='level_choice';
count
-------
8342
```
Прекрасно, один и тот же пользователь не выбирает уровень сложности несколько раз. А сколько
это будет в процентах от общего числа зарегистрировавшихся?
```
select round(ls.count*100.0/reg.count,2) as ts_pct
from
(select count(distinct user_id) from evts17 where event_type='level_choice') as ls,
(select count(distinct user_id) from evts17 where event_type='registration') as reg;
ts_pct
--------
41.86
```
Почти 42% пользователей выбирают какой-нибудь уровень сложности. А зависит ли это от того, прошёл ли
пользователь обучение? Или хотя бы начинал ли его проходить?
Нужно придумать общее выражение для ситуации "доля пользователей, совершивших событие B, от пользователей,
совершивших событие A". На помощь приходит `LEFT JOIN`
Начнём с `tutorial_start`, посчитаем по количеству пользователей и процент:
```
select count(te.user_id) as te, count(ts.user_id) as ts
from
(select distinct user_id from evts17 where event_type='tutorial_start') as ts
left join
(select distinct user_id from evts17 where event_type='level_choice') as te using (user_id);
te | ts
------+-------
8244 | 11858
(1 row)
select round(count(lc.user_id) * 100 / count(ts.user_id), 2) as "lvl_choice%"
from
(select distinct user_id from evts17 where event_type='tutorial_start') as ts
left join
(select distinct user_id from evts17 where event_type='level_choice') as lc using (user_id);
lvl_choice%
-------------
69.00
(1 row)
```
Доля выбравших уровень сложности среди начавших обучение пользователей заметно выше, чем среди
всех пользователей ("валовая"). Посмотрим, поднимается ли эта доля по окончании обучения?
Для `tutorial_finish` аналогично (набрал прямо в `psql`:
```
dgolub=> select count(lc.user_id) as lc, count(tf.user_id) as tf
from (select distinct user_id from evts17 where event_type='tutorial_finish') as tf
left join (select distinct user_id from evts17 where event_type='level_choice') as lc using (user_id);
lc | tf
------+-------
7501 | 10250
dgolub=> select round(100.0 * count(lc.user_id) / count(tf.user_id), 2) as "lvl_choice%"
from (select distinct user_id from evts17 where event_type='tutorial_finish') as tf
left join (select distinct user_id from evts17 where event_type='level_choice') as lc using (user_id);
lvl_choice%
-------------
73.18
```
Видим, что среди закончивших обучение процент выбравших уровень ещё выше. Для контроля нужно
расчитать процент пользователей, которые не проходили обучение, но выбрали уровень.
```
with
curious as (
select distinct user_id from evts17 where event_type='tutorial_start'
),
ignorant as (
select user_id from evts17
where event_type='registration' and user_id not in (select user_id from curious)
),
ignorant_lc as (
select user_id from evts17
where event_type='level_choice' and user_id in (select user_id from ignorant)
)
select
count(lc.user_id) as lvl_choice,
count(ignorant.user_id) as ingorants
from
ignorant left join ignorant_lc as lc using (user_id);
lvl_choice | ingorants
------------+-----------
98 | 8068
```
В процентах это чуть больше 1.2, то есть необходимо зазывать пользователей на обучение.
Ещё один возможный путь — пользователь начал обучение, но не закончил и сразу перешёл к выбору уровня
сложности.
### Анализ события training_choice
Общее число пользователей. выбравших бесплатные тренировки (`training_choice`):
```
dgolub=> select count(user_id) from evts17 where event_type='training_choice';
count
-------
5737
```
И да, я проверил, что `distinct` ничего не меняет — тренировки пользователь выбирает один раз.
> Оценим процент таких пользователей от числа пользователей, которые выбрали уровень сложности:
```
select round(count(tc.user_id) * 100.0 / count(lc.user_id), 2) as "trn_choice%"
from
(select distinct user_id from evts17 where event_type='level_choice') as lc
left join
(select distinct user_id from evts17 where event_type='training_choice') as tc
using (user_id);
trn_choice%
-------------
68.77
```
Не все доходят. А есть ли среди пользователей этапа выбора тренировок такие, которые не выбирали уровень?
```
dgolub=> select count(distinct user_id) from evts17 where event_type='training_choice' and user_id not in (select distinct user_id from evts17 where event_type='level_choice');
count
-------
0
```
ОК, таких пользователей нет. Все пользователи, выбравшие бесплатные тренировки, сначала выбирали уровень сложности.
Проверка: замена в запросе `not in` на `in` даёт нам уже известное число пользователей, выбравших бесплатные тренировки.
## Исследование покупателей (таблица `purchase`)
> Рассчитаем процент пользователей percent_of_paying_users, которые оплатили тренировки от числа пользователей,
> которые выбрали бесплатные тренировки:
```
select round(buyers.count*100.0/trained.count,2) as buyers_pct
from
(select count(distinct user_id) from purs17) as buyers,
(select count(distinct user_id) from evts17 where event_type='training_choice') as trained;
buyers_pct
------------
27.89
```
> Какой процент пользователей, которые оплатили тренировки (от числа зарегистрировавшихся пользователей)?
```
dgolub=> select round(buyers.count*100.0/reg.count,2) as buyers_pct
from
(select count(distinct user_id) from purs17) as buyers,
(select count(distinct user_id) from evts17 where event_type='registration') as reg;
buyers_pct
------------
8.03
```
Итак, до покупки в 2017 году доходили чуть больше 8% зарегистрированых пользователей.
А есть ли такие покупатели, которые не выбирали уровень тренировок или не проходили бесплатных тренировок:
```
dgolub=> select count(distinct user_id) from purs17 where user_id not in (select distinct user_id from evts17 where event_type='level_choice');
count
-------
0
dgolub=> select count(distinct user_id) from purs17 where user_id in (select distinct user_id from evts17 where event_type='level_choice');
count
-------
1600
```
Аналогично с `training_choice`:
```
dgolub=> select count(distinct user_id) from purs17 where user_id not in (select distinct user_id from evts17 where event_type='training_choice');
count
-------
0
dgolub=> select count(distinct user_id) from purs17 where user_id in (select distinct user_id from evts17 where event_type='training_choice');
count
-------
1600
```
Прямой ответ — таких покупателей нет.
## Выводы после анализа событий
Все данные по выборке пользователей, зарегистрированных в 2017 году.
* Количество зарегистрировавшихся пользователей: 19926;
* Количество пользователей, начавших обучение : 11858;
* % пользователей, начавших обучение (от общего числа зарегистрировавшихся): 59.5;
* Количество пользователей, завершивших обучение: 10250;
* % пользователей, завершивших обучение (от начавших): 86.4;
* Количество пользователей, выбравших уровень сложности: 8342;
* % пользователей, выбравших уровень сложности тренировок (от общего числа зарегистрировавшихся): 41.9;
* Количество пользователей, выбравших набор бесплатных тренировок: 5737;
* % пользователей, выбравших набор бесплатных тренировок (от числа пользователей, которые выбрали уровень сложности): 68.8;
* Количество покупателей тренировок: 1600;
* % покупателей от числа пользователей, выбравших тренировки: 27.9;
* % покупателей от зарегистрированных пользователей: 8.03.
<file_sep>/make_html.sh
#!/bin/bash
pp thinking_a8.map |
/usr/bin/pandoc -f markdown -t html5 \
-o /tmp/think.html \
--self-contained \
--metadata title="Кейс A8" \
--toc \
-
# cleanup: remove temporary files
ls -1 | ag 'graphviz-[0-9a-f]{64}.png' | xargs rm
# -F ~/bin/pandoc-filter-graphviz \
|
55a7ab3649bf589375c2d4808c4e1ed3f28ff824
|
[
"Markdown",
"Python",
"Shell"
] | 7 |
Markdown
|
gdg-work/SkillFactory__SDA5__Case_A8
|
c824c0f456e54dbb885e538a2064cf216886f620
|
641ddae01476655580d3f5ec8d78dcbf7275bc3f
|
refs/heads/master
|
<file_sep>package gui;
import application.Main;
import application.Message;
import network.ClientHandler;
import network.ServerHandler;
import javax.swing.*;
import java.awt.*;
import java.time.LocalTime;
public class Gui {
JFrame jf;
JPanel content;
public Button btnHost, btnClient, btnSend, btnDisconnect;
public JTextField tfInput, tfName, tfIP; //einzeilge Eingabe
JScrollPane sp;
public JTextArea taChat; // die kann mehrere Zeilen haben
int width = 435, height = 580;
public void create (){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
jf = new JFrame("Chat");
jf.setSize(width, height);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(null);
jf.setLocationRelativeTo(null); // bei null ist es zentriert auf dem Bildschirm
jf.setResizable(false); //feste grösse des Fenster
content = new JPanel();
content.setBounds(0,0, width, height);
content.setLayout(null);
btnHost = new Button("Host");
btnHost.setBounds(10,10, 100, 25);
btnHost.setVisible(true);
btnHost.addActionListener(e ->{ //ist eine anonyme Funktion (aufsetzten des Server)
btnDisconnect.setEnabled(true);
ServerHandler.start();
Main.isHost = true;
});
content.add(btnHost);
btnClient = new Button("Client");
btnClient.setBounds(120,10, 100, 25);
btnClient.setVisible(true);
btnClient.addActionListener(e ->{ //ist eine anonyme Funktion (aufsetzten des Server)
if(!tfIP.getText().isEmpty()){
ClientHandler.ip = tfIP.getText();
}
ClientHandler.start();
Main.isHost = false;
});
content.add(btnClient);
JLabel lblName = new JLabel("Name:");
lblName.setBounds(10, 485, 50, 25);
content.add(lblName);
tfName = new JTextField();
tfName.setBounds(10, 510, 80, 25);
tfName.setVisible(true);
content.add(tfName);
JLabel lblIP = new JLabel("Server IP(leer für Localhost):");
lblIP.setBounds(100, 485, 200, 25);
content.add(lblIP);
tfIP = new JTextField();
tfIP.setBounds(100, 510, 150, 25);
tfIP.setVisible(true);
content.add(tfIP);
tfInput = new JTextField();
tfInput.setBounds(10, 45, 400, 25);
tfInput.setVisible(true);
content.add(tfInput);
btnSend = new Button("Send");
btnSend.setBounds(310,10, 100, 25);
btnSend.setVisible(true);
btnSend.addActionListener(e ->{ //ist eine anonyme Funktion (aufsetzten des Server)
if(Main.isConnected){
Message m = new Message(tfName.getText(),tfInput.getText());
m.setTimeStamp(LocalTime.now());
if (Main.isHost){
ServerHandler.send(m);
}else{
ClientHandler.send(m);
}
tfInput.setText("");
}
});
content.add(btnSend);
btnDisconnect = new Button("Disconnect");
btnDisconnect.setBounds(310,510, 100, 25);
btnDisconnect.setVisible(true);
btnDisconnect.setEnabled(false);
btnDisconnect.addActionListener(e ->{ //ist eine anonyme Funktion (aufsetzten des Server)
if(Main.isHost){
ServerHandler.close();
}else{
ClientHandler.close();
}
btnDisconnect.setEnabled(false);
btnHost.setEnabled(true);
btnClient.setEnabled(true);
});
content.add(btnDisconnect);
taChat = new JTextArea();
taChat.setVisible(true);
sp = new JScrollPane(taChat);
sp.setBounds(10,80, 400, 400);
sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
content.add(sp);
jf.setContentPane(content);
jf.setVisible(true);
}
}
<file_sep>package network;
import application.Message;
import com.esotericsoftware.kryo.Kryo;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DecimalStyle;
import java.util.Locale;
public class Register {
public static void register(Kryo k){
k.register(Message.class);
k.register(LocalTime.class, new LocalTimeSerializer());
k.register(DateTimeFormatter.class);
k.register(Locale.class);
k.register(DecimalStyle.class);
}
}
|
26c78462c8d8f987e02e1c621b3a2e93dbc46c7b
|
[
"Java"
] | 2 |
Java
|
Coco-Gianluca/Chatprogramm
|
c06c112184f7287c9130b0980573082f07116e71
|
54ab3796596b3255b112d8faa49204f46b01a358
|
refs/heads/main
|
<repo_name>rakawidjaja169/Calculate-Profit<file_sep>/exercise3.sql
-- dapatkan semua barang dengan total penjualan yang lebih besar dari "hoodie abu-abu"
SELECT items.id, items.name, SUM(price) AS "total penjualan"
FROM sales_records
JOIN items
ON sales_records.item_id = items.id
GROUP BY items.id
HAVING SUM(price) > (
SELECT SUM(price)
FROM items
JOIN sales_records
ON sales_records.item_id = items.id
WHERE name = "<NAME>-abu"
);<file_sep>/exercise2.sql
-- dapatkan data untuk 5 produk dengan penjualan tertinggi
SELECT items.id, items.name, SUM(price) AS "total penjualan"
FROM sales_records
JOIN items
ON sales_records.item_id = items.id
GROUP BY items.id
ORDER BY SUM(price) DESC
LIMIT 5;
|
428e01d76ac3d93ef79640e6f7acc3999074a44d
|
[
"SQL"
] | 2 |
SQL
|
rakawidjaja169/Calculate-Profit
|
b740a6bceeeb8883c69a257a85c6514f6a0aa062
|
f9c359a9cddd03147bb99fc8afaeb1d551b6e6d6
|
refs/heads/master
|
<repo_name>Caro2222/pharmacie<file_sep>/app/controllers/HomeController.php
<?php
class HomeController
{
public function mainAction()
{
return [
'template' => ['folder' => "Home",
"file" => 'home',
],
"title" => "Pharmacie de la gare",
];
}
}<file_sep>/app/controllers/ProductController.php
<?php
class ProductController
{
private $allowedExtensions =[".jpg",".jpeg",".png"];
public function showAllAction()
{
$model = NEW ProductModel();
return [
'template' => ['folder' => "Product",
"file" => 'showAll',
],
"title" => " fiche produit",
"allProducts"=>$allproducts=$model->showAll(),
];
}
public function showOneAction()
{
$redirectURl=null;
$model= NEW ProductModel();
return [
'template' => ['folder' => "Product",
"file" => 'showOne',
],
"title" => " fiche produit",
"product"=> $model->showOne($_GET['id']),
"redirect" => $redirectURl,
];
}
public function createAction()
{
$redirectURl=null;
$error = false ;
$modelLabo =NEW LaboratoireModel();
$allLabo= $modelLabo->findAllLabo();
if($_POST) {
$flashBag = NEW Flashbag();
if (!isset($_POST['productName']) || trim($_POST['productName']) == "") {
$flashBag->addMessage("Veuillez entrer le nom du laboratoire");
$error = "true";
}
if (!isset($_POST['description']) || trim($_POST['description']) == "") {
$flashBag->addMessage("Veuillez entrer la description du laboratoire");
$error = "true";
}
if (!isset($_POST['category']) || trim($_POST['category']) == "") {
$flashBag->addMessage("Veuillez entrer la category du laboratoire");
$error = "true";
}
if (!isset($_POST['buyPrice']) || trim($_POST['buyPrice']) == "") {
$flashBag->addMessage("Veuillez entrer le prix d'achat");
$error = "true";
}
if (!isset($_POST['sellingPrice']) || trim($_POST['sellingPrice']) == "") {
$flashBag->addMessage("Veuillez entrer le prix de vente du produit");
$error = "true";
}
if (!isset($_POST['laboratoire']) || trim($_POST['laboratoire']) == "") {
$flashBag->addMessage("Veuillez entrer le laboratoire");
$error = "true";
}
if ($error) {
return ["redirect" => "pharmacie_product_create"];
} else {
$model = NEW ProductModel();
$idProduct= $model->create($_POST['productName'],$_POST['description'], $_POST['category'],$_POST['buyPrice'],
$_POST['sellingPrice'],$_POST['laboratoire'],$_POST['image']= NULL);
if(isset($_FILES["image"]) && $_FILES["image"]["error"]>=0)
{
$extension= (substr($_FILES['image']['name'],
strpos($_FILES["image"]["name"],'.',strlen($_FILES['image']['name'])-5)));
if(in_array($extension,$this->allowedExtensions))
{
$filename = "product_" . $idProduct . $extension;
$router = new Router();
$filePath = $router->getWwwPath(true)."/upload/";
move_uploaded_file($_FILES['image']['tmp_name'],$filePath . $filename);
$model->updateImg($idProduct,$filename);
}
}
$flashBag = new Flashbag();
$flashBag->addMessage("Fiche produit crée avec succés");
$redirectURl = "pharmacie_laboratoire_showAll";
}
}
return [
'template' => ['folder' => "Product",
"file" => 'create',
],
"title" => "Création de fiche produit",
'allLabo' => $allLabo,
"redirect" => $redirectURl,
];
}
public function updateAction()
{
$redirect= null;
$product=null;
$allLabo=null;
$model=NEW ProductModel();
if(isset($_GET['id']) && ctype_digit($_GET['id']))
{
$product=$model->showOne($_GET['id']);
$modelLabo= NEW LaboratoireModel();
$allLabo=$modelLabo->findAllLabo();
if(!$product)
{
$redirect="pharmacie_product_showAll";
}
}
elseif(isset($_POST['productName']))
{
$router = new Router();
$model = new ProductModel();
$model->update($_POST["id"], $_POST['productName'], $_POST['productDescription'], $_POST['category'],
$_POST['buyPrice'], $_POST['sellingPrice'],$_POST['laboratoire'] ,$_POST['photo']=NULL);
if(isset($_FILES["image"]) && $_FILES["image"]["size"] > 0 && $_FILES["image"]['error']>= 0)
{
$product = $model->showOne($_POST['id']) ;
$filePath = $router->getWwwPath(true) . "/upload/";
if($product['image'])
{
$fileName = $product['image'];
$fullFilePath = $filePath . $fileName;
if (file_exists($fullFilePath)) {
unlink($fullFilePath);
}
}
$extension= (substr($_FILES['image']['name'],
strpos($_FILES["image"]["name"],'.',strlen($_FILES['image']['name'])-5)));
if (in_array($extension,$this->allowedExtensions))
{
$filename = "product_".$_POST['id'].$extension;
move_uploaded_file($_FILES["image"]["tmp_name"],$filePath.$filename);
$model->updateImg($_POST['id'],$filename);
}
}
elseif(isset($_POST["img-suppr"]) && $_POST["img-suppr"])
{
//effacer l'image existance et mettre img dans la BDD à NULL
$plat = $model->showOne($_POST['id']) ;
$filePath = $router->getWwwPath(true)."/upload/" ;
$fileName = $plat['image'] ;
$fullFilePath = $filePath.$fileName ;
if(file_exists($fullFilePath))
{
unlink($fullFilePath) ;
}
$model->updateImg($_POST['id'],NULL);
}
$redirect="pharmacie_product_showAll";
}
else
{
$redirect ="pharmacie_product_showOne";
}
return [
'template' => ['folder' => "Product",
"file" => 'update',
],
"title" => "Modifier la fiche produit",
"redirect" =>$redirect,
"product"=>$product,
"allLabo"=>$allLabo,
];
}
}<file_sep>/app/models/laboratoireModel.php
<?php
class LaboratoireModel
{
public function create($name,$description,$contact,$logo){
$pdo = (new Database())->getPdo();
$query = $pdo->prepare("INSERT INTO laboratoire (nameLabo,description,contact,logo)
VALUES (:nameLabo,:description,:contact,:logo)");
$query->execute(["nameLabo"=>$name,
"description"=>$description,
"contact"=>$contact,
"logo"=>$logo ]);
return $pdo->lastInsertId();
}
public function findAllLabo()
{
$pdo = (new Database())->getPdo();
$query = $pdo->prepare("SELECT nameLabo
FROM laboratoire");
$query->execute();
return $query->fetchAll();
}
}<file_sep>/index.php
<?php
define("ABSOLUTE_ROOT_PATH",__DIR__);
include "lib/Router.class.php";
include "lib/Kernel.class.php";
include "lib/Database.php";
include "lib/Flashbag.php";
$kernel = new Kernel();
$kernel->bootstrap();
try
{
//demarrer udput buffering
ob_start();
$kernel->run();
ob_end_flush();
} catch (Exception $exception)
{
ob_start();
$kernel->renderError(implode("<br>",[$exception->getMessage(),
"<strong>Fichier</strong>".$exception->getFile(),
"<strong>Ligne</strong>".$exception->getLine()]));
}<file_sep>/app/controllers/LaboratoireController.php
<?php
class LaboratoireController
{
public function createAction()
{
$redirectURl=null;
$error = false ;
if($_POST)
{
$flashBag = NEW Flashbag();
if(!isset($_POST['name']) || trim($_POST['name'])=="")
{
$flashBag->addMessage("Veuillez entrer le nom du laboratoire");
$error="true";
}
if(!isset($_POST['description']) || trim($_POST['description'])=="")
{
$flashBag->addMessage("Veuillez entrer le nom la description");
$error="true";
}
if(!isset($_POST['contact']) || trim($_POST['contact'])=="")
{
$flashBag->addMessage("Veuillez entrer le contact du laboratoire");
$error="true";
}
if ($error) {
return ["redirect" => "pharmacie_laboratoire_create"];
} else {
$model= NEW LaboratoireModel();
$model->create($_POST['name'],$_POST['description'],$_POST['contact'],$_POST['logo']);
$flashBag = new Flashbag();
$flashBag->addMessage("Fiche laboratoire crée avec succés");
$redirectURl = "pharmacie_home";
}
}
return [
"template"=> [
"folder"=>"laboratoire",
"file"=>"create",
],
"title"=>"Création fiche laboratoire",
];
}
}<file_sep>/app/models/ProductModel.php
<?php
class ProductModel
{
public function showAll()
{
$pdo = (new Database())->getPdo();
$query = $pdo->prepare("SELECT * FROM product");
$query->execute();
return $query->fetchAll();
}
public function showOne($id)
{
$pdo = (new Database())->getPdo();
$query = $pdo->prepare("SELECT * FROM product
WHERE id=:id");
$query->execute(['id' => $id]);
return $query->fetch();
}
public function create($productName, $description, $category, $buyPrice, $sellingPrice, $laboratoire, $image)
{
$pdo = (new Database())->getPdo();
$query = $pdo->prepare("INSERT INTO product (`productName`, `productDescription`, `category`, `buyPrice`, `sellingPrice`, `laboratoire`,image)
VALUES (:productName,:description,:category,:buyPrice,:sellingPrice,:laboratoire,:image) ");
$query->execute(["productName" => $productName,
"description" => $description,
"category" => $category,
"buyPrice" => $buyPrice,
"sellingPrice" => $sellingPrice,
"laboratoire" => $laboratoire,
"image" => $image]);
return $pdo->lastInsertId();
}
public function updateImg($id, $filename)
{
$pdo = (new Database())->getPdo();
$query = $pdo->prepare("UPDATE product
SET image = :filename
WHERE id = :id ");
$query->execute([
"filename" => $filename,
"id" => $id,
]);
}
public function update($id, $productName, $productDescription, $category, $buyPrice, $sellingPrice, $laboratoire, $image)
{
$pdo = (new Database())->getPdo();
$query = $pdo->prepare("UPDATE product
SET productName=:productName,
productDescription=:productDescription,
category=:category,
buyPrice=:buyPrice,
sellingPrice=:sellingPrice,
laboratoire=:laboratoire,
image=:image
WHERE id=:id
");
$query->execute(['id' => $id,
'productName' => $productName,
'productDescription' => $productDescription,
'category' => $category,
'buyPrice' => $buyPrice,
'sellingPrice' => $sellingPrice,
'laboratoire' => $laboratoire,
'image' => $image]);
$pdo->lastInsertId();
}
}
<file_sep>/lib/Router.class.php
<?php
class Router
{
private $rootURl="/pharmacie/index.php";
private $wwwPath="/pharmacie/www";
private $allUrls=[];
private $localHostPath = ABSOLUTE_ROOT_PATH;
private $allRoutes=
[
"/"
=>[
"controller"=>"Home",
"method"=>"main",
"name"=>'pharmacie_home'
],
"/product/create"
=>[
"controller"=>"Product",
"method"=>"create",
"name"=>"pharmacie_product_create"
],
"/laboratoire/create"
=>[
"controller"=>"Laboratoire",
"method"=>"create",
"name"=>"pharmacie_laboratoire_create"
],
"/laboratoire/showAll"
=>[
"controller"=>"Laboratoire",
"method"=>"showAll",
"name"=>"pharmacie_laboratoire_showAll"
],
"/product/showAll"
=>[
"controller"=>"Product",
"method"=>"showAll",
"name"=>"pharmacie_product_showAll"
],
"/product/showOne"
=>[
"controller"=>"Product",
"method"=>"showOne",
"name"=>"pharmacie_product_showOne"
],
"/product/update"
=>[
"controller"=>"Product",
"method"=>"update",
"name"=>"pharmacie_product_update"
],
];
public function __construct()
{
$nbrSlashes =substr_count($this->rootURl,"/");
$this->localHostPath=dirname($this->localHostPath,$nbrSlashes-1);
foreach ($this->allRoutes as $url=>$route)
{
$this->allUrls[$route["name"]]=
["url"=>$url,
"route"=>["controller"=>$route['controller'],
"method"=>$route["method"]
]
];
}
}
public function getRoute($requestedPath)
{
if(isset($this->allRoutes[$requestedPath]))
{
return $this->allRoutes[$requestedPath];
}
// a renplacé par des execptions
die("Erreurs url inconnu");
}
public function getWwwPath($absolute=false)
{
if($absolute)
{
return realpath($this->localHostPath.$this->wwwPath);
}
else {
return $this->wwwPath;
}
}
public function generatePath($routeName)
{
return $this->rootURl.$this->allUrls[$routeName]["url"];
}
}<file_sep>/lib/Kernel.class.php
<?php
class Kernel
{
private $applicationPath = "app";
private $controllerPath = "app/controllers/";
private $modelPath ="app/models/";
private $viewPath="www/views/";
private $viewData;
public function __construct()
{
$this->viewData=["variable"=>[]];
}
public function bootstrap()
{
spl_autoload_register([$this,"loadClass"]);
error_reporting(E_ALL);
set_error_handler(function($code,$message,$filename,$lineNumber)
{
throw new ErrorException($message,$code,1,$filename,$lineNumber);
});
return $this;
}
public function loadClass($class)
{
if(substr($class,-10)== "Controller")
{
$filename=$this->controllerPath.$class.".php";
}
elseif(substr($class,-5)== "Model")
{
$filename=$this->modelPath.$class.".php";
}
else
{
$filename=$this->applicationPath."/class/".$class.".php";
}
if(file_exists($filename))
{
include $filename;
}
else{
die("le dossier <strong>".$filename."</strong> n'exite pas");
}
}
public function run()
{
$requestedPath= $_SERVER['PATH_INFO'];
if($requestedPath)
{
$router = new Router();
$requestedRoute= $router->getRoute($requestedPath);
$controllerName=$requestedRoute["controller"]."Controller";
$controller = new $controllerName();
$methodName= $requestedRoute["method"]."Action";
if(method_exists($controller,$methodName))
{
$this->viewData["variable"]["router"]=$router;
$this->viewData['variable']=
array_merge((array) $this->viewData['variable'],
(array)$controller->$methodName());
$this->renderResponse();
}
else{
die("erreur: ".$methodName." introuvable dans ".$controllerName );
}
}
}
public function renderResponse()
{
if(isset($this->viewData["variable"]["redirect"]))
{
$redirectUrl=$this->viewData["variable"]["router"]->generatePath($this->viewData["variable"]["redirect"]);
header("Location:".$redirectUrl);
exit();
}
//si template
elseif (isset($this->viewData['variable']['template']))
{
$templatePath = $this->viewPath;
$templatePath.= $this->viewData['variable']['template']['folder']."/";
$templatePath.= $this->viewData['variable']['template']['file'];
$templatePath.= 'View.phtml';
extract($this->viewData["variable"],EXTR_OVERWRITE);
if (isset($this->viewData['variable']['template']['_raw']))
{
include $templatePath;
}
else
{
$flashBag= new Flashbag();
// $userSession = new UserSession();
include $this->viewPath."layoutView.phtml";
}
}
elseif (isset($this->viewData['variable']['jsonResponse'])) {
echo $this->viewData['variable']['jsonResponse'];
}
}
public function renderError($errorMessage)
{
extract($this->viewData["variable"],EXTR_OVERWRITE);
include "errorView.html";
die();
}
}
|
80e6a46e0de343f3a91745cc3a0a2084941e9a46
|
[
"PHP"
] | 8 |
PHP
|
Caro2222/pharmacie
|
8699487407fcff7e25702bcc1875b46d9b8af5a4
|
95705e4fcce213243d5e130f311e7ec1e4a1b448
|
refs/heads/master
|
<repo_name>amul-agrawal/pygame-project<file_sep>/River Battle/config.py
import pygame
pygame.init()
# create the screen
window_width_X=1600
window_width_Y=900
# Score
score_value_player = [0]*2
font = pygame.font.Font('freesansbold.ttf', 25)
textX = 10 #position of score of player 1
testY = 10 #position of score of player 1
text1X = 1300 #position of score of player 2
test1Y = 850 #position of score of player 2
# Caption and Icon
pygame.display.set_caption("River Battle")
icon = pygame.image.load('pokeball.png')
pygame.display.set_icon(icon)
# Player
pikachuImg = pygame.image.load('pikachu.png')
snorlaxImg = pygame.image.load('snorlax.png')
playerImg = pikachuImg
playerX = 720
playerY = 835
playerX_change = 0
playerY_change = 0
# rock obastacle
rockImg = pygame.image.load('rocks.png')
rockX = []
rockY = []
rockX.append(1500)
rockX.append(300)
rockX.append(250)
rockX.append(30)
rockY.append(4)
rockY.append(334)
rockY.append(664)
rockY.append(831)
num_of_rocks = 4
# bonfire obastacle
bonfireImg = pygame.image.load('bonfire.png')
bonfireX = []
bonfireY = []
bonfireX.append(1100)
bonfireX.append(50)
bonfireY.append(169)
bonfireY.append(499)
num_of_bonfires = 2
# volcano obastacle
volcanoImg = pygame.image.load('volcano.png')
volcanoX = []
volcanoY = []
volcanoX.append(1450)
volcanoY.append(499)
num_of_volcanoes = 1
# boat obastacle
boatImg = pygame.image.load('boat.png')
boatX = []
boatY = []
boatX.append(400)
boatX.append(1300)
boatX.append(800)
boatX.append(50)
boatX.append(400)
boatX.append(1100)
boatY.append(85)
boatY.append(85)
boatY.append(415)
boatY.append(415)
boatY.append(745)
boatY.append(745)
boatX_change = 2
num_of_boats = 6
# cruise obastacle
cruiseImg = pygame.image.load('cruise.png')
cruiseX = []
cruiseY = []
cruiseX.append(1300)
cruiseX.append(500)
cruiseX.append(1500)
cruiseX.append(900)
cruiseY.append(250)
cruiseY.append(250)
cruiseY.append(580)
cruiseY.append(580)
cruiseX_change = -2
num_of_cruises = 4
# cavewoman obastacle
cavewomanImg = pygame.image.load('cavewoman.png')
cavewomanX = []
cavewomanY = []
cavewomanX.append(300)
cavewomanX.append(900)
cavewomanY.append(170)
cavewomanY.append(500)
cavewomanX_change = []
cavewomanX_change.append(1)
cavewomanX_change.append(1)
cavewomanY_change = 0
num_of_cavewomen = 2
#rhino obastacle
rhinoImg = pygame.image.load('rhino.png')
rhinoX = []
rhinoY = []
rhinoX.append(1000)
rhinoX.append(800)
rhinoY.append(335)
rhinoY.append(664)
rhinoX_change = -1
rhinoY_change = 0
num_of_rhinos = 2
<file_sep>/River Battle/main.py
import pygame
# initialize pygame
pygame.init()
# importing math to check distance
import math
from config import *
# Set the screen size
screen = pygame.display.set_mode((window_width_X, window_width_Y))
# ---------------------------------------------------------------------------------------
# function that shows score on coordinate (x,y)
# ---------------------------------------------------------------------------------------
def show_score(Score, x, y):
if y > 100:
score = font.render("Player2 Score : " + str(Score), True, (0, 0, 0))
else:
score = font.render("Player1 Score : " + str(Score), True, (0, 0, 0))
screen.blit(score, (x, y))
# ---------------------------------------------------------------------------------------
# function to show text
# ---------------------------------------------------------------------------------------
def show(name, x, y):
screen.blit(name, (x, y))
# ---------------------------------------------------------------------------------------
# function to check collision
# ---------------------------------------------------------------------------------------
def isCollision(playerX, playerY, obstacleX, obstacleY):
distance = math.sqrt(math.pow(playerX - obstacleX, 2) + (math.pow(playerY - obstacleY, 2)))
if distance < 45:
return True
else:
return False
running = True
turn = 0
flag = [False] * 12
flag1 = [False] * 12
prev_Time = pygame.time.get_ticks()
speedFlag = 0
call = 0
# ---------------------------------------------------------------------------------------
# creates a black window which in necessary for the trasitons in the game
# ---------------------------------------------------------------------------------------
def window():
global running
global playerX_change
global playerY_change
global boatX_change
global cruiseX_change
global cavewomanX_change
global rhinoX_change
global call
global speedFlag
# call variable keeps a track of how many times the funtion has been called
call = call + 1
font1 = pygame.font.Font('freesansbold.ttf', 50)
score = ""
player1score = ""
player2Score = ""
if call == 1:
score = font1.render("WELCOME press ENTER to continue", True, (255, 255, 255))
elif call == 2:
score = font1.render(" PLAYER 2 TURN press ENTER ", True, (255, 255, 255))
elif call == 3:
score = font1.render(" ROUND 2 press ENTER ", True, (255, 255, 255))
player1score = font1.render("Player1 Score: " + str(score_value_player[0]), True, (255, 255, 255))
player2Score = font1.render("Player2 Score: " + str(score_value_player[1]), True, (255, 255, 255))
if score_value_player[0] > score_value_player[1]:
# speedflag goes 1 if player1 wins the game
speedFlag = 1
if score_value_player[0] < score_value_player[1]:
# speedflag goes 2 if player2 wins the game
speedFlag = 2
elif call == 4:
score = font1.render(" PLAYER 2 TURN press ENTER ", True, (255, 255, 255))
elif call == 5:
if score_value_player[0] > score_value_player[1]:
score = font1.render("PLAYER 1 WINS press ENTER to exit", True, (255, 255, 255))
elif score_value_player[0] == score_value_player[1]:
score = font1.render(" TIE press enter to exit ", True, (255, 255, 255))
else:
score = font1.render("PLAYER 2 WINS press ENTER to exit", True, (255, 255, 255))
while running:
screen.fill((0, 0, 0))
if call == 3:
screen.blit(score, (250, 300))
screen.blit(player1score, (350, 400))
screen.blit(player2Score, (350, 500))
else:
screen.blit(score, (350, 400))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
call = 5
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER:
running = False
if event.key == pygame.K_RETURN:
running = False
pygame.display.update()
running = True
boatX_change = 2
cruiseX_change = -2
cavewomanX_change = []
cavewomanX_change.append(1)
cavewomanX_change.append(1)
rhinoX_change = -1
if call == 5:
running = False
#
if call == 3 and speedFlag == 1:
boatX_change = 3
cruiseX_change = -3
cavewomanX_change = []
cavewomanX_change.append(1.5)
cavewomanX_change.append(1.5)
rhinoX_change = -1.5
if call == 4 and speedFlag == 2:
boatX_change = 3
cruiseX_change = -3
cavewomanX_change = []
cavewomanX_change.append(1.5)
cavewomanX_change.append(1.5)
rhinoX_change = -1.5
playerY_change = 0
playerX_change = 0
# calling window function to welcome player to play the game
window()
while running:
# ---------------------------------------------------------------------------------------
# SETUP THE GAME WINDOW AND PLAYER MOVEMENTS
# ---------------------------------------------------------------------------------------
screen.fill((77, 184, 255))
pygame.draw.rect(screen, (64, 255, 0), (0, 0, 1600, 75))
pygame.draw.rect(screen, (64, 255, 0), (0, 165, 1600, 75))
pygame.draw.rect(screen, (64, 255, 0), (0, 330, 1600, 75))
pygame.draw.rect(screen, (64, 255, 0), (0, 495, 1600, 75))
pygame.draw.rect(screen, (64, 255, 0), (0, 660, 1600, 75))
pygame.draw.rect(screen, (64, 255, 0), (0, 825, 1600, 75))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# ---------------------------------------------------------------------------------------
# changing player position on the basis of arrow key pressed
# ---------------------------------------------------------------------------------------
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -1
if event.key == pygame.K_RIGHT:
playerX_change = 1
if event.key == pygame.K_DOWN:
playerY_change = 1
if event.key == pygame.K_UP:
playerY_change = -1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
playerY += playerY_change
playerX += playerX_change
# ---------------------------------------------------------------------------------------
# checking the player bound
# ---------------------------------------------------------------------------------------
if playerX <= 0:
playerX = 1536
elif playerX >= 1536:
playerX = 0
if playerY <= 0:
playerY = 0
elif playerY >= 836:
playerY = 836
# ---------------------------------------------------------------------------------------
# displaying all the obstacles in every frame based on their updated position
# ---------------------------------------------------------------------------------------
show(playerImg, playerX, playerY)
for i in range(num_of_cruises):
cruiseX[i] += cruiseX_change
if cruiseX[i] <= 0:
cruiseX[i] = 1536
elif cruiseX[i] >= 1536:
cruiseX[i] = 0
show(cruiseImg, cruiseX[i], cruiseY[i])
for i in range(num_of_boats):
boatX[i] += boatX_change
if boatX[i] <= 0:
boatX[i] = 1536
elif boatX[i] >= 1536:
boatX[i] = 0
show(boatImg, boatX[i], boatY[i])
for i in range(num_of_rocks):
show(rockImg, rockX[i], rockY[i])
for i in range(num_of_bonfires):
show(bonfireImg, bonfireX[i], bonfireY[i])
for i in range(num_of_volcanoes):
show(volcanoImg, volcanoX[i], volcanoY[i])
for i in range(num_of_cavewomen):
cavewomanX[i] += cavewomanX_change[i]
if cavewomanX[0] <= 0:
cavewomanX[0] = 0
cavewomanX_change[0] = 1.5
elif cavewomanX[0] >= 600:
cavewomanX[0] = 600
cavewomanX_change[0] = -1.5
if cavewomanX[1] <= 550:
cavewomanX[1] = 550
cavewomanX_change[1] = 1.5
elif cavewomanX[1] >= 1200:
cavewomanX[1] = 1200
cavewomanX_change[1] = -1.5
for i in range(num_of_cavewomen):
show(cavewomanImg, cavewomanX[i], cavewomanY[i])
for i in range(num_of_rhinos):
rhinoX[i] += rhinoX_change
if rhinoX[0] <= 700:
rhinoX[0] = 700
rhinoX_change = 1.5
elif rhinoX[0] >= 1300:
rhinoX[0] = 1300
rhinoX_change = -1.5
if rhinoX[1] <= 500:
rhinoX[1] = 500
rhinoX_change = 1.5
elif rhinoX[1] >= 1100:
rhinoX[1] = 1100
rhinoX_change = -1.5
for i in range(num_of_rhinos):
show(rhinoImg, rhinoX[i], rhinoY[i])
# ---------------------------------------------------------------------------------------
# collision detection
# ---------------------------------------------------------------------------------------
collision = False
for i in range(num_of_cruises):
if (collision):
break
collision = isCollision(playerX, playerY, cruiseX[i], cruiseY[i])
for i in range(num_of_boats):
if collision:
break
collision = isCollision(playerX, playerY, boatX[i], boatY[i])
for i in range(num_of_cavewomen):
if collision:
break
collision = isCollision(playerX, playerY, cavewomanX[i], cavewomanY[i])
for i in range(num_of_rhinos):
if collision:
break
collision = isCollision(playerX, playerY, rhinoX[i], rhinoY[i])
for i in range(num_of_rocks):
if collision:
break
collision = isCollision(playerX, playerY, rockX[i], rockY[i])
for i in range(num_of_volcanoes):
if collision:
break
collision = isCollision(playerX, playerY, volcanoX[i], volcanoY[i])
for i in range(num_of_bonfires):
if collision:
break
collision = isCollision(playerX, playerY, bonfireX[i], bonfireY[i])
if collision:
playerX = 720
if turn == 0:
playerY = 5
turn = 1
playerImg = snorlaxImg
elif turn == 1:
playerY = 835
turn = 0
playerImg = pikachuImg
window()
# ---------------------------------------------------------------------------------------
# updating player score based on his position on the screen and time spent playing the game
# ---------------------------------------------------------------------------------------
if turn == 0:
flag1 = [False] * 12
if playerY < 761:
if not flag[0]:
score_value_player[0] += 5
flag[0] = True
if playerY < 671:
if flag[1] is False:
score_value_player[0] += 20
flag[1] = True
if playerY < 596:
if flag[2] is False:
score_value_player[0] += 15
flag[2] = True
if playerY < 506:
if flag[3] is False:
score_value_player[0] += 20
flag[3] = True
if playerY < 431:
if flag[4] is False:
score_value_player[0] += 20
flag[4] = True
if playerY < 341:
if flag[5] is False:
score_value_player[0] += 20
flag[5] = True
if playerY < 266:
if flag[6] is False:
score_value_player[0] += 15
flag[6] = True
if playerY < 176:
if flag[7] is False:
score_value_player[0] += 20
flag[7] = True
if playerY < 101:
if flag[8] is False:
score_value_player[0] += 15
flag[8] = True
if playerY < 11:
if flag[9] is False:
score_value_player[0] += 20
flag[9] = True
playerX = 720
playerY = 5
turn = 1
playerImg = snorlaxImg
window()
cur_Time = pygame.time.get_ticks()
if cur_Time - prev_Time >= 2000:
score_value_player[0] -= 1
prev_Time = cur_Time
else:
flag = [False] * 12
if playerY > 75:
if flag1[0] is False:
score_value_player[1] += 5
flag1[0] = True
if playerY > 165:
if flag1[1] is False:
score_value_player[1] += 20
flag1[1] = True
if playerY > 240:
if flag1[2] is False:
score_value_player[1] += 15
flag1[2] = True
if playerY > 330:
if flag1[3] is False:
score_value_player[1] += 20
flag1[3] = True
if playerY > 405:
if flag1[4] is False:
score_value_player[1] += 15
flag1[4] = True
if playerY > 495:
if flag1[5] is False:
score_value_player[1] += 20
flag1[5] = True
if playerY > 570:
if flag1[6] is False:
score_value_player[1] += 20
flag1[6] = True
if playerY > 660:
if flag1[7] is False:
score_value_player[1] += 20
flag1[7] = True
if playerY > 735:
if flag1[8] is False:
score_value_player[1] += 15
flag1[8] = True
if playerY > 825:
if flag1[9] is False:
score_value_player[1] += 20
flag1[9] = True
playerX = 720
playerY = 835
turn = 0
playerImg = pikachuImg
window()
cur_Time = pygame.time.get_ticks()
if cur_Time - prev_Time >= 2000:
score_value_player[1] -= 1
prev_Time = cur_Time
show_score(score_value_player[0], textX, testY)
show_score(score_value_player[1], text1X, test1Y)
pygame.display.update()
<file_sep>/Readme.md
# ISS Assignment 3
### Game Development using Python and PyGame
## _**River Battle**_
> _<NAME>
> 2019101113_
### Hello there! This is a small game developed by me for my course assignment. Read the instructions here and try out the game. I hope you like it :)
### Gameplay and Rules :
The game has two rounds, each round consists of both the players playing once against each other.
Player 1 is at bottom and has to reach the other end by avoiding all the obstacles and in minimum time.
Player 2 starts at the top of the screen and has to reach the bottom, the other objectives remain the same.
As the player crosses a band, he/she is rewarded points according to the number of obstacles in that band, the rules are –
1. +5 for fixed obstacles
1. +10 for moving obstacles
The player with the greater score wins that particular round, score decreases as time passes.Time penalty is 1 point for 2 seconds.
In the next round, the speed of the moving obstacles increases for the winner of the previous round.
The game automatically closes after the second round.
### Controls:
Keyboard `Arrow Keys` to move up, down, left and right.
### How to install and run on Linux:
1. Download the folder/copy it to your local device.
1. Install python, pygame
1. Check this link to get them installed on linux – https://linuxize.com/post/how-to-install-python-3-7-on-ubuntu-18-04/
1. Download PyGame – https://www.pygame.org/download.shtml
1. Further help - https://www.pygame.org/wiki/GettingStarted
1. Open the folder in Terminal and run :
1. python3 main.py
1. Enjoy the Game.
### How to install and run on Windows:
1. Download the folder/copy it to your local device.
1. Install python, pygame
1. Download python3 – https://www.python.org/downloads/release/python-376/
1. Download PyGame – https://www.pygame.org/download.shtml
1. Further help - https://www.pygame.org/wiki/GettingStarted
1. Open the folder in Python IDE or some other IDE like PyCharm or code editor like VS CODE and run :
>https://www.jetbrains.com/pycharm/download/
>https://code.visualstudio.com/download
1. python3 main.py
1. Enjoy the Game.
#### Attributes
In this game I have used `Python 3` and `PyGame`.
These are some resources I used for icons.
Icons made by <a href="https://www.flaticon.com/authors/freepik" title="Freepik">Freepik</a> from <a
href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a>
Icons made by <a href="https://www.flaticon.com/authors/surang" title="surang">surang</a> from <a
href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a>
Icons made by <a href="https://www.flaticon.com/authors/smashicons" title="Smashicons">Smashicons</a> from <a
href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a>
For the game development i have used PyCharm by JetBrains https://www.jetbrains.com/pycharm/download/
|
2fdfc76114fc161fd223f9fc2a153aae9ac92fe4
|
[
"Markdown",
"Python"
] | 3 |
Python
|
amul-agrawal/pygame-project
|
9cae75a9ad3d6cbf3c9a21a2432436a20c964df7
|
56435ac14434e389ce51f27b13a0f2df8689053c
|
refs/heads/master
|
<file_sep>import toThrow from '../src/toThrow';
describe('toThrow', () => {
it('should check functions', () => {
const throwingFn = () => { throw new Error('test'); };
expect(toThrow(throwingFn, 'test')).toBeTruthy();
expect(toThrow(() => throwingFn(), 'test')).toBeTruthy();
expect(toThrow(() => {}, 'test')).toBeFalsy();
expect(toThrow(() => { throw new Error('test1'); }, 'test')).toBeFalsy();
});
});
<file_sep>export default function toBeDefined(a) {
return typeof a !== 'undefined';
}
<file_sep>import toBeInstanceOf from '../src/toBeInstanceOf';
describe('toBeInstanceOf', () => {
it('Should be an instance of', () => {
expect(toBeInstanceOf('window', Window)).toBeTruthy;
expect(toBeInstanceOf(document.body, Element)).toBeTruthy;
expect(toBeInstanceOf([], Array)).toBeTruthy;
expect(toBeInstanceOf({}, Window)).toBeFalsy;
});
});
<file_sep>export default function toContain(a, b) {
if (Array.isArray(a)) {
return a.indexOf(b) >= 0;
} else if (typeof a === 'object') {
return Object.values(a).indexOf(b) >= 0;
}
return false;
}
<file_sep>import toBeDefined from '../src/toBeDefined';
describe('toBeDefined', () => {
it('should match simple values', () => {
expect(toBeDefined(1)).toBeTruthy();
expect(toBeDefined('onyx')).toBeTruthy();
expect(toBeDefined(null)).toBeTruthy();
expect(toBeDefined({})).toBeTruthy();
expect(toBeDefined(false)).toBeTruthy();
expect(toBeDefined(undefined)).toBeFalsy();
});
});
<file_sep>const isEqual = require('lodash.isequal');
export default function toBe(a, b) {
return isEqual(a, b) && (a !== b || Object.is(a, b));
}
<file_sep>import toBeUndefined from '../src/toBeUndefined';
describe('toBeUndefined', () => {
it('should match simple values', () => {
expect(toBeUndefined(undefined)).toBeTruthy();
expect(toBeUndefined(null)).toBeFalsy();
expect(toBeUndefined(NaN)).toBeFalsy();
expect(toBeUndefined(0)).toBeFalsy();
expect(toBeUndefined({})).toBeFalsy();
});
});
<file_sep>import toBeTruthy from '../src/toBeTrue';
describe('toBeTruthy', () => {
it('Should return truthy', () => {
expect(toBeTruthy('string')).toBeTruthy();
expect(toBeTruthy({})).toBeTruthy();
expect(toBeTruthy(Infinity)).toBeTruthy();
expect(toBeTruthy(0)).toBeFalsy();
});
});
<file_sep>import toBeNull from '../src/toBeNull';
describe('toBeNull', () => {
it('should match simple values', () => {
expect(toBeNull(null)).toBeTruthy();
expect(toBeNull(0)).toBeFalsy();
expect(toBeNull(undefined)).toBeFalsy();
expect(toBeNull(NaN)).toBeFalsy();
});
});
<file_sep>import toBe from '../src/toBe';
describe('toBe', () => {
it('should match simple values', () => {
expect(toBe(1, 1)).toBeTruthy();
expect(toBe('onyx', 'onyx')).toBeTruthy();
expect(toBe(0, 0)).toBeTruthy();
expect(toBe(0, -1)).toBeFalsy();
});
it('should match objects', () => {
expect(toBe({}, {})).toBeTruthy();
expect(toBe({ a: 'b' }, { a: 'b' })).toBeTruthy();
expect(toBe({ a: { b: 'c' } }, { a: { b: 'c' } })).toBeTruthy();
expect(toBe({}, { a: 'b' })).toBeFalsy();
expect(toBe({ a: 'b' }, { a: 'c' })).toBeFalsy();
});
it('should match NaN', () => {
expect(toBe(NaN, NaN)).toBeTruthy();
expect(toBe(NaN, 0)).toBeFalsy();
});
it('should differ 0 from -0', () => {
expect(toBe(0, -0)).toBeFalsy();
});
});
<file_sep>import toBeNaN from '../src/toBeNaN';
describe('toBeNaN', () => {
it('should match NaN and NaN strings', () => {
expect(toBeNaN(NaN)).toBeTruthy();
expect(toBeNaN('onyx')).toBeTruthy();
expect(toBeNaN(0)).toBeFalsy();
expect(toBeNaN(-32768)).toBeFalsy();
expect(toBeNaN('1337')).toBeFalsy();
});
});
<file_sep>import toStrictlyEqual from '../src/toStrictlyEqual';
describe('toEqual', () => {
it('should match simple values', () => {
expect(toStrictlyEqual(1, 1)).toBeTruthy();
expect(toStrictlyEqual('onyx', 'onyx')).toBeTruthy();
expect(toStrictlyEqual(0, 0)).toBeTruthy();
expect(toStrictlyEqual(0, -1)).toBeFalsy();
expect(toStrictlyEqual(0, '0')).toBeFalsy();
});
});
<file_sep>export default function toBeInstanceOf(a, b) {
return (a instanceof b);
}
<file_sep>export default function toThrow(a, b) {
try {
a();
} catch (e) {
if (e.message == b) return true;
}
return false;
}
<file_sep>export default function toBeUndefined(a) {
return typeof a === 'undefined';
}
<file_sep>export default function toBeNaN(a) {
return isNaN(parseInt(a));
}
<file_sep>import toContain from '../src/toContain';
describe('toContain', () => {
it('should search in arrays', () => {
expect(toContain([1], 1)).toBeTruthy();
expect(toContain(['onyx', 1337, 7357], 'onyx')).toBeTruthy();
expect(toContain([1337, 7357], 'onyx')).toBeFalsy();
expect(toContain([], 'onyx')).toBeFalsy();
});
it('should search in objects', () => {
expect(toContain({ a: 1 }, 1)).toBeTruthy();
expect(toContain({ a: 'onyx', b: 1337, c: 7357}, 'onyx')).toBeTruthy();
expect(toContain({ a: 1337, b: 7357 }, 'onyx')).toBeFalsy();
expect(toContain({}, 'onyx')).toBeFalsy();
});
it('should return false if first argument neither object or array', () => {
expect(toContain(1, 'onyx')).toBeFalsy();
});
});
<file_sep>import toBeFalse from '../src/toBeFalse';
describe('toBeFalse', () => {
it('should match true and false', () => {
expect(toBeFalse(false)).toBeTruthy();
expect(toBeFalse(true)).toBeFalsy();
});
});
<file_sep># This repository has been moved to [OnyxJS](https://github.com/onyxjs/onyx)
<file_sep>import toEqual from '../src/toEqual';
describe('toEqual', () => {
it('should match simple values', () => {
expect(toEqual(1, 1)).toBeTruthy();
expect(toEqual('onyx', 'onyx')).toBeTruthy();
expect(toEqual(0, 0)).toBeTruthy();
expect(toEqual(0, '0')).toBeTruthy();
expect(toEqual(0, -1)).toBeFalsy();
});
});
<file_sep>export default function toHaveLength(a, b) {
if (!a) return false;
if(typeof a === 'object') {
return Object.keys(a).length === b;
} else {
return a.length === b;
}
}
|
3780f78552e8da8dedc0d77f4cd8b821fc987f75
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 21 |
JavaScript
|
ElijahKotyluk/onyx
|
7b38883475a57aebddaa93fb270d07774959328c
|
c1eec336ad6a8bb47069cd8ab0c7a1ebd86644f9
|
refs/heads/master
|
<file_sep>require "ponzi/version"
module Ponzi
# Your code goes here...
end
|
59f140f882dd7f164ba59885cca8fd99c631271b
|
[
"Ruby"
] | 1 |
Ruby
|
trobrock/ponzi
|
9ba1f68cf0fc158866d6e20cf42dabe68f76bb0a
|
1922c9ea0e1676df540faa1c919e87edd4200bf6
|
refs/heads/master
|
<file_sep># js-ipfs-browser-server
Run JS IPFS in the browser, with an API bridge
<file_sep>const { createProxyServer, closeProxyServer } = require('ipfs-postmsg-proxy')
module.exports.closeProxyServer = closeProxyServer
module.exports.createProxyServer = createProxyServer
<file_sep>'use strict'
const fs = require('fs')
const { spawn } = require('child_process')
const http = require('http')
const { PassThrough } = require('stream')
const WebSocket = require('ws')
const Hapi = require('hapi')
const setHeader = require('hapi-set-header')
const debug = require('debug')
const multiaddr = require('multiaddr')
const apiRoutes = require('ipfs/src/http/api/routes')
const { createProxyClient } = require('ipfs-postmsg-proxy')
const assets = require('./assets')
const chrome = require('./chrome')
const chromepath = chrome.binary()
main(process.env.IPFS_PATH || process.cwd()).catch(err => {
console.error(err)
process.exit(1)
})
function HttpAPI(config, routes) {
this.server = undefined
this.apiaddr = multiaddr(config.Addresses.API)
this.start = (callback) => {
console.log('starting')
this.server = new Hapi.Server({
connections: {
routes: {
cors: true
}
},
debug: process.env.DEBUG ? {
request: ['*'],
log: ['*']
} : undefined
})
const api = this.apiaddr.nodeAddress()
// select which connection with server.select(<label>) to add routes
this.server.connection({
host: api.address,
port: api.port,
labels: 'API',
})
this.server.ext('onRequest', (request, reply) => {
if (request.path.startsWith('/api/') && !request.server.app.ipfs) {
return reply({
Message: 'Daemon is not online',
Code: 0,
Type: 'error'
}).code(500).takeover()
}
reply.continue()
})
// load routes
routes.forEach(r => r(this.server))
// Set default headers
setHeader(this.server,
'Access-Control-Allow-Headers',
'X-Stream-Output, X-Chunked-Output, X-Content-Length')
setHeader(this.server,
'Access-Control-Expose-Headers',
'X-Stream-Output, X-Chunked-Output, X-Content-Length')
this.server.start(err => {
if (err) {
return callback(err)
}
const api = this.server.select('API')
try {
api.info.ma = multiaddr.fromNodeAddress(api.info, 'tcp').toString()
} catch (err) {
return callback(err)
}
callback()
})
}
this.stop = (callback) => {
console.log('stopping')
this.server.stop(err => {
if (err) {
console.error('There were errors stopping')
console.error(err)
}
callback()
})
}
}
async function main(repopath, gateway, hash, version) {
let config
console.log('reading config')
try {
config = fs.readFileSync(`${repopath}/config`)
} catch (err) {
throw new Error(`No IPFS repo found in ${repopath}`)
}
try {
config = JSON.parse(config)
} catch (err) {
throw new Error(`Could not parse config ${err.message}`)
}
const httpapi = new HttpAPI(config, [
(server) => apiRoutes(server),
(server) => {
// Currently serving everything off of the same connection
// that the API is running on
const apiserver = server.select('API')
const { vendorJS, indexHTML, ipfsJS } = assets
apiserver.route({
method: 'GET',
path: '/',
handler: (request, reply) => reply(indexHTML())
})
apiserver.route({
method: 'GET',
path: '/vendor.js',
handler: (request, reply) => reply(vendorJS())
})
apiserver.route({
method: 'GET',
path: '/ipfs.js',
handler: (request, reply) => reply(ipfsJS())
})
}
])
await p(httpapi.start)
// Setup proxy socket
new WebSocket.Server({
server: httpapi.server.listener
})
.on('connection', socket => {
console.log('new websocket connection')
// We only accept a single connection except when
// the debug env is set to allow for refreshing of
// the browser
if (httpapi.server.app.ipfs != undefined) {
console.log('websocket proxy already started, closing new connection')
return socket.close()
}
// Set instance to another falsey value, but not undefined so that
// our middleware hook will error correctly till the proxy is setup
httpapi.server.app.ipfs = null
// Websockets can only send buffer like data, but postmsg-proxy
// works on object data. For every listener we have to wrap it
// in a function which parses the buffer prior to passing it into
// the original listener. This maps contains the mapping so that
// we can properly remove listeners
const fnmap = new Map()
// Send the initial setup with the ipfs config to the browser
socket.send(JSON.stringify({
__controller: true,
__type: 'SETUP',
__payload: config,
}))
socket.addEventListener('close', () => {
console.log('websocket connection closed')
fnmap.clear()
httpapi.server.app.ipfs = undefined
})
// One time message receiver that constructs the
// postmsg-proxy client once the ipfs node in the browser is
// running
socket.addEventListener('message', ev => {
if (httpapi.server.app.ipfs) {
return
}
const msg = JSON.parse(ev.data)
if (msg.__controller && msg.__type == 'READY') {
console.log('creating new ipfs websocket proxy')
httpapi.server.app.ipfs = createProxyClient({
postMessage: msg => {
socket.send(JSON.stringify(msg))
},
addListener: (name, fn) => {
const cb = ev => fn({ ...ev, data: JSON.parse(ev.data) })
fnmap.set(fn, cb)
socket.addEventListener(name, cb)
},
removeListener: (name, fn) => {
socket.removeEventListener(name, fnmap.get(fn))
}
})
}
})
})
const apiserver = httpapi.server.select('API')
console.log('api running on %s', apiserver.info.ma)
console.log('writing api file to repo')
await p(cb => {
fs.createWriteStream('./api')
.on('error', cb)
.end(apiserver.info.ma, cb)
})
console.log('starting browser')
const browser = spawn(chromepath, chrome.options(`${process.cwd()}/data`, !process.env.DEBUG, apiserver.info.uri))
browser.on('exit', async (code, signal) => {
console.log('browser exited')
await p(httpapi.stop)
await p(cb => fs.unlink('./api', cb))
process.exit(code)
})
const signalHandler = signal => {
console.log('received signal %s', signal)
browser.kill(signal)
}
process.on('SIGINT', signalHandler)
process.on('SIGTERM', signalHandler)
process.on('SIGQUIT', signalHandler)
}
function p(fn) {
return new Promise((resolve, reject) => {
fn((err, ...rest) => {
if (err) return reject(err)
resolve(...rest)
})
})
}
|
8a3e68e64814d4bf3a8546bb37c4010e4277a231
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
travisperson/js-ipfs-browser-server
|
ca386fe2dd5b10571dd01e183fdfe0ecd07439d1
|
6e56dae5371df2b7d754e3e2c3a62d3d4380b3ae
|
refs/heads/master
|
<file_sep>import * as actionTypes from 'constants/actionTypes/dictionarySearch';
import * as statuses from 'constants/statuses';
const initialState = {
data: {
definitions: []
},
requestStatus: null
};
function failUrbanDictionarySearch(state, action) {
const { data } = action.data;
return {
...state,
data,
requestStatus: statuses.FAILED
}
}
function getData(state, action) {
const { result } = action.data;
if (result.list.length > 0) {
const definitions = result.list.map(resultList => {
const { definition } = resultList;
return definition
})
return { ...state.data, definitions }
} else {
return { ...state.data, ...initialState.data }
}
}
function receiveUrbanDictionarySearch(state, action) {
return {
...state,
data: getData(state, action),
requestStatus: statuses.RECEIVED
};
}
function requestUrbanDictionarySearch(state) {
return { ...state, requestStatus: statuses.REQUESTED }
}
export default function urbanDictionarySearch(state = initialState, action) {
switch (action.type) {
case actionTypes.FAILED_URBAN_DICTIONARY_SEARCH:
return failUrbanDictionarySearch(state, action);
case actionTypes.RECEIVE_URBAN_DICTIONARY_SEARCH:
return receiveUrbanDictionarySearch(state, action);
case actionTypes.REQUEST_URBAN_DICTIONARY_SEARCH:
return requestUrbanDictionarySearch(state);
default:
return state
}
}
<file_sep>import React from 'react';
import "./ThesaurusResults.css";
export default function ThesaurusResults(props) {
const { conditionalRender, data, requestStatus } = props;
const { terms } = data;
return (
<div className={ `Result-Section ThesaurusResults` }>
<div className={ `Result ThesaurusResult` }>
{ conditionalRender({
status: requestStatus,
result: (terms && terms.map((term) => {
const { wordType, antonyms, synonyms } = term;
return (
<div className={ `WordType` } key={ `definition-${wordType}` }>
<div>{ `${wordType.toUpperCase()}:` }</div>
{ antonyms && <div>antonyms: { antonyms } </div> }
{ synonyms && <div>synonyms: { synonyms } </div> }
</div>
)
}
)
)
}) }
</div>
</div>
)
}
<file_sep>Starter app created using create-react-app.
Dependencies:
```
"devDependencies": {
"axios-mock-adapter": "^1.14.1",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"jest-enzyme": "^6.0.0",
"redux-mock-store": "^1.5.1"
}
```
```
"axios": "^0.18.0",
"lodash": "^4.17.5",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.7",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.1",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0"
```
<file_sep>import React from 'react';
import TextForm from 'components/TextForm'
import SearchResults from 'components/SearchResults/SearchResults';
import './SearchPage.css';
export default function SearchPage(props) {
const { fetchWord } = props;
return (
<div
className={ `SearchPage` }
>
<div className={ `Search-Section` }>
<TextForm
submitHandler={ fetchWord }
/>
</div>
<div className={ `Result-Section` }>
{ <SearchResults {...props} /> }
</div>
</div>
)
}
<file_sep>import { combineReducers } from "redux";
import searchWord from "./searchWord";
import officialDictionarySearch from "./officialDictionarySearch";
import thesaurusTermsSearch from "./thesaurusTermsSearch";
import urbanDictionarySearch from "./urbanDictionarySearch";
const rootReducer = combineReducers({
searchWord,
officialDictionarySearch,
thesaurusTermsSearch,
urbanDictionarySearch
});
export default rootReducer;
<file_sep>const requestPromise = require('request-promise');
module.exports = {
webstersSearch: function(word) {
const options = {
uri: `https://od-api.oxforddictionaries.com:443/api/v1/entries/en/${word}`,
headers: {
app_id: '70b66f4f',
app_key: '<KEY>'
},
json: true
};
return requestPromise(options)
.then(response => response)
.catch(error => console.log(error))
}
};
<file_sep>class HIError extends Error {
constructor(messageType, message) {
if (arguments.length === 2 && typeof messageType === 'string' && message) {
super()
let error = this.httpErrors(500, message).captureStackTrace(error, HomeInspectionError)
this.errorTypeOne = error
}
if (arguments.length == 2 && typeof messageType === 'number' && message) {
this.errorTypeTwo = this.httpError(messageType, message)
}
if (arguments.length == 2 && typeof messageType === 'object') {
this.errorTypeThree = "Something"
}
}
}
<file_sep>import * as actionTypes from 'constants/actionTypes/dictionarySearch';
import * as statuses from 'constants/statuses';
const initialState = {
data: {
etymologies: [],
definitions: []
},
requestStatus: null
};
function getData(state, action) {
const { result } = action.data;
if (result && result.response && result.response.results.length > 0) {
const responseResults = action.data.result.response.results[ 0 ];
const responseResultsEntries = responseResults.lexicalEntries[ 0 ].entries[ 0 ]
const { etymologies } = responseResultsEntries;
const { definitions } = responseResultsEntries.senses[ 0 ];
return { ...state.data, etymologies, definitions }
} else {
return { ...state.data, ...initialState.data }
}
}
function receiveOfficialDictionarySearch(state, action) {
return {
...state, data: getData(state, action),
requestStatus: statuses.RECEIVED
}
}
function failOfficialDictionarySearch(state, action) {
const { data } = action.data;
return {
...state,
data,
requestStatus: statuses.FAILED
}
}
function requestOfficialDictionarySearch(state) {
return { ...state, requestStatus: statuses.REQUESTED }
}
export default function officialDictionarySearch(state = initialState, action) {
switch (action.type) {
case actionTypes.FAILED_OFFICIAL_DICTIONARY_SEARCH:
return failOfficialDictionarySearch(state, action);
case actionTypes.RECEIVE_OFFICIAL_DICTIONARY_SEARCH:
return receiveOfficialDictionarySearch(state, action);
case actionTypes.REQUEST_OFFICIAL_DICTIONARY_SEARCH:
return requestOfficialDictionarySearch(state);
default:
return state
}
}
<file_sep>export const FETCH_WORD = 'FETCH_WORD';
export const SET_WORD = 'SET_WORD';
export const FAILED_OFFICIAL_DICTIONARY_SEARCH = 'FAILED_OFFICIAL_DICTIONARY_SEARCH';
export const RECEIVE_OFFICIAL_DICTIONARY_SEARCH = 'RECEIVE_OFFICIAL_DICTIONARY_SEARCH';
export const REQUEST_OFFICIAL_DICTIONARY_SEARCH = 'REQUEST_OFFICIAL_DICTIONARY_SEARCH';
export const FAILED_URBAN_DICTIONARY_SEARCH = 'FAILED_URBAN_DICTIONARY_SEARCH';
export const FAILED_THESAURUS_TERMS_SEARCH = 'FAILED_THESAURUS_TERMS_SEARCH';
export const RECEIVE_URBAN_DICTIONARY_SEARCH = 'RECEIVE_URBAN_DICTIONARY_SEARCH';
export const REQUEST_URBAN_DICTIONARY_SEARCH = 'REQUEST_URBAN_DICTIONARY_SEARCH';
export const RECEIVE_THESAURUS_TERMS_SEARCH = 'RECEIVE_THESAURUS_TERMS_SEARCH';
export const REQUEST_THESAURUS_TERMS_SEARCH = 'REQUEST_THESAURUS_TERMS_SEARCH';
<file_sep>import * as actionTypes from 'constants/actionTypes/dictionarySearch';
const initialState = {
word: null
};
function setWord(state, action) {
const { word } = action.data;
return { ...state, word }
}
export default function searchWord(state = initialState, action) {
switch (action.type) {
case actionTypes.SET_WORD:
return setWord(state, action);
default:
return state
}
}
<file_sep>import React, { Component } from 'react';
import './TextForm.css';
export default class TextForm extends Component {
state = { word: "" };
handleChange = (event) => {
this.setState({ word: event.target.value })
};
handleSubmit = (e) => {
e.preventDefault();
const { submitHandler } = this.props;
const { word } = this.state;
submitHandler(word)
};
render() {
return (
<div
className={ `TextFormContainer` }
>
<form
className={ `TextForm` }
>
<input
className={ `WordTextInput` }
type="text"
name="words"
value={ this.state.word }
onChange={ this.handleChange }
/>
<input
className={ `Submit` }
type="submit"
value="Submit"
onClick={ this.handleSubmit }
/>
</form>
</div>
)
}
}
<file_sep>import React from 'react';
import * as renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
import TextForm from 'components/TextForm';
describe('TextForm', () => {
it('generates a snapshot', () => {
const tree = renderer.create(<TextForm/>).toJSON();
expect(tree).toMatchSnapshot();
});
it(`changes it's input value`, () => {
const component = shallow(<TextForm/>);
const textInput = component.find(`input[name="words"]`);
const inputValue = 'hat';
textInput.simulate('change', { target: { value: inputValue } });
const componentState = component.state();
expect(componentState.words).toEqual(inputValue)
})
});
<file_sep>import axios from 'axios';
export function getRequest({ url }) {
return axios.get(url).then(response => response)
}
<file_sep>import * as request from 'api/request';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const mock = new MockAdapter(axios);
describe('request', () => {
describe('getRequest', () => {
it('gets a response', async () => {
const headers = { api_key: 'randomKey123' };
const params = { word: 'hat' };
const url = "http://api.website.com";
const response = {
definition: 'something you wear on your head'
};
mock.onGet(url, { params }).reply(200, response);
const result = await request.getRequest({ params, url, headers});
expect(result).toMatchObject(response)
})
})
});
<file_sep>export const webstersSearchURL = `/api/webstersSearch`;
export const urbanDictionarySearchUrl = `https://api.urbandictionary.com/v0/define`;
export const thesaurusSearchUrl = `https://words.bighugelabs.com/api/2/${process.env.REACT_APP_BIG_HUGE_LABS_TOKEN}`;
<file_sep>jest.mock('reducers/index')
import React from 'react';
import App from 'components/App';
import {shallow} from 'enzyme';
describe('App', () => {
it('renders without crashing', () => {
const component = shallow(<App />);
expect(component.exists()).toBeTruthy();
});
});
<file_sep>- search history
- without redux
<file_sep>import React, { Component } from 'react';
import "./SearchResults.css"
import * as statuses from 'constants/statuses';
import LoadingSpinner from 'components/LoadingSpinner/LoadingSpinner';
import OfficialDictionaryResults from "components/OfficialDictionaryResults/OfficialDictionaryResults";
import UrbanDictionaryResults from "components/UrbanDictionaryResults/UrbanDictionaryResults";
import ThesaurusResults from "components/ThesaurusResults/ThesaurusResults";
export default class SearchResult extends Component {
conditionalRender = ({ status, result }) => {
switch (status) {
case(statuses.REQUESTED):
return <LoadingSpinner/>;
case(statuses.RECEIVED):
return result;
default:
return null
}
}
renderSearchResults = () => {
const {
searchWord, officialDictionarySearch, urbanDictionarySearch, thesaurusTermsSearch
} = this.props;
const { word } = searchWord;
const resultsSet = [
{ result: officialDictionarySearch, Component: OfficialDictionaryResults },
{ result: urbanDictionarySearch, Component: UrbanDictionaryResults },
{ result: thesaurusTermsSearch, Component: ThesaurusResults },
];
return word && word !== "" ?
(
<div
key={ word }
className={ `Search-Result` }
>
<div className={ `Search-Word` }>
{ word }
</div>
<div className={ `Result-Sections` }>
{ resultsSet.map((resultSet, index) => {
const { result, Component } = resultSet;
return <Component { ...result } key={ `${index}` } conditionalRender={ this.conditionalRender }/>
})
}
</div>
</div>
)
:
null
}
render() {
return (
<div className={ `Search-Results` }>
<div className={ `Search-Result-Headings` }>
<div className={ `Word-Heading` }>
Word
</div>
<div className={ `Result-Sections-Headings` }>
<div className={ `Result-Heading` }>
Official Definition
</div>
<div className={ `Result-Heading` }>
Official Etymology
</div>
<div className={ `Result-Heading` }>
Urban Dictionary Definition
</div>
<div className={ `Result-Heading` }>
Thesaurus
</div>
</div>
</div>
{ this.renderSearchResults() }
</div>
)
}
}
|
62c0b9adc71a60107aa24886b26bd15831a26e1d
|
[
"JavaScript",
"Markdown"
] | 18 |
JavaScript
|
davidimoore/archive-async-word-search
|
2f986cc1a76b64e3dabf0a3841d2a3097de90ed8
|
8a770ec51519c77f9ed0fc1f38fe2f5355326576
|
refs/heads/master
|
<repo_name>KubaO/coroutine_experiments<file_sep>/co_awaiter.hpp
// A basic return object and promise type for a coroutine that co_awaits
/*
Copyright (c) 2018 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef CO_AWAITER_HPP
#define CO_AWAITER_HPP
#include <type_traits>
#include <experimental/coroutine>
template<typename T=void>
struct await_return_object {
struct promise_type;
await_return_object(promise_type & p) : m_coro(std::experimental::coroutine_handle<promise_type>::from_promise(p)) {}
await_return_object(await_return_object const &) = delete;
await_return_object(await_return_object && other) {
m_coro = other.m_coro;
other.m_coro = nullptr;
}
~await_return_object() {
if (m_coro) {
m_coro.destroy();
}
}
// promise type must have either return_void or return_value member but not both
// not even if one is SFINAEd out - you cannot have both names present, per Lewis Baker
template<typename U>
struct promise_base {
void return_value(U const&) const noexcept {
}
};
// void specialization to replace with return_void() is below at namespace scope
#ifdef INTERNAL_VOID_SPECIALIZATION
template<>
struct promise_base<void> {
void return_void() const noexcept {}
};
#endif // INTERNAL_VOID_SPECIALIZATION
struct promise_type : promise_base<T> {
// coroutine promise requirements:
auto initial_suspend() const noexcept {
return std::experimental::suspend_never(); // produce at least one value
}
auto final_suspend() const noexcept {
return std::experimental::suspend_always(); // ?? not sure
}
// either return_void or return_value will exist, depending on T
await_return_object get_return_object() {
return await_return_object(*this);
}
void unhandled_exception() {} // do nothing :)
};
private:
std::experimental::coroutine_handle<promise_type> m_coro;
};
#ifndef INTERNAL_VOID_SPECIALIZATION
template<>
template<>
struct await_return_object<void>::promise_base<void> {
void return_void() const noexcept {
}
};
#endif // INTERNAL_VOID_SPECIALIZATION
#endif // CO_AWAITER_HPP
<file_sep>/my_awaitable.hpp
// A simple Awaitable type for experiments
/*
Copyright (c) 2018 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef MY_AWAITABLE_HPP
#define MY_AWAITABLE_HPP
#include <experimental/coroutine>
#include <type_traits>
template<typename F,
typename ReturnType = typename std::remove_cv_t<std::invoke_result_t<F>>>
struct my_awaitable {
// construct with a nullary function that does something and returns a value
my_awaitable(F work_fn) : work_(work_fn) {}
struct awaiter {
awaiter(my_awaitable* awaitable) : awaitable_(awaitable) {}
bool await_ready() const noexcept { return false; } // pretend to not be ready
ReturnType await_resume() noexcept { return awaitable_->work_(); }
template<typename P>
void await_suspend(std::experimental::coroutine_handle<P> coro) noexcept {
// decide we are ready after all, so resume caller
coro.resume();
// we could also leave off the call to resume() and return false from a bool version
// of this function. That means "don't suspend".
}
my_awaitable* awaitable_; // remember parent
};
awaiter operator co_await () { return awaiter{this}; }
private:
F work_;
};
// type deduction helper
template<typename F>
my_awaitable<F>
make_my_awaitable(F fn) {
return my_awaitable{fn};
}
#endif // MY_AWAITABLE_HPP
|
06bfaf8ffedcc73ecec2e0140aa8ae5f4f23c9ec
|
[
"C++"
] | 2 |
C++
|
KubaO/coroutine_experiments
|
4e64cdb6d8cc7f739401caf552244ab198d1fd98
|
b0618f7fd3eb38b3b97920d16892b0130e19c78f
|
refs/heads/master
|
<repo_name>msoyks/js-math-solver<file_sep>/main.js
function solveMath() {
var math = document.getElementById("mathToSolve").value;
var answer = eval(math);
document.getElementById("mathAnswer").innerHTML = answer;
}
<file_sep>/README.md
# JS Math Solver [](https://npmjs.org/package/msoyks-math-solver)
[](https://greenkeeper.io/)
## A program by [msoyks](https://github.com/msoyks) and [bsoyka](https://github.com/bsoyka)
|
53d176cda35ad1057e129adac36f8d9c65bb9191
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
msoyks/js-math-solver
|
26d41903f2f8b6968d4980e0b6ce71ee3d3c3c85
|
65ae933aff4203d4f09cb87dcfa6dba8d1fcd722
|
refs/heads/master
|
<repo_name>MindaugasKvietkus/Deevoo<file_sep>/src/AppBundle/Form/LoginFormType.php
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\AbstractType;
use AppBundle\Entity\LoginVariables;
class LoginFormType extends AbstractType{
public function buildForm (FormBuilderInterface $builder, array $option){
$builder->add('username', TextType::class, array(
'label' => 'Username'
))
->add('password', PasswordType::class, array(
'label' => 'Password'
))
->add('login', SubmitType::class);
}
public function configureOptions (OptionsResolver $resolver){
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\LoginVariables'
));
}
public function getName()
{
return 'login';
}
}<file_sep>/src/AppBundle/Entity/LoginVariables.php
<?php
namespace AppBundle\Entity;
class LoginVariables {
public $username;
public $password;
}<file_sep>/src/AppBundle/Form/AddUserFormType.php
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\AbstractType;
use AppBundle\Entity\CorrectUserDatabase;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class AddUserFormType extends AbstractType{
public function buildForm (FormBuilderInterface $builder, array $option){
$builder->add('username', TextType::class, array(
'label' => 'Username'
))
->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
))
->add('role', ChoiceType::class, array(
'choices' => array(
'user' => 'ROLE_USER',
'admin' => 'ROLE_ADMIN'
)
))
->add('add', SubmitType::class);
}
public function configureOptions (OptionsResolver $resolver){
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\CorrectUserDatabase'
));
}
public function getName()
{
return 'addUser';
}
}<file_sep>/src/AppBundle/Form/EmailFormType.php
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
class EmailFormType extends AbstractType{
public function buildForm (FormBuilderInterface $builder, array $option){
$builder->add('email', EmailType::class, array(
'label' => 'Recipient\'s e-mail'
))
->add('message', TextareaType::class, array(
'label' => 'Message',
))
->add('send', SubmitType::class);
}
public function configureOptions (OptionsResolver $resolver){
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Email'
));
}
public function getName()
{
return 'send_email';
}
}<file_sep>/src/AppBundle/Entity/ImagesVariables.php
<?php
namespace AppBundle\Entity;
class ImagesVariables {
public $id;
public $project_id;
public $images_name;
public $images_path;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set projectId
*
* @param integer $projectId
*
* @return ImagesVariables
*/
public function setProjectId($projectId)
{
$this->project_id = $projectId;
return $this;
}
/**
* Get projectId
*
* @return integer
*/
public function getProjectId()
{
return $this->project_id;
}
/**
* Set imagesName
*
* @param string $imagesName
*
* @return ImagesVariables
*/
public function setImagesName($imagesName)
{
$this->images_name = $imagesName;
return $this;
}
/**
* Get imagesName
*
* @return string
*/
public function getImagesName()
{
return $this->images_name;
}
/**
* Set imagesPath
*
* @param string $imagesPath
*
* @return ImagesVariables
*/
public function setImagesPath($imagesPath)
{
$this->images_path = $imagesPath;
return $this;
}
/**
* Get imagesPath
*
* @return string
*/
public function getImagesPath()
{
return $this->images_path;
}
}
<file_sep>/src/AppBundle/Form/ProjectImagesAdditionalForm.php
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\Button;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
class ProjectImagesAdditionalForm extends AbstractType{
public function buildForm (FormBuilderInterface $builder, array $option)
{
$builder->add('project_name', TextType::class)
->add('images_name', CollectionType::class, array(
'entry_type' => TextType::class,
'allow_add' => TRUE,
'allow_delete' => TRUE,
'entry_options' => array(
'label' => FALSE
)
))
->add('images_path', CollectionType::class, array(
'entry_type' => TextType::class,
'allow_add' => TRUE,
'allow_delete' => TRUE,
'entry_options' => array(
'label' => FALSE
)
))
->add('images_id', CollectionType::class, array(
'entry_type' => TextType::class,
'allow_add' => TRUE,
'allow_delete' => TRUE,
'entry_options' => array(
'label' => FALSE
)
))
->add('delete', CollectionType::class, array(
'entry_type' => SubmitType::class,
'entry_options' => array(
'label' => FALSE
)
))
->add('update', ButtonType::class)
->add('add_file', FileType::class, array(
'label' => 'File',
'multiple' => TRUE
))
->add('add', ButtonType::class);
}
public function configureOptions (OptionsResolver $resolver){
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\ProjectImagesAdditionalVariables'
));
}
public function getName()
{
return 'add_image';
}
}
/**
* Created by PhpStorm.
* User: Mariukas
* Date: 2016.11.10
* Time: 13:17
*/<file_sep>/README.md
projectdeevoo
=============
A Symfony project created on October 20, 2016, 11:42 am.
<file_sep>/src/AppBundle/Form/ProjectFormType.php
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\Button;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
class ProjectFormType extends AbstractType{
public function buildForm (FormBuilderInterface $builder, array $option){
$builder->add('projectname', TextType::class, array(
'label' => 'Project name'
))
->add('file', FileType::class, array(
'label' => 'File',
'multiple' => TRUE
))
->add('add', SubmitType::class);
}
public function configureOptions (OptionsResolver $resolver){
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\ProjectFromVariables'
));
}
public function getName()
{
return 'addproject';
}
}<file_sep>/src/AppBundle/Controller/MainController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\ProjectImagesAdditionalVariables;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\LoginVariables;
use AppBundle\Form\LoginFormType;
use AppBundle\Entity\ProjectVariables;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use AppBundle\Entity\ProjectFromVariables;
use AppBundle\Entity\ImagesVariables;
use AppBundle\Entity\Email;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;
use AppBundle\Entity\Login;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Serializer\SerializerAwareTrait;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use AppBundle\Entity\CorrectUserDatabase;
use AppBundle\Form\AddUserFormType;
use Symfony\Component\Security\Core\Tests\Encoder\PasswordEncoder;
class MainController extends Controller
{
/**
* @Route("/", name="login")
*/
public function index(Request $request){
$login = new LoginVariables();
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$form = $this->createForm('AppBundle\Form\LoginFormType', $login);
if($request->getMethod() === 'POST'){
$form = $form->handleRequest($request);
if ($form->isValid()){
$user = $this->getDoctrine()->getRepository("AppBundle:CorrectUserDatabase")->findOneBy(array(
'username' => $login->username,
'password' => $<PASSWORD>-><PASSWORD>,
));
$json_user = $serializer->serialize($user, "json");
$json_decode = json_decode($json_user, TRUE);
if (($login->username == $json_decode['username']) && ($login->password = $json_decode['password'])){
return $this->redirectToRoute ( 'home' );
}else{
echo "Not correct username or password";
}
}
}
return $this->render('default/index.html.twig', array(
'form' => $form->createView(),
));
}
/**
* @Route ("/home", name="home")
*/
public function home(){
$project = $this->getDoctrine()
->getRepository("AppBundle:ProjectVariables")
->findAll();
return $this->render('default/home.html.twig', array(
'projects' => $project,
));
}
/**
*@route("/addproject", name="addproject")
*/
public function addproject(Request $request){
$addproject = new ProjectFromVariables();
$form = $this->createForm('AppBundle\Form\ProjectFormType', $addproject);
if($request->getMethod() === 'POST'){
$form = $form->handleRequest($request);
if ($form->isValid()){
$project = new ProjectVariables();
$images_info = new ImagesVariables();
$em = $this->getDoctrine()->getManager();
$project->disable = 0;
$project->project_name = $addproject->projectname;
$em->persist($project);
$em->flush();
foreach($addproject->file as $file){
$projectId = $project->getId();
$photo = new ImagesVariables();
$photo->setProjectId($project);
$photo->setImagesName( $file->getClientOriginalName());
$photo->setImagesPath("/uploaded_images/".$project->id."/".$file->getClientOriginalName());
$project->file_info->add($photo);
$file->move($this->getParameter("temp_uploaded_images"), $file->getClientOriginalName());
//."/".$project->project_name."/"
}
$em->persist($project);
$em->flush();
$finder = new Finder();
$finder->files()->in($this->getParameter("temp_uploaded_images"));
$change_path = $this->getParameter("uploaded_images")."/".$project->id."/";
$fs = new Filesystem();
$fs->mirror($this->getParameter("temp_uploaded_images"), $change_path);
$fs->remove($this->getParameter("temp_uploaded_images"));
}
}
return $this->render('default/addproject.html.twig', array(
'form' => $form->createView(),
));
}
/**
* @Route("/edit/{id}", name="edit")
*/
public function Edit($id){
/**
* @var $project ProjectVariables
* @var $images ImagesVariables
* */
$project = $this->getDoctrine()->getRepository("AppBundle:ProjectVariables")->find($id);
$images = $this->getDoctrine()->getRepository("AppBundle:ImagesVariables")->findBy(array(
'project_id' => $id
));
$images = $project->getFileInfo();
$addproject = new ProjectImagesAdditionalVariables();
$addproject->project_name = $project->getProjectName();
$array_names = array();
$array_path = array();
$array_id = array();
foreach ($images as $image){
array_push($array_names, $image->getImagesName());
array_push($array_path, $image->getImagesPath());
array_push($array_id, $image->getId());
}
$addproject->images_name = $array_names;
$addproject->images_path = $array_path;
$addproject->images_id = $array_id;
$form = $this->createForm('AppBundle\Form\ProjectImagesAdditionalForm', $addproject);
return $this->render('default/edit.html.twig', array(
'form' => $form->createView(),
'project' => $project,
'images' => $images,
'id' => $array_id,
'names' => $array_names,
'project_id' => $id
));
}
/**
* @Route("/disable/{id}")
*/
public function setDisable($id){
$em = $this->getDoctrine()->getManager();
$project = $em->getRepository("AppBundle:ProjectVariables")->find($id);
$project->setDisable(1);
$em->flush();
return $this->redirectToRoute("home");
}
/**
* @Route("/enable/{id}")
*/
public function setEnable($id){
$em = $this->getDoctrine()->getManager();
$project = $em->getRepository("AppBundle:ProjectVariables")->find($id);
$project->setDisable(0);
$em->flush();
return $this->redirectToRoute("home");
}
/**
* @Route("/view/{id}/{page}", name="projectView")
*/
public function getView($id, $page = 1){
$project = $this->getDoctrine()->getRepository("AppBundle:ProjectVariables")->find($id);
if ($project->getDisable() == 0){
$images_count = $this->getDoctrine()->getRepository("AppBundle:ImagesVariables")->findBy(array(
'project_id' => $id
));
$limit = count($images_count);
$count = array();
for ($i = 1; $i<=$limit; $i++){
array_push($count, $i);
}
//print_r($count);
$images = $this->getDoctrine()->getRepository("AppBundle:ImagesVariables")->findBy(array(
'project_id' => $id
),array(), 1, $page);
//print_r($project);
return $this->render('default/view.html.twig', array(
'project' => $project,
'images' => $images,
'count' => $count
));
}else {
return $this->render('default/notfound.html.twig');
}
}
/**
* @Route("/send/{id}")
*/
public function Send(Request $request, $id){
$project = $this->getDoctrine()->getRepository("AppBundle:ProjectVariables")->find($id);
$send_email = new Email();
$form = $this->createForm('AppBundle\Form\EmailFormType', $send_email);
if($request->getMethod() === 'POST'){
$form = $form->handleRequest($request);
if ($form->isValid()){
$message = $send_email->message."\r\n\r\n<a href=\"localhost:8000/view/$id\">Peržiūra</a>";
$email = \Swift_Message::newInstance()
->setSubject("Send project")
->setFrom("<EMAIL>", "<NAME>")
->setTo($send_email->email)
->setBody($message, 'text/html');
$sent = $this->get('mailer')->send($email);
}
}
return $this->render('default/send.html.twig', array(
'form' => $form->createView()
));
}
/**
* @Route("/delete/{id}", name="delete")
*/
public function Delete($id){
$em = $this->getDoctrine()->getManager();
$project = $em->getRepository("AppBundle:ProjectVariables")->find($id);
$em->remove($project);
$em->flush();
return $this->redirectToRoute("home");
}
/**
* @Route("/delete_images/{id}", name="delete_images")
*/
public function DeleteImages($id){
$em = $this->getDoctrine()->getManager();
$image = $em->getRepository("AppBundle:ImagesVariables")->findOneBy(array(
'id' => $id
));
$project = $em->getRepository("AppBundle:ProjectVariables")->findOneBy(array(
'id' => $image->getProjectId()
)
);
$windows_path = str_replace('/', '\\', $image->getImagesPath());
$path = $this->getParameter("web").$windows_path;
$fs = new Filesystem();
$fs->remove($path);
$em->remove($image);
$em->flush();
return $this->redirectToRoute("edit", array(
'id' => $project->getId()
));
}
/**
* @Route ("/add_images/{id}", name="add_images")
*/
/*
* Neveikia
*/
public function AddImage(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$project = $em->getRepository("AppBundle:ProjectVariables")->findOneBy(array(
'id' => $id
)
);
$image = new ProjectImagesAdditionalVariables();
print_r($image->add_file);
foreach ($image->add_file as $file) {
$photo = new ImagesVariables();
$photo->setProjectId($project->id);
$photo->setImagesName($file->getClientOriginalName());
$photo->setImagesPath("/uploaded_images/" . $project->id . "/" . $file->getClientOriginalName());
$project->file_info->add($image->add_file);
$file->move($this->getParameter("temp_uploaded_images"), $file->getClientOriginalName());
//."/".$project->project_name."/"
}
$em->persist($project);
$em->flush();
exit;
$finder = new Finder();
$finder->files()->in($this->getParameter("temp_uploaded_images"));
$change_path = $this->getParameter("uploaded_images")."/".$project->id."/";
$fs = new Filesystem();
$fs->mirror($this->getParameter("temp_uploaded_images"), $change_path);
$fs->remove($this->getParameter("temp_uploaded_images"));
}
/**
* @Route ("/images_update/{id}", name="images_update")
*/
public function ImagesUpdate($id){
$em = $this->getDoctrine()->getManager();
$project = $em->getRepository("AppBundle:ProjectVariables")->findOneBy(array(
'id' => $id
));
$image = $em->getRepository("AppBundle:ImagesVariables")->findBy(array(
'project_id' => $id
));
$image_form = new ProjectImagesAdditionalVariables();
//print_r($image->getImagesPath());
exit;
print_r($project->getImagesName());
print_r($project->getProjectId());
print_r($project->getId());
exit;
$image_form->images_id = $project->getId();
$project->setProjectId($project->getProjectId());
$image_form->images_name = $project->getImagesName();
$image_form->images_path = $project->getImagesPath();
return $this->redirectToRoute("edit", array(
""
));
}
/**
* @Route("/logout", name="logout")
*/
public function Logout(){
/*
$session = new Session();
$username = $session->get("username");
$session->remove("username");
return $this->redirectToRoute("login", array(
'username' => $username
));
*/
}
/**
* @Route("/test/{id}", name="test")
*/
public function Test($id){
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
/*
$user = $this->getDoctrine()->getRepository("AppBundle:Login")->findOneBy(array(
'username' => $login->username,
'password' => $login-><PASSWORD>,
));
*/
$project = $this->getDoctrine()->getRepository("AppBundle:ProjectVariables")->findOneBy(array(
'id' => $id
));
$project_id = $this->getDoctrine()->getRepository("AppBundle:ImagesVariables")->findBy(array(
'project_id' => $id
));
print_r($project);
//$json_user = $serializer->serialize($project_id, "json");
//$json_decode = json_decode($json_user, TRUE);
//print_r($json_user);
return $this->render('default/test.html.twig', array(
'project_id' => $project_id
));
}
/**
* @Route("/add_user", name="add_user")
*/
public function Adduser(Request $request){
$addUser = new CorrectUserDatabase();
$form = $this->createForm("AppBundle\Form\AddUserFormType", $addUser);
if($request->getMethod() === 'POST'){
$form = $form->handleRequest($request);
if ($form->isValid()){
$password = $this->get("security.password_encoder")
->encodePassword($addUser, $addUser->getPassword());
$addUser->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->persist($addUser);
$em->flush();
return $this->redirectToRoute('home');
}
}
return $this->render("default/addUser.html.twig", array(
'form' =>$form->createView()
));
}
}
<file_sep>/src/AppBundle/Entity/ProjectVariables.php
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
class ProjectVariables {
public $id;
public $project_name;
public $disable = NULL;
public $file_info;
public function __construct(){
$this->file_info = new ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set projectName
*
* @param string $projectName
*
* @return ProjectVariables
*/
public function setProjectName($projectName)
{
$this->project_name = $projectName;
return $this;
}
/**
* Get projectName
*
* @return string
*/
public function getProjectName()
{
return $this->project_name;
}
/**
* Set disable
*
* @param integer $disable
*
* @return ProjectVariables
*/
public function setDisable($disable)
{
$this->disable = $disable;
return $this;
}
/**
* Get disable
*
* @return integer
*/
public function getDisable()
{
return $this->disable;
}
/**
* Add fileInfo
*
* @param \AppBundle\Entity\ImagesVariables $fileInfo
*
* @return ProjectVariables
*/
public function addFileInfo(\AppBundle\Entity\ImagesVariables $fileInfo)
{
$this->file_info[] = $fileInfo;
return $this;
}
/**
* Remove fileInfo
*
* @param \AppBundle\Entity\ImagesVariables $fileInfo
*/
public function removeFileInfo(\AppBundle\Entity\ImagesVariables $fileInfo)
{
$this->file_info->removeElement($fileInfo);
}
/**
* Get fileInfo
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getFileInfo()
{
return $this->file_info;
}
}
<file_sep>/src/AppBundle/Entity/Email.php
<?php
namespace AppBundle\Entity;
class Email {
public $email;
public $message;
}<file_sep>/src/AppBundle/Entity/ProjectFromVariables.php
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ProjectFromVariables {
public $projectname;
/**
* @var UploadedFile
*/
public $file;
}<file_sep>/src/AppBundle/Entity/ProjectImagesAdditionalVariables.php
<?php
namespace AppBundle\Entity;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ProjectImagesAdditionalVariables {
public $project_name;
public $images_name;
public $images_path;
public $images_id;
public $delete;
public $update;
public $insert;
/**
* @var UploadedFile
*/
public $add_file;
}
/**
* Created by PhpStorm.
* User: Mariukas
* Date: 2016.11.10
* Time: 13:23
*/
|
5e5d026a2a2dc3d051f663b8c4f8194242f08d63
|
[
"Markdown",
"PHP"
] | 13 |
PHP
|
MindaugasKvietkus/Deevoo
|
124f5720f5f4d2e54183869eb07467c5b035d218
|
509b68ad50005eff4b79c256746e102ecf129ca4
|
refs/heads/master
|
<repo_name>aniket-yadav/python_basics<file_sep>/assingment.py
# multiple asignment
x=y=z=10
print(x)
print(y)
print(z)
p,q,r = 10,100,1000
print(p)
print(q)
print(r)
<file_sep>/tuple.py
a = (1,2,34,5,5,'abc',"python",(1212,344,56,3),[12,34,56],{'name':'python'})
print(isinstance(a,tuple))
print(a)
print(a[3:5])
print(a[:])
print(a[:4])
print(a[2:])
print(a[6]*2)
print(a[-4])
# does not support assignment
a[4]='a'<file_sep>/list.py
# a = [1,3,5,'a',"aniket",[1,2,3,4],(1,2,3,4),{'name':'pyton'}]
# print(isinstance(a,list))
# print(a)
# print(a[0:3])
# print(a[5:])
# print(a[:5])
# print(a[4]+' likes '+a[-1]['name'])
# print(a[5]*5)
mobileBrand = []
no = int(input('Enter number of value you want to enter : '))
for i in range(0,no):
mobileBrand.append(input("Enter element : "))
print("Mobile brands : ")
for i in mobileBrand:
print(i)
<file_sep>/memorymange.py
# object identityfier memory management for same value python doesn't give new memory location
a = 100
b = a
print(id(a))
print(id(b))
b= 1
print(id(b))
<file_sep>/string.py
# # single line
# a = 'python'
# b = "this is python "
# # multiline
# c= ''' this
# is
# python
# string
# demo '''
# d = """ you can use
# single or
# double quote """
# print(a)
# print(b)
# print(c)
# print(d)
# print(a+b)
# print(a*3)
# print('this is {}. hello {}'.format('python',"aniket"))
# print('this is {1}. hello {0}'.format("aniket",'python'))
# print('this is {a}. hello {b}'.format(b="aniket",a='python'))
# string function
a = 'pythonyyashdjkfnchuwueosjdhfk'
print(a.count('y',0,-1))
print(a.endswith('k',0,len(a)))
print(a.find('y',4,-1))
b= 'an23'
print(b.isalnum())
b= '23'
print(b.isdigit())
<file_sep>/loop.py
# list1 = [1,2,3,4,5]
# for a in list1:
# print(a)
# no1 = int(input("Enter number to find table of it : "))
# for i in range(1,11):
# print(f'{no1} * {i} = {no1*i}')
no1 = int(input("Enter number to find table of it : "))
i= 1
while i<= 10:
print(f'{no1} * {i} = {no1*i}')
i+=1
<file_sep>/filterfun.py
def greaterThanFive(no):
if no > 5:
return True
return False
list1 = [2,34,5,66,4,34,23,6]
list2 = list(filter(greaterThanFive,list1))
print(list2)
list3 = list(filter(lambda a: a>5,list1))
print(list3)
<file_sep>/functions.py
def hello(name):
print(f'hello, {name}')
hello("aniket")
def factorial(no):
if(no == 0):
return 1
return no*factorial(no - 1)
print(factorial(5))
# types function based on arguments
# normal
def hello(name):
print(f'hello, {name}')
hello("aniket")
# default args
def sayName(name = "Anom"):
print(name)
sayName()
sayName("aniket")
# variable length args
def createList(*elements):
return(list(elements))
print(createList('python','java','C#'))
# keyword arguments
def person(name,age):
print(f'my name is {name} and i am {age} old')
person(age=23,name="aniket")
def createDict(**args):
print(args)
createDict(name="apple",color='res')<file_sep>/files/files.py
import os
os.rename('read.txt','readfile.txt')
# file = open('read.txt','r')
# if(file):
# print('file is open now')
# txt = file.readline()
# print(txt)
# file.close()
# with open('read.txt','r') as f:
# txt = f.readline()
# print(txt)
# file = open('write.txt','w')
# if(file):
# file.write('hello ')
# file.close()
# file = open('write.txt', 'a')
# if(file):
# file.write(' world')
# file.close()
# with open('write.txt','a') as f:
# f.write('file demo')
# with open('read.txt','r') as r:
# with open('write.txt','a') as w:
# w.write(r.read())
<file_sep>/operator.py
# arithmetic operators
a = 5
b = 2
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a**b)
print(a//b)
print(a%b)
# comparison operators
print(a == b)
print(a != b)
print(a <= b)
print(a >= b)
print(a > b)
print(a < b)
# assignment operator
a+=b
print(a)
a-=b
print(a)
a/=b
print(a)
a//=b
print(a)
a*=b
print(a)
a**=b
print(a)
# bitwise operator
a = 1
b = 2
# 0001
# 0010
print(a & b )
print(a | b )
print(a ^ b )
print( ~b )
print(a << 1 )
print(a >> 1 )
# logical operator
print( True and True)
print( True and False)
print( True or True)
print( True or False)
print( not True)
# membership operator
a = (1,3,5,7)
print( 3 in a)
print(4 in a)
print(3 not in a)
print(4 not in a)
# identity operator
a = 5
b = 5
print( a is b)
print(a is not b)<file_sep>/type.py
#data type in python
print(type("hello world"))
print(type('a'))
print(type(1))
print(type(23.45))
print(type(True))
print(type(1+7j))
print(type([1,23,4]))
print(type((1,23,454)))
print(type({'name':"aniket",'age':23}))
<file_sep>/set.py
set1 = set()
print(set1)
set2 = {1,3,4,56,(123,3,42)}
print(set2)
set2.add('aniket')
print(set2)
set2.remove(56)
print(set2)
set2.pop()
print(set2)<file_sep>/mapfun.py
def doubleNumber(no):
return no*2
list1 = [1,3,5,6]
list2 = list(map(doubleNumber,list1))
print(list2)
list3 = list(map(lambda a: a*2,list1))
print(list3)
<file_sep>/isintance.py
#isinstance
a = 1
print(isinstance(a,int))<file_sep>/modules/calculation.py
def add(*args):
sum = 0
for i in args:
sum+=i
return sum
def sub(a,b):
return a-b
def mult(*args):
product = 1
for i in args:
product *= i
return product
def div(a,b):
return a//b
<file_sep>/modules/test.py
import calculation as cal
while 1:
try:
a = int(input("Enter value of a : "))
b = int(input("Enter value of b : "))
op = int(input("""Options :
1. Add
2. sub
3. mult
4. div
Enter option no : """))
oplist = [1,2,3,4]
if(op not in oplist):
raise ValueError("Invalid option selected")
if(op == 1):
print(f'Addition of {a} and {b} is {cal.add(a,b)}')
elif(op == 2):
print(f'Subtraction of {b} from {a} is {cal.sub(a,b)}')
elif(op == 3):
print(f'Multiplication of {a} and {b} is {cal.mult(a,b)}')
elif(op == 4):
print(f'Division of {b} by {a} is {cal.div(a,b)}')
else:
print('invalid input ')
except Exception as e:
print(e)
else:
print("Operation successful")
finally:
cont = input("Do you want to continue y/n : ")
if(cont == 'n'):
break
<file_sep>/zipfun.py
list1 = [1,2,3,4,5]
list2 = ['one','two','three','four','five']
list3 = set(zip(list1,list2))
print(list3)
list4 = ['1','2','3']
list5 = [1,2]
print(list(zip(list4,list5)))
list4 = ['1','2','3']
list5 = [1,2,4,6]
print(list(zip(list4,list5)))<file_sep>/ifelse.py
# if else condition
age = int(input("Enter your age : "))
if age > 18:
print("You are allowed to vote ")
else:
print("You are not allowed to vote")
# if elif condition
marks = int(input("Enter your marks out of 100 : "))
if(marks > 90):
print('O grade')
elif(marks > 75):
print('A+ grade')
elif(marks > 60):
print('A grade')
elif(marks > 50):
print('B grade')
elif(marks > 40):
print('C grade')
else:
print('You failed')
adhunik compuer ke janak
bharat me kis prakar ka computer upalabhdh hai
3 search engine
antivirus kya hai
plagiarism kya hai
computer deri ki kami
computer ka mantrikan kise kahte hai
website kise kahte hai
hard copy softcopy
compuet kranti kya hai
sodh ke kendra me compuer ki kya upyogika hai
computer ke gun aur dosh
computer pointpresntation kya hai
computer dwaraa aakda sishleshan ka udhaharan
sodhh prashtuti yavam computer sambandho ko batayiye
sampling ke nirdharan me computer ki kya bhumika hai
english na jannane wale vidyarathiyon ke sikhne me aane wali kathinayio ko batayiye
<file_sep>/dict.py
a = {1:'one',2:"two",3:(1,3,4),4:[2,5,4],"name":'aniket'}
print(isinstance(a,dict))
print(a)
print(a[1])
print(a['name'])
print(a['name']*2)
print(a['name']+' hi')
print(a.keys())
print(a.values())
|
d3e8b6498d84d24d9c6d6b01b6407e303d4d4531
|
[
"Python"
] | 19 |
Python
|
aniket-yadav/python_basics
|
81a1118819fcc5bd7f882c1157b854ee8b06874d
|
ae336bcb7622f5f29620d0bcd79ba097f00c1ac3
|
refs/heads/main
|
<file_sep>package br.gov.ac.sefaz.TesteXMLeXSD;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class LeituradeXML {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException{
DocumentBuilderFactory fabrica = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fabrica.newDocumentBuilder();
Document document = builder.parse("target/pessoa.xml");
NodeList formasDePagamento = document.getElementsByTagName("nome");
Element fdp= (Element) formasDePagamento.item(0);
String formaDePagamento = fdp.getTextContent();
System.out.println(formaDePagamento);
}
}<file_sep>package br.gov.ac.sefaz.TesteXMLeXSD;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Teste {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException{
DocumentBuilderFactory fabrica = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fabrica.newDocumentBuilder();
Document document = builder.parse("target/vendas.xml");
NodeList formasDePagamento = document.getElementsByTagName("formaDePagamento");
Element fdp= (Element) formasDePagamento.item(0);
String formaDePagamento = fdp.getTextContent();
System.out.println(formaDePagamento);
}
}
|
491ad47b3c7a769c3d1e03e50ac6b7f128f0f739
|
[
"Java"
] | 2 |
Java
|
thalyasb/FirstDay
|
b5f0d0a907c07a67f83a15f7a00c123874a6729b
|
d3b391f94ced5440779b82f369b6cc78d4a1fa79
|
refs/heads/master
|
<file_sep><?php
// printing some characteristics of a person
$student = [
'id' => 1,
'name' => 'Mohsen',
'family' => 'Hosseini',
'father' => 'Ali',
'grade' => 17.25,
'passed' => true,
];
$keys = array_keys($student);
$c = count($keys);
for($i = 0; $i < $c; $i++){
echo '<p>' . $keys[$i] . " : " . $student[$keys[$i]] . '</p>';
}
?>
<file_sep>CREATE TABLE `countries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`capital` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
INSERT INTO `countries` VALUES
(1,'Iran','Tehran'),
(2,'Russia','Moscow'),
(3,'Afghanistan','Kabul'),
(4,'Algeria','Algiers'),
(5,'Albania','Tirana');
<file_sep>Welcome to Learn-GitHub Project!
This Project is just a Test to Practice and Learn ' How to work with guthub? '
now, You are free to Clone This Project To your PC and change Everything you want,
then, You Can push it to github (You are able to practice and work with GitHub by yourself);
LET'S DO THIS!
|
9bfbfbe383dc6036a52d0fa2c8fe2950710d596f
|
[
"Markdown",
"SQL",
"PHP"
] | 3 |
PHP
|
moh-java4/Learn-GitHub
|
db69002d6183ba6d1d24251371eabda352de33f6
|
9a8d7de6d905a61dd62bb8e977958837c7604dcf
|
refs/heads/master
|
<file_sep># JS_Misc
## Description
JS_misc is a collection of small and independent javascript codes. Most of the codes are trivial and only exist for convenience.
## Documentation
Check doc/index.html
(Generated with: [JSDoc](https://github.com/jsdoc/jsdoc))
<file_sep>
/**
* Get the first Node based on an xPath
* (A shorthand version of document.evaluate(...) returning only the first match)
*
* @param {XPathExpression} xPath
* @param {Node} contextNode
* @returns {Node}
*/
function getElementByXpath(xPath) {
return getElementsByXpath(xPath)[0]
}
/**
* Get all Nodes based on an xPath
* (A shorthand version of document.evaluate(...) with an array as a result)
*
* @param {XPathExpression} xPath
* @param {Node} contextNode
* @returns {Array<Node>}
*/
function getElementsByXpath(xPath, contextNode=document) {
let xpathResult = document.evaluate(xPath, contextNode, null, XPathResult.ANY_TYPE, null)
let resultList = []
let result
while (result = xpathResult.iterateNext()) {
resultList.push(result)
}
return resultList
}
/**
*
* Creates an array with the same number of dimensions as the number of the parameters with the given amount of elements
*
* @param {...integer} size the sizes of the dimensions as separate arguments (at least one)
* @param {Function} init optionally this can be a function which should return the desired values of the element upon call. It might get the current element's position in the array as argument (depends on next parameter).
* @param {boolean} passPosition if true, the init function gets the current element's position in the array as parameter
*/
function createArray() {
let array;
let newArgs = Array.prototype.slice.call(arguments, 1);
if( ! Array.isArray(newArgs[newArgs.length-1]) ){
if(newArgs[newArgs.length-1] === true)
newArgs[newArgs.length-1] = [];
else if(newArgs[newArgs.length-1] !== false)
newArgs.push(false);
}
if(Number.isInteger(arguments[0])) {
array = new Array(arguments[0]);
let i = arguments[0];
if(newArgs[newArgs.length-1] !== false){
newArgs[newArgs.length-1] = newArgs[newArgs.length-1].slice();
newArgs[newArgs.length-1].push(0);
}
while(i--){
let pos = arguments[0]-1 - i;
if(newArgs[newArgs.length-1] !== false){
newArgs[newArgs.length-1] = newArgs[newArgs.length-1].slice();
newArgs[newArgs.length-1][ newArgs[newArgs.length-1].length-1 ] = pos;
}
array[pos] = createArray(...newArgs);
}
} else if(arguments.length == 2){
array = arguments[1] === false ? arguments[0]() : arguments[0](arguments[1]);
}
return array;
}
/**
*
* Simple function that returns the parameter
* Same as x => x
*
* @param {*} x
*/
function identityFn(x){
return x;
}
/**
*
* Delays an async code with the given amount of milliseconds
*
* @param {integer} milliseconds Length of the delay in milliseconds
*/
function waitForMilliseconds(milliseconds){
return new Promise(resolve =>{
setTimeout(() =>{
resolve();
}, milliseconds);
});
}
/**
* Wait until something potentially changing is at the right state by periodically checking it
* The returned Promise is resolved when the checking the state returns true
*
* @param {Function} stateFunc The function yielding the value to check, using the check parameter
* @param {integer} delay Delay in milliseconds between the checks
* @returns {Promise} Promise containing the last state value which resolved. The value is only useful if a non true, but truthy value is the state
*/
function waitForState(stateFunc, delay=1000) {
return new Promise(resolve => {
function checkState() {
let state = stateFunc()
if (state) {
resolve(state)
} else {
window.setTimeout(checkState, delay);
}
}
checkState();
});
}
/**
*
* Calls a given function after a precise number of "eventComplete()" call
*
*/
class CallFunctionOnMultipleEvents {
/**
*
* Creates a caller object
*
* @param {*} numberOfEvents
* @param {*} functionToCall
*/
constructor(numberOfEvents, functionToCall){
this.numberOfEvents = numberOfEvents;
this.functionToCall = functionToCall;
}
/**
*
* Function to call on every completed event
*
*/
eventComplete(){
this.numberOfEvents--;
if(this.numberOfEvents <= 0){
this.functionToCall();
}
}
}
/**
*
* Creates a table with the specified number of rows and columns
*
* @param {integer} xCellNum
* @param {integer} yCellNum
* @param {Object} options if contains addCellID = true, the cells will have and id whicj is their coordinates like [y,x]
*/
function createTable(rowNum, colNum, options = {}){
let table = document.createElement('table');
for(let y = 0; y < rowNum; y++){
let row = document.createElement('tr');
for(let x = 0; x < colNum; x++){
let cell = document.createElement('td');
if(options.addCellID)
cell.id = JSON.stringify({x:x, y:y});
if(options.toAssign){
Object.assign(cell, options.toAssign);
}
row.appendChild(cell);
}
table.appendChild(row);
}
return table;
}
/**
*
* Creates a radio input which can be switched off on click
*
* @param {Object} toAssign An object of properties to assign to the element (note that this assign is shallow)
*/
function createSwitchableRadioInput(toAssign = undefined){
let radioButton = document.createElement('input');
radioButton.addEventListener('mousedown', (event) => {
event.preventDefault();
event.target.checked = !event.target.checked;
});
radioButton.addEventListener('click', preventEvent);
if(toAssign != undefined)
Object.assign(radioButton, toAssign);
return radioButton;
}
/**
*
* Works like the "%" operator, but the result is always positive
*
* @param {integer} num The number
* @param {integer} mod The modulo
*/
function mathMod(num, mod){
return ((num % mod) + mod) % mod;
}
/**
*
* Returns if arg can be a proper number (not NaN) with parseFloat
*
* @param {*} arg
*/
function isNumber(arg){
return !isNaN(parseFloat(arg)) && !Array.isArray(arg);
}
/**
*
* Returns the "thing"'s Number value.
* In case it were NaN it will be 0 instead
*
* @param {*} thing
*/
function convertToNumber(thing){
return isNumber(thing) ? parseFloat(thing) : 0;
whole
}
/**
*
* Returns a random whole number with the given parameters
*
* @param {*} possResNum Number.MAX_SAFE_INTEGER by default. The number of possible result values. In case of wholeNum(3), the possible outcomes are 0,1,2. Shouldn't be higher then the default value
* @param {*} minVal 0 by default. The lowest possible value. In case of wholeNum(3, 2), the possible outcomes are 2,3,4.
*/
function wholeRand(possResNum = Number.MAX_SAFE_INTEGER, minVal = 0){
return Math.floor( (Math.random() * possResNum) + minVal );
}
/**
*
* Makes a node visible by setting it's inline display to ""
*
* @param {Node} node
*/
function nodeOn(node){
node.style.display = "";
}
/**
*
* Makes a node invisible by setting it's inline display to "none"
*
* @param {Node} node
*/
function nodeOff(node){
node.style.display = "none";
}
/**
*
* Sets a node's visibility by setting it's inline display between "" and "none"
*
* @param {Node} node
*/
function nodeOnOff(node){
node.style.display == "none" ? nodeOn(node) : nodeOff(node);
}
/**
*
* Wraps a given element into a newly created one
*
* @param {Element} toWrap Node to wrap
* @param {String} wrapperElement A createable element's name (eg.: div, span...)
* @returns {Element} The wrapper element
*/
function wrap(toWrap, wrapperElement) {
let wrapper = document.createElement(wrapperElement);
if(toWrap.parentNode)
toWrap.parentNode.insertBefore(wrapper, toWrap);
wrapper.appendChild(toWrap);
return wrapper;
}
/**
*
* A simple function to shorten callback when preventing default is the only intent
*
* @param {Event} event
*/
function preventEvent(event){
event.preventDefault();
}
/**
*
* A simple function to shorten callback when selecting the input's content is the only intent
*
* @param {Event} event
*/
function selectInputText(event){
event.target.setSelectionRange(0, event.target.value.length);
}
|
ebe3e01d743e90d8d371f16e58987960d9cdc763
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
Heck-R/JS_Misc
|
a4f8f8115ba7f81172d900d96d50c890849ac678
|
15bb5ffd7c3ef9963ec1af5dbfbcb43b5f7e9698
|
refs/heads/master
|
<file_sep># JavaProject
STOCK MANAGEMENT SYSTEM USING JAVA GUI/ SWING
<img src="images/login.png" width="80%" height="80%">
<img src="images/options.png" width="80%" height="80%">
<img src="images/edit.png" width="80%" height="80%">
<file_sep>package Project;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.UIManager;
import javax.swing.JScrollPane;
import javax.swing.ImageIcon;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseMotionAdapter;
public class Cars {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args)
{
Cars ca =new Cars();
}
/**
* Create the application.
*/
public Cars()
{
frame = new JFrame();
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 17));
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.setBounds(300, 60, 850, 650);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel_1 = new JLabel(" BORNVILLE");
lblNewLabel_1.setForeground(new Color(0, 0, 102));
lblNewLabel_1.setFont(new Font("Monotype Corsiva", Font.BOLD | Font.ITALIC, 50));
lblNewLabel_1.setBounds(305, 0, 529, 243);
frame.getContentPane().add(lblNewLabel_1);
JLabel lblBestAndLuxiourious = new JLabel("BEST AND LUXURIOUS CARS FROM ALL OVER THE WORLD");
lblBestAndLuxiourious.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblBestAndLuxiourious.setBounds(360, 160, 415, 14);
frame.getContentPane().add(lblBestAndLuxiourious);
JPanel panel_8 = new JPanel();
panel_8.setBounds(315, 0, 62, 283);
frame.getContentPane().add(panel_8);
panel_8.setLayout(null);
JLabel lblTextId = new JLabel("");
lblTextId.setForeground(new Color(0, 0, 102));
lblTextId.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblTextId.setBounds(28, 255, 31, 18);
panel_8.add(lblTextId);
JLabel lblTextname = new JLabel("");
lblTextname.setForeground(new Color(0, 102, 204));
lblTextname.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblTextname.setBounds(575, 280, 198, 27);
frame.getContentPane().add(lblTextname);
JLabel lblTextBrand = new JLabel("");
lblTextBrand.setForeground(new Color(0, 102, 204));
lblTextBrand.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblTextBrand.setBounds(575, 327, 198, 22);
frame.getContentPane().add(lblTextBrand);
JLabel lblTextSpeed = new JLabel("");
lblTextSpeed.setForeground(new Color(0, 102, 204));
lblTextSpeed.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblTextSpeed.setBounds(575, 376, 198, 22);
frame.getContentPane().add(lblTextSpeed);
JLabel lblTextAcc = new JLabel("");
lblTextAcc.setForeground(new Color(0, 102, 204));
lblTextAcc.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblTextAcc.setBounds(575, 421, 198, 22);
frame.getContentPane().add(lblTextAcc);
JLabel lblTextCylinder = new JLabel("");
lblTextCylinder.setForeground(new Color(0, 102, 204));
lblTextCylinder.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblTextCylinder.setBounds(575, 468, 198, 22);
frame.getContentPane().add(lblTextCylinder);
JLabel lblTextPrize = new JLabel("");
lblTextPrize.setForeground(new Color(0, 102, 204));
lblTextPrize.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblTextPrize.setBounds(575, 517, 198, 27);
frame.getContentPane().add(lblTextPrize);
JPanel panel = new JPanel();
panel.setBackground(new Color(0, 51, 102));
panel.setBounds(0, 0, 306, 611);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("CARS");
lblNewLabel.setBounds(43, 23, 141, 37);
lblNewLabel.setBackground(new Color(102, 0, 153));
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblNewLabel.setForeground(new Color(255, 255, 255));
panel.add(lblNewLabel);
JPanel panel_1 = new JPanel();
panel_1.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_1.setOpaque(true);
panel_1.setBackground(new Color(0, 102, 194));
}
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_1.setOpaque(true);
panel_1.setBackground(new Color(0, 102, 204));
lblNewLabel_1.setIcon(new ImageIcon(Cars.class.getResource("/Project/image/Aventador.jpg")));
try
{
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from scars where id='"+1+"'");
if(rs.next())
{
lblTextId.setText(rs.getString("id"));
lblTextname.setText(rs.getString("name"));
lblTextBrand.setText(rs.getString("brand"));
lblTextSpeed.setText(rs.getString("speed"));
lblTextAcc.setText(rs.getString("acceleration"));
lblTextCylinder.setText(rs.getString("cylinder"));
lblTextPrize.setText(rs.getString("price"));
}
else
JOptionPane.showMessageDialog(null, "Wrong ID Inserted....");
rs.close();
st.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void mouseExited(MouseEvent arg0)
{
panel_1.setOpaque(true);
panel_1.setBackground(new Color(0,51,102));
}
});
panel_1.setBounds(0, 80, 306, 59);
panel.add(panel_1);
panel_1.setOpaque(false);
panel_1.setLayout(null);
JLabel lblCarName1 = new JLabel("New label");
lblCarName1.setForeground(Color.WHITE);
lblCarName1.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblCarName1.setBounds(43, 11, 222, 37);
panel_1.add(lblCarName1);
JPanel panel_2 = new JPanel();
panel_2.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_2.setOpaque(true);
panel_2.setBackground(new Color(0, 102, 194));
}
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_2.setOpaque(true);
panel_2.setBackground(new Color(0, 102, 204));
lblNewLabel_1.setIcon(new ImageIcon(Cars.class.getResource("/Project/image/177.jpg")));
try
{
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from scars where id='"+2+"'");
if(rs.next())
{
lblTextId.setText(rs.getString("id"));
lblTextname.setText(rs.getString("name"));
lblTextBrand.setText(rs.getString("brand"));
lblTextSpeed.setText(rs.getString("speed"));
lblTextAcc.setText(rs.getString("acceleration"));
lblTextCylinder.setText(rs.getString("cylinder"));
lblTextPrize.setText(rs.getString("price"));
}
else
JOptionPane.showMessageDialog(null, "Wrong ID Inserted...");
rs.close();
st.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void mouseExited(MouseEvent arg0)
{
panel_2.setOpaque(true);
panel_2.setBackground(new Color(0,51,102));
}
});
panel_2.setBackground(new Color(0, 102, 204));
panel_2.setBounds(0, 139, 306, 59);
panel.add(panel_2);
panel_2.setOpaque(false);
panel_2.setLayout(null);
JLabel lblCarName2 = new JLabel("New label");
lblCarName2.setForeground(new Color(255, 255, 255));
lblCarName2.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblCarName2.setBounds(41, 11, 238, 37);
panel_2.add(lblCarName2);
JPanel panel_3 = new JPanel();
panel_3.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_3.setOpaque(true);
panel_3.setBackground(new Color(0, 102, 194));
}
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_3.setOpaque(true);
panel_3.setBackground(new Color(0, 102, 204));
lblNewLabel_1.setIcon(new ImageIcon(Cars.class.getResource("/Project/image/911.jpg")));
try
{
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from scars where id='"+3+"'");
if(rs.next())
{
lblTextId.setText(rs.getString("id"));
lblTextname.setText(rs.getString("name"));
lblTextBrand.setText(rs.getString("brand"));
lblTextSpeed.setText(rs.getString("speed"));
lblTextAcc.setText(rs.getString("acceleration"));
lblTextCylinder.setText(rs.getString("cylinder"));
lblTextPrize.setText(rs.getString("price"));
}
else
JOptionPane.showMessageDialog(null, "Wrong ID Inserted...");
rs.close();
st.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void mouseExited(MouseEvent arg0)
{
panel_3.setOpaque(true);
panel_3.setBackground(new Color(0,51,102));
}
});
panel_3.setBounds(0, 198, 306, 59);
panel.add(panel_3);
panel_3.setLayout(null);
panel_3.setOpaque(false);
JLabel lblCarName3 = new JLabel("New label");
lblCarName3.setForeground(new Color(255, 255, 255));
lblCarName3.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblCarName3.setBounds(43, 11, 232, 37);
panel_3.add(lblCarName3);
JPanel panel_4 = new JPanel();
panel_4.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_4.setOpaque(true);
panel_4.setBackground(new Color(0, 102, 194));
}
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_4.setOpaque(true);
panel_4.setBackground(new Color(0, 102, 204));
lblNewLabel_1.setIcon(new ImageIcon(Cars.class.getResource("/Project/image/R8.jpg")));
try
{
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from scars where id='"+4+"'");
if(rs.next())
{
lblTextId.setText(rs.getString("id"));
lblTextname.setText(rs.getString("name"));
lblTextBrand.setText(rs.getString("brand"));
lblTextSpeed.setText(rs.getString("speed"));
lblTextAcc.setText(rs.getString("acceleration"));
lblTextCylinder.setText(rs.getString("cylinder"));
lblTextPrize.setText(rs.getString("price"));
}
else
JOptionPane.showMessageDialog(null, "Wrong ID Inserted...");
rs.close();
st.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void mouseExited(MouseEvent arg0)
{
panel_4.setOpaque(true);
panel_4.setBackground(new Color(0,51,102));
}
});
panel_4.setBounds(0, 256, 306, 59);
panel.add(panel_4);
panel_4.setLayout(null);
panel_4.setOpaque(false);
JLabel lblCarName4 = new JLabel("New label");
lblCarName4.setForeground(new Color(255, 255, 255));
lblCarName4.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblCarName4.setBounds(43, 11, 239, 37);
panel_4.add(lblCarName4);
JPanel panel_5 = new JPanel();
panel_5.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_5.setOpaque(true);
panel_5.setBackground(new Color(0, 102, 194));
}
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_5.setOpaque(true);
panel_5.setBackground(new Color(0, 102, 204));
lblNewLabel_1.setIcon(new ImageIcon(Cars.class.getResource("/Project/image/f12 berlinetta.jpg")));
try
{
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from scars where id='"+5+"'");
if(rs.next())
{
lblTextId.setText(rs.getString("id"));
lblTextname.setText(rs.getString("name"));
lblTextBrand.setText(rs.getString("brand"));
lblTextSpeed.setText(rs.getString("speed"));
lblTextAcc.setText(rs.getString("acceleration"));
lblTextCylinder.setText(rs.getString("cylinder"));
lblTextPrize.setText(rs.getString("price"));
}
else
JOptionPane.showMessageDialog(null, "Wrong ID Inserted...");
rs.close();
st.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void mouseExited(MouseEvent arg0)
{
panel_5.setOpaque(true);
panel_5.setBackground(new Color(0,51,102));
}
});
panel_5.setBounds(0, 314, 306, 59);
panel.add(panel_5);
panel_5.setLayout(null);
panel_5.setOpaque(false);
JLabel lblCarName5 = new JLabel("New label");
lblCarName5.setForeground(new Color(255, 255, 255));
lblCarName5.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblCarName5.setBounds(43, 11, 230, 37);
panel_5.add(lblCarName5);
JPanel panel_6 = new JPanel();
panel_6.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_6.setOpaque(true);
panel_6.setBackground(new Color(0, 102, 194));
}
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_6.setOpaque(true);
panel_6.setBackground(new Color(0, 102, 204));
lblNewLabel_1.setIcon(null);
try
{
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from scars where id='"+6+"'");
if(rs.next())
{
lblTextId.setText(rs.getString("id"));
lblTextname.setText(rs.getString("name"));
lblTextBrand.setText(rs.getString("brand"));
lblTextSpeed.setText(rs.getString("speed"));
lblTextAcc.setText(rs.getString("acceleration"));
lblTextCylinder.setText(rs.getString("cylinder"));
lblTextPrize.setText(rs.getString("price"));
}
else
{
lblTextId.setText(null);
lblTextname.setText(null);
lblTextBrand.setText(null);
lblTextSpeed.setText(null);
lblTextAcc.setText(null);
lblTextCylinder.setText(null);
lblTextPrize.setText(null);
}
rs.close();
st.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void mouseExited(MouseEvent arg0)
{
panel_6.setOpaque(true);
panel_6.setBackground(new Color(0,51,102));
}
});
panel_6.setBounds(0, 373, 306, 59);
panel.add(panel_6);
panel_6.setOpaque(false);
panel_6.setLayout(null);
panel_6.setOpaque(false);
JLabel lblCarName6 = new JLabel("");
lblCarName6.setForeground(new Color(255, 255, 255));
lblCarName6.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblCarName6.setBounds(41, 11, 238, 37);
panel_6.add(lblCarName6);
JPanel panel_7 = new JPanel();
panel_7.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_7.setOpaque(true);
panel_7.setBackground(new Color(0, 102, 194));
}
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_7.setOpaque(true);
panel_7.setBackground(new Color(0, 102, 204));
lblNewLabel_1.setIcon(null);
try
{
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from scars where id='"+7+"'");
if(rs.next())
{
lblTextId.setText(rs.getString("id"));
lblTextname.setText(rs.getString("name"));
lblTextBrand.setText(rs.getString("brand"));
lblTextSpeed.setText(rs.getString("speed"));
lblTextAcc.setText(rs.getString("acceleration"));
lblTextCylinder.setText(rs.getString("cylinder"));
lblTextPrize.setText(rs.getString("price"));
}
else
{
lblTextId.setText(null);
lblTextname.setText(null);
lblTextBrand.setText(null);
lblTextSpeed.setText(null);
lblTextAcc.setText(null);
lblTextCylinder.setText(null);
lblTextPrize.setText(null);
}
rs.close();
st.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void mouseExited(MouseEvent arg0)
{
panel_7.setOpaque(true);
panel_7.setBackground(new Color(0,51,102));
}
});
panel_7.setBounds(0, 432, 306, 59);
panel.add(panel_7);
panel_7.setOpaque(false);
panel_7.setLayout(null);
panel_7.setOpaque(false);
JLabel lblCarName7 = new JLabel("");
lblCarName7.setForeground(new Color(255, 255, 255));
lblCarName7.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblCarName7.setBounds(41, 11, 238, 37);
panel_7.add(lblCarName7);
JLabel lbl_name = new JLabel("MODEL ");
lbl_name.setFont(new Font("Tahoma", Font.PLAIN, 13));
lbl_name.setBounds(428, 280, 114, 22);
frame.getContentPane().add(lbl_name);
JLabel lbl_brand = new JLabel("BRAND ");
lbl_brand.setFont(new Font("Tahoma", Font.PLAIN, 13));
lbl_brand.setBounds(428, 327, 114, 22);
frame.getContentPane().add(lbl_brand);
JLabel lbl_speed = new JLabel("SPEED");
lbl_speed.setFont(new Font("Tahoma", Font.PLAIN, 13));
lbl_speed.setBounds(428, 376, 114, 22);
frame.getContentPane().add(lbl_speed);
JLabel lbl_acc = new JLabel("ACCELERATION");
lbl_acc.setFont(new Font("Tahoma", Font.PLAIN, 13));
lbl_acc.setBounds(428, 421, 114, 22);
frame.getContentPane().add(lbl_acc);
JLabel lbl_cylinder = new JLabel("CYLINDERS");
lbl_cylinder.setFont(new Font("Tahoma", Font.PLAIN, 13));
lbl_cylinder.setBounds(428, 468, 114, 22);
frame.getContentPane().add(lbl_cylinder);
JLabel lbl_price = new JLabel("PRICE");
lbl_price.setFont(new Font("Tahoma", Font.PLAIN, 13));
lbl_price.setBounds(428, 517, 114, 27);
frame.getContentPane().add(lbl_price);
try
{
int i=0,j=0,k=0;
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet r1=st.executeQuery("select * from scars where id='"+1+"'");
if(r1.next())
{
lblCarName1.setText(r1.getString("name"));
}
else
lblCarName1.setText(null);
ResultSet r2=st.executeQuery("select * from scars where id='"+2+"'");
if(r2.next())
{
lblCarName2.setText(r2.getString("name"));
}
else
lblCarName2.setText(null);
ResultSet r3=st.executeQuery("select * from scars where id='"+3+"'");
if(r3.next())
{
i=1;
lblCarName3.setText(r3.getString("name"));
}
else
lblCarName3.setText(null);
ResultSet r4=st.executeQuery("select * from scars where id='"+4+"'");
if(r4.next())
{
lblCarName4.setText(r4.getString("name"));
}
else
lblCarName4.setText(null);
ResultSet r5=st.executeQuery("select * from scars where id='"+5+"'");
if(r5.next())
{
lblCarName5.setText(r5.getString("name"));
}
else
lblCarName5.setText(null);
ResultSet r6=st.executeQuery("select * from scars where id='"+6+"'");
if(r6.next())
{
lblCarName6.setText(r6.getString("name"));
}
else
lblCarName6.setText(null);
ResultSet r7=st.executeQuery("select * from scars where id='"+7+"'");
if(r7.next())
{
lblCarName7.setText(r7.getString("name"));
}
else
lblCarName7.setText(null);
r1.close();
r2.close();
r3.close();
r4.close();
r5.close();
r6.close();
r7.close();
st.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
frame.setVisible(true);
}
}
<file_sep>package Project;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
public class ElectronicsEdit {
private JFrame frame;
private JTextField TextSearch;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel lblNewLabel_2;
private JLabel lblNewLabel_3;
private JLabel lblNewLabel_4;
private JLabel lblNewLabel_5;
private JLabel lblNewLabel_6;
private JTextField textName;
private JTextField textBrand;
private JTextField textOS;
private JTextField textDisplay;
private JTextField textCamera;
private JTextField textPrice;
private JPanel panel_1;
private JLabel lblTextNotify;
private JPanel panel_2;
private JTextField textId;
/**
* Launch the application.
*/
public static void main(String[] args)
{
ElectronicsEdit ee= new ElectronicsEdit();
}
/**
* Create the application.
*/
public ElectronicsEdit()
{
frame = new JFrame();
frame.setBounds(300, 60, 750, 650);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 834, 50);
frame.getContentPane().add(panel);
panel.setLayout(null);
panel_2 = new JPanel();
panel_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
try
{
Connection con=DAO.getConnection();
//step 3: Create Statement object
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from selectronics where name='"+TextSearch.getText()+"' or id='"+TextSearch.getText()+"'");
if(rs.next())
{
textId.setText(rs.getString("id"));
textName.setText(rs.getString("name"));
textBrand .setText(rs.getString("brand"));
textOS.setText(rs.getString("os"));
textDisplay.setText(rs.getString("display"));
textCamera.setText(rs.getString("camera"));
textPrice.setText(rs.getString("price"));
}
else
lblTextNotify.setText("INVALID ID");
rs.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
lblTextNotify.setText("INVALID ID");
e.printStackTrace();
}
}
});
panel_2.setBackground(new Color(0, 102, 204));
panel_2.setBounds(681, 11, 33, 28);
panel.add(panel_2);
TextSearch = new JTextField();
TextSearch.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
TextSearch.setText("");
}
});
TextSearch.setForeground(Color.GRAY);
TextSearch.setText("Search by Id or Name");
TextSearch.setBounds(409, 11, 273, 28);
panel.add(TextSearch);
TextSearch.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(1.9f)));
TextSearch.setColumns(10);
JLabel lblElectronics = new JLabel("ELECTRONICS");
lblElectronics.setForeground(new Color(0, 0, 51));
lblElectronics.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblElectronics.setBounds(35, 11, 144, 28);
panel.add(lblElectronics);
lblNewLabel = new JLabel("ID");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblNewLabel.setBounds(152, 104, 133, 14);
frame.getContentPane().add(lblNewLabel);
lblNewLabel_1 = new JLabel("NAME");
lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblNewLabel_1.setBounds(152, 158, 133, 14);
frame.getContentPane().add(lblNewLabel_1);
lblNewLabel_2 = new JLabel("BRAND");
lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblNewLabel_2.setBounds(152, 215, 133, 14);
frame.getContentPane().add(lblNewLabel_2);
lblNewLabel_3 = new JLabel("OS");
lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblNewLabel_3.setBounds(152, 268, 133, 14);
frame.getContentPane().add(lblNewLabel_3);
lblNewLabel_4 = new JLabel("DISPLAY");
lblNewLabel_4.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblNewLabel_4.setBounds(152, 321, 133, 14);
frame.getContentPane().add(lblNewLabel_4);
lblNewLabel_5 = new JLabel("CAMERA");
lblNewLabel_5.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblNewLabel_5.setBounds(152, 378, 133, 14);
frame.getContentPane().add(lblNewLabel_5);
lblNewLabel_6 = new JLabel("PRICE");
lblNewLabel_6.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblNewLabel_6.setBounds(152, 434, 133, 14);
frame.getContentPane().add(lblNewLabel_6);
textName = new JTextField();
textName.setFont(new Font("Tahoma", Font.PLAIN, 13));
textName.setForeground(Color.DARK_GRAY);
textName.setBounds(306, 152, 280, 20);
frame.getContentPane().add(textName);
textName.setOpaque(false);
textName.setBorder(null);
textName.setColumns(10);
textBrand = new JTextField();
textBrand.setFont(new Font("Tahoma", Font.PLAIN, 13));
textBrand.setForeground(Color.DARK_GRAY);
textBrand.setBounds(306, 209, 280, 20);
frame.getContentPane().add(textBrand);
textBrand.setOpaque(false);
textBrand.setBorder(null);
textBrand.setColumns(10);
textOS = new JTextField();
textOS.setForeground(Color.DARK_GRAY);
textOS.setFont(new Font("Tahoma", Font.PLAIN, 13));
textOS.setBounds(306, 262, 280, 20);
frame.getContentPane().add(textOS);
textOS.setOpaque(false);
textOS.setBorder(null);
textOS.setColumns(10);
textDisplay = new JTextField();
textDisplay.setForeground(Color.DARK_GRAY);
textDisplay.setFont(new Font("Tahoma", Font.PLAIN, 13));
textDisplay.setBounds(306, 315, 280, 20);
frame.getContentPane().add(textDisplay);
textDisplay.setOpaque(false);
textDisplay.setBorder(null);
textDisplay.setColumns(10);
textCamera = new JTextField();
textCamera.setFont(new Font("Tahoma", Font.PLAIN, 13));
textCamera.setForeground(Color.DARK_GRAY);
textCamera.setBounds(306, 372, 280, 20);
frame.getContentPane().add(textCamera);
textCamera.setOpaque(false);
textCamera.setBorder(null);
textCamera.setColumns(10);
textPrice = new JTextField();
textPrice.setFont(new Font("Tahoma", Font.PLAIN, 13));
textPrice.setForeground(Color.DARK_GRAY);
textPrice.setBounds(306, 428, 280, 20);
frame.getContentPane().add(textPrice);
textPrice.setOpaque(false);
textPrice.setBorder(null);
textPrice.setColumns(10);
JSeparator separator = new JSeparator();
separator.setForeground(Color.LIGHT_GRAY);
separator.setBackground(Color.LIGHT_GRAY);
separator.setBounds(306, 116, 280, 2);
frame.getContentPane().add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setForeground(Color.LIGHT_GRAY);
separator_1.setBackground(Color.LIGHT_GRAY);
separator_1.setBounds(306, 170, 280, 2);
frame.getContentPane().add(separator_1);
JSeparator separator_2 = new JSeparator();
separator_2.setForeground(Color.LIGHT_GRAY);
separator_2.setBackground(Color.LIGHT_GRAY);
separator_2.setBounds(306, 227, 280, 2);
frame.getContentPane().add(separator_2);
JSeparator separator_3 = new JSeparator();
separator_3.setForeground(Color.LIGHT_GRAY);
separator_3.setBackground(Color.LIGHT_GRAY);
separator_3.setBounds(306, 280, 280, 2);
frame.getContentPane().add(separator_3);
JSeparator separator_4 = new JSeparator();
separator_4.setForeground(Color.LIGHT_GRAY);
separator_4.setBackground(Color.LIGHT_GRAY);
separator_4.setBounds(306, 333, 280, 2);
frame.getContentPane().add(separator_4);
JSeparator separator_5 = new JSeparator();
separator_5.setForeground(Color.LIGHT_GRAY);
separator_5.setBackground(Color.LIGHT_GRAY);
separator_5.setBounds(306, 390, 280, 2);
frame.getContentPane().add(separator_5);
JSeparator separator_6 = new JSeparator();
separator_6.setForeground(Color.LIGHT_GRAY);
separator_6.setBackground(Color.LIGHT_GRAY);
separator_6.setBounds(306, 446, 280, 2);
frame.getContentPane().add(separator_6);
panel_1 = new JPanel();
panel_1.setBackground(new Color(0, 102, 204));
panel_1.setForeground(new Color(255, 255, 255));
panel_1.setBounds(0, 567, 734, 44);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
lblTextNotify = new JLabel("");
lblTextNotify.setForeground(new Color(255, 255, 255));
lblTextNotify.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 13));
lblTextNotify.setBounds(328, 11, 224, 22);
panel_1.add(lblTextNotify);
JButton btnNewButton = new JButton("INSERT");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
try
{
int i=0;
Connection con=DAO.getConnection();
PreparedStatement pst=con.prepareStatement("insert into selectronics values(?,?,?,?,?,?,?)");
pst.setString(1, textId.getText());
pst.setString(2, textName.getText());
pst.setString(3, textBrand.getText());
pst.setString(4, textOS.getText());
pst.setString(5, textDisplay.getText());
pst.setString(6, textCamera.getText());
pst.setString(7, textPrice.getText());
i=pst.executeUpdate();
if(i!=0)
lblTextNotify.setText("INSERTED");
else
lblTextNotify.setText("NOT INSERTED");
pst.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
lblTextNotify.setText("NOT INSERTED");
e.printStackTrace();
}
}
});
btnNewButton.setBackground(new Color(0, 102, 204));
btnNewButton.setForeground(new Color(255, 255, 255));
btnNewButton.setBounds(152, 492, 119, 35);
frame.getContentPane().add(btnNewButton);
btnNewButton.setContentAreaFilled(true);
btnNewButton.setFocusPainted(false);
btnNewButton.setBorderPainted(false);
JButton btnNewButton_1 = new JButton("DELETE");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
try
{
int i=0;
Connection con=DAO.getConnection();
PreparedStatement pst=con.prepareStatement("delete from selectronics where id=?");
pst.setString(1, textId.getText());
i=pst.executeUpdate();
if(i!=0)
lblTextNotify.setText("DELETED");
else
lblTextNotify.setText("NOT DELETED");
pst.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
lblTextNotify.setText("NOT DELETED");
e.printStackTrace();
}
}
});
btnNewButton_1.setBackground(new Color(0, 102, 204));
btnNewButton_1.setForeground(new Color(255, 255, 255));
btnNewButton_1.setBounds(467, 492, 119, 35);
frame.getContentPane().add(btnNewButton_1);
btnNewButton_1.setContentAreaFilled(true);
btnNewButton_1.setFocusPainted(false);
btnNewButton_1.setBorderPainted(false);
JButton btnNewButton_2 = new JButton("UPDATE");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
try
{
int i=0;
Connection con=DAO.getConnection();
PreparedStatement pst=con.prepareStatement("update selectronics set name=?,brand=?,os=?,display=?,camera=?,price=? where id=?");
pst.setString(1, textName.getText());
pst.setString(2, textBrand.getText());
pst.setString(3, textOS.getText());
pst.setString(4, textDisplay.getText());
pst.setString(5, textCamera.getText());
pst.setString(6, textPrice.getText());
pst.setString(7, textId.getText());
i=pst.executeUpdate();
if(i!=0)
lblTextNotify.setText("UPDATED");
else
lblTextNotify.setText("NOT UPDATED");
pst.close();
con.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
lblTextNotify.setText("NOT UPDATED");
e.printStackTrace();
}
}
});
btnNewButton_2.setBackground(new Color(0, 102, 204));
btnNewButton_2.setForeground(new Color(255, 255, 255));
btnNewButton_2.setBounds(306, 492, 119, 35);
frame.getContentPane().add(btnNewButton_2);
btnNewButton_2.setContentAreaFilled(true);
btnNewButton_2.setFocusPainted(false);
btnNewButton_2.setBorderPainted(false);
textId = new JTextField();
textId.setOpaque(false);
textId.setForeground(Color.DARK_GRAY);
textId.setFont(new Font("Tahoma", Font.PLAIN, 13));
textId.setColumns(10);
textId.setBorder(null);
textId.setBounds(306, 98, 280, 20);
frame.getContentPane().add(textId);
frame.setVisible(true);
}
}
<file_sep>package Project;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Font;
public class AboutUs {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args)
{
AboutUs au=new AboutUs();
}
/**
* Create the application.
*/
public AboutUs()
{
frame = new JFrame();
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setForeground(Color.GRAY);
frame.setBounds(300, 60, 750, 650);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel_2 = new JLabel("<NAME>");
lblNewLabel_2.setFont(new Font("MV Boli", Font.BOLD, 15));
lblNewLabel_2.setForeground(new Color(0, 0, 102));
lblNewLabel_2.setBounds(36, 361, 186, 37);
frame.getContentPane().add(lblNewLabel_2);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(26, 216, 145, 140);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setIcon(new ImageIcon(AboutUs.class.getResource("/Project/image/suvam(3).jpg")));
lblNewLabel_1.setBounds(5, 5, 135, 130);
panel.add(lblNewLabel_1);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon(AboutUs.class.getResource("/Project/image/coffee-creativity-writer.jpg")));
lblNewLabel.setBounds(0, 0, 734, 356);
frame.getContentPane().add(lblNewLabel);
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 399, 734, 60);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_3 = new JLabel("I'm a Btech Student,crazy about tech and gadgets. #faujibrat,#wanderlust,#hangout,#bikerider");
lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNewLabel_3.setBounds(35, 11, 660, 37);
panel_1.add(lblNewLabel_3);
frame.setVisible(true);
}
}
<file_sep>package Project;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JTextPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Product {
private JFrame frame;
int i=0,j=0,k=0;
/**
* Launch the application.
*/
public static void main(String[] args)
{
Product pro = new Product();
}
/**
* Create the application.
*/
public Product()
{
frame = new JFrame();
JButton btnNewButton = new JButton("CARS");
JButton btnNewButton_1 = new JButton("CLOTHES");
JButton btnNewButton_2 = new JButton("ELECTRONICS");
JLabel lblCarPic = new JLabel("New label");
JLabel lblClothPic = new JLabel("New label");
JLabel lblElectronicsPic = new JLabel("New label");
JLabel lbloption1 = new JLabel("");
JLabel lbloption2 = new JLabel("");
JLabel lbloption3 = new JLabel("");
JPanel panel_4 = new JPanel();
JPanel panel_5 = new JPanel();
panel_4.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_4.setVisible(true);
}
});
panel_4.setBackground(new Color(0, 102, 204));
panel_4.setBounds(267, 0, 282, 611);
frame.getContentPane().add(panel_4);
panel_4.setLayout(null);
panel_4.setVisible(false);
frame.getContentPane().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_4.setVisible(false);
}
});
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.setBounds(300, 60, 850, 650);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_4.setVisible(false);
}
});
panel.setBackground(new Color(0, 51, 102));
panel.setBounds(0, 0, 268, 611);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("OPTIONS");
lblNewLabel.setBackground(new Color(102, 0, 153));
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblNewLabel.setForeground(new Color(255, 255, 255));
lblNewLabel.setBounds(39, 21, 141, 37);
panel.add(lblNewLabel);
panel_5.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
if(i==1)
{
lblCarPic.setVisible(true);
lblClothPic.setVisible(true);
lblElectronicsPic.setVisible(true);
btnNewButton.setVisible(true);
btnNewButton_1.setVisible(true);
btnNewButton_2.setVisible(true);
}
else if(i==2)
{
CarsEdit ee=new CarsEdit();
}
else if(i==3)
{
AboutUs au =new AboutUs();
}
}
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_5.setBackground(new Color(0, 85, 204));
panel_5.setOpaque(true);
}
@Override
public void mouseExited(MouseEvent arg0)
{
panel_5.setBackground(new Color(0, 102, 204));
panel_5.setOpaque(true);
}
});
panel_5.setBackground(new Color(0, 102, 204));
panel_5.setBounds(0, 76, 282, 50);
panel_4.add(panel_5);
panel_5.setLayout(null);
lbloption1.setFont(new Font("Tahoma", Font.PLAIN, 15));
lbloption1.setForeground(new Color(255, 255, 255));
lbloption1.setBounds(35, 11, 237, 28);
panel_5.add(lbloption1);
JPanel panel_6 = new JPanel();
panel_6.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
if(j==1)
{
frame.dispose();
}
else if(j==2)
{
ClothsEdit ce = new ClothsEdit();
}
}
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_6.setBackground(new Color(0, 85, 204));
panel_6.setOpaque(true);
}
@Override
public void mouseExited(MouseEvent arg0)
{
panel_6.setBackground(new Color(0, 102, 204));
panel_6.setOpaque(true);
}
});
panel_6.setBackground(new Color(0, 102, 204));
panel_6.setBounds(0, 126, 282, 50);
panel_4.add(panel_6);
panel_6.setLayout(null);
lbloption2.setForeground(new Color(255, 255, 255));
lbloption2.setFont(new Font("Tahoma", Font.PLAIN, 15));
lbloption2.setBounds(37, 11, 235, 28);
panel_6.add(lbloption2);
JPanel panel_7 = new JPanel();
panel_7.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
if(k==2)
{
ElectronicsEdit ee = new ElectronicsEdit();
}
}
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_7.setBackground(new Color(0, 85, 204));
panel_7.setOpaque(true);
}
@Override
public void mouseExited(MouseEvent arg0)
{
panel_7.setBackground(new Color(0, 102, 204));
panel_7.setOpaque(true);
}
});
panel_7.setBackground(new Color(0, 102, 204));
panel_7.setBounds(0, 176, 282, 50);
panel_4.add(panel_7);
panel_7.setLayout(null);
lbloption3.setForeground(new Color(255, 255, 255));
lbloption3.setBackground(new Color(255, 255, 255));
lbloption3.setFont(new Font("Tahoma", Font.PLAIN, 15));
lbloption3.setBounds(37, 11, 235, 28);
JPanel panel_1 = new JPanel();
panel_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_1.setBackground(new Color(0, 85, 204));
panel_1.setOpaque(true);
panel_4.setVisible(true);
lbloption1.setText("SHOW");
lbloption2.setText("EXIT");
lbloption3.setText(null);
i=1;
j=1;
k=1;
}
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_1.setBackground(new Color(0, 102, 204));
panel_1.setOpaque(true);
}
@Override
public void mouseExited(MouseEvent arg0)
{
panel_1.setBackground(new Color(0, 51,102));
panel_1.setOpaque(true);
}
});
panel_1.setBounds(0, 76, 268, 50);
panel.add(panel_1);
panel_1.setLayout(null);
panel_1.setOpaque(false);
JLabel lblPprducts = new JLabel("Products");
lblPprducts.setForeground(new Color(255, 255, 255));
lblPprducts.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblPprducts.setBounds(43, 11, 106, 28);
panel_1.add(lblPprducts);
JPanel panel_2 = new JPanel();
panel_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_2.setBackground(new Color(0, 85, 204));
panel_2.setOpaque(true);
panel_4.setVisible(true);
lbloption1.setText("CARS");
lbloption2.setText("CLOTHS");
lbloption3.setText("ELECTRONICS");
i=2;
j=2;
k=2;
}
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_2.setBackground(new Color(0, 102, 204));
panel_2.setOpaque(true);
}
@Override
public void mouseExited(MouseEvent arg0)
{
panel_2.setBackground(new Color(0, 51,102));
panel_2.setOpaque(true);
}
});
panel_2.setBackground(new Color(0, 102, 204));
panel_2.setBounds(0, 126, 268, 50);
panel.add(panel_2);
panel_2.setLayout(null);
panel_2.setOpaque(false);
JLabel lblNewLabel_1 = new JLabel("Edit products");
lblNewLabel_1.setForeground(new Color(255, 255, 255));
lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblNewLabel_1.setBounds(43, 11, 166, 28);
panel_2.add(lblNewLabel_1);
JPanel panel_3 = new JPanel();
panel_3.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
panel_3.setBackground(new Color(0, 85, 204));
panel_3.setOpaque(true);
panel_4.setVisible(true);
lbloption1.setText("ABOUT US");
lbloption2.setText(null);
lbloption3.setText(null);
i=3;
}
@Override
public void mouseEntered(MouseEvent arg0)
{
panel_3.setBackground(new Color(0, 102, 204));
panel_3.setOpaque(true);
}
@Override
public void mouseExited(MouseEvent arg0)
{
panel_3.setBackground(new Color(0, 51,102));
panel_3.setOpaque(true);
}
});
panel_3.setBackground(new Color(0, 102, 204));
panel_3.setBounds(0, 176, 268, 50);
panel.add(panel_3);
panel_3.setLayout(null);
panel_3.setOpaque(false);
JLabel lblNewLabel_2 = new JLabel("Help");
lblNewLabel_2.setForeground(new Color(255, 255, 255));
lblNewLabel_2.setBackground(new Color(255, 255, 255));
lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblNewLabel_2.setBounds(43, 11, 58, 28);
panel_3.add(lblNewLabel_2);
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
Cars ca = new Cars();
}
});
btnNewButton.setVisible(false);
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
Cloths clo = new Cloths();
}
});
btnNewButton_1.setVisible(false);
btnNewButton_1.setForeground(new Color(255, 255, 255));
btnNewButton_1.setBackground(new Color(0, 102, 204));
btnNewButton_1.setBounds(677, 347, 114, 30);
frame.getContentPane().add(btnNewButton_1);
btnNewButton_1.setContentAreaFilled(true);
btnNewButton_1.setFocusPainted(false);
btnNewButton_1.setBorderPainted(false);
btnNewButton_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0)
{
Electronics ele = new Electronics();
}
});
btnNewButton_2.setVisible(false);
btnNewButton_2.setForeground(new Color(255, 255, 255));
btnNewButton_2.setBackground(new Color(0, 102, 204));
btnNewButton_2.setBounds(677, 517, 114, 30);
frame.getContentPane().add(btnNewButton_2);
btnNewButton_2.setContentAreaFilled(true);
btnNewButton_2.setFocusPainted(false);
btnNewButton_2.setBorderPainted(false);
panel_7.add(lbloption3);
btnNewButton.setForeground(new Color(255, 255, 255));
btnNewButton.setBackground(new Color(0, 102, 204));
btnNewButton.setBounds(677, 172, 114, 30);
frame.getContentPane().add(btnNewButton);
btnNewButton.setContentAreaFilled(true);
btnNewButton.setFocusPainted(false);
btnNewButton.setBorderPainted(false);
lblCarPic.setIcon(new ImageIcon(Product.class.getResource("/Project/image/cars3.jpg")));
lblCarPic.setBounds(302, 38, 500, 170);
frame.getContentPane().add(lblCarPic);
lblCarPic.setVisible(false);
lblClothPic.setIcon(new ImageIcon(Product.class.getResource("/Project/image/clothe (2).jpg")));
lblClothPic.setBounds(302, 213, 500, 170);
frame.getContentPane().add(lblClothPic);
lblClothPic.setVisible(false);
lblElectronicsPic.setIcon(new ImageIcon(Product.class.getResource("/Project/image/elec (2).jpg")));
lblElectronicsPic.setBounds(302, 388, 500, 170);
frame.getContentPane().add(lblElectronicsPic);
JLabel lblBornville = new JLabel("BORNVILLE");
lblBornville.setFont(new Font("Monotype Corsiva", Font.BOLD, 50));
lblBornville.setForeground(new Color(0, 0, 102));
lblBornville.setBounds(357, 130, 344, 71);
frame.getContentPane().add(lblBornville);
JLabel lblNewLabel_3 = new JLabel(" BEST AND LUXURIOUS PRODUTS FROM ALL OVER THE WORLD");
lblNewLabel_3.setBounds(320, 226, 450, 28);
frame.getContentPane().add(lblNewLabel_3);
lblNewLabel_3.setForeground(new Color(0, 0, 51));
lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblElectronicsPic.setVisible(false);
frame.setVisible(true);
}
}
|
91ea2bd51777c3d9cdec3f4772e7d5a19cf5b2fb
|
[
"Markdown",
"Java"
] | 5 |
Markdown
|
angryboysuv/JavaProject
|
cb34c1eaaebf2e8a51109775ca586fcb0d042449
|
affea74e4bec5cd8af0f51900ca1de3d4e7f4365
|
refs/heads/master
|
<repo_name>singhutsav9697/customerhomework<file_sep>/CustomerHomework/mvcrest/src/main/java/com/capg/dao/ICustomerDao.java
package com.capg.dao;
import com.capg.entities.Customer;
import java.util.List;
public interface ICustomerDao {
Customer findById(int id);
Customer save(Customer user);
List<Customer> fetchAll();
boolean remove(int id);
}
<file_sep>/CustomerHomework/mvcjpa/src/main/java/com/capg/dao/ICustomerDao.java
package com.capg.dao;
import com.capg.entities.Customer;
import java.util.List;
public interface ICustomerDao {
Customer findById(int id);
Customer save(Customer user);
Customer updateCustomer(Customer customer);
}
<file_sep>/CustomerHomework/mvcrest/src/main/java/com/capg/controller/CustomerRestController.java
package com.capg.controller;
import com.capg.dto.CustomerDto;
import com.capg.entities.Customer;
import com.capg.service.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class CustomerRestController {
@Autowired
private ICustomerService service;
@GetMapping("/customers/find/{id}")
public ResponseEntity<Customer> getCustomer(@PathVariable("id") int id) {
Customer customer = service.findById(id);
if(customer==null){
ResponseEntity<Customer> response= new ResponseEntity<>(HttpStatus.NOT_FOUND);
return response;
}
ResponseEntity<Customer> response = new ResponseEntity<>(customer, HttpStatus.OK);
return response;
}
@PostMapping("/customers/add")
public ResponseEntity<Customer> addCustomer(@RequestBody CustomerDto dto) {
Customer customer = convert(dto);
customer = service.save(customer);
ResponseEntity<Customer> response = new ResponseEntity<>(customer, HttpStatus.OK);
return response;
}
Customer convert(CustomerDto dto) {
Customer customer = new Customer();
customer.setName(dto.getName());
return customer;
}
@GetMapping("/customers")
public ResponseEntity<List<Customer>> fetchAll() {
List<Customer> customers = service.fetchAll();
ResponseEntity<List<Customer>> response = new ResponseEntity<>(customers, HttpStatus.OK);
return response;
}
@DeleteMapping("/customers/delete/{id}")
public ResponseEntity<Boolean>deleteCustomer(@PathVariable int id){
boolean result= service.remove(id);
ResponseEntity<Boolean>response=new ResponseEntity<>(result, HttpStatus.OK);
return response;
}
@PutMapping("/customers/update/{id}")
public ResponseEntity<Customer>updateCustomer(@RequestBody CustomerDto dto ,@PathVariable("id")int id){
Customer customer=convert(dto);
customer.setId(id);
customer=service.save(customer);
ResponseEntity<Customer>response=new ResponseEntity<>(customer,HttpStatus.OK);
return response;
}
}
<file_sep>/CustomerHomework/mvcjpa/src/main/java/com/capg/service/ICustomerService.java
package com.capg.service;
import com.capg.entities.Customer;
import java.util.List;
public interface ICustomerService {
Customer findById(int id);
Customer save(Customer user);
Customer updateCustomer(Customer customer);
}
<file_sep>/CustomerHomework/mvcjpa/src/main/java/com/capg/dao/CustomerDaoImpl.java
package com.capg.dao;
import com.capg.entities.Customer;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
@Repository
public class CustomerDaoImpl implements ICustomerDao {
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Customer findById(int id) {
Customer user = entityManager.find(Customer.class, id);
return user;
}
@Override
public Customer updateCustomer(Customer customer) {
customer = entityManager.merge(customer);
return customer;
}
@Override
public Customer save(Customer customer) {
customer = getEntityManager().merge(customer);
return customer;
}
}
|
317853e8a3d06e0007a6bc814f29902980a6fe43
|
[
"Java"
] | 5 |
Java
|
singhutsav9697/customerhomework
|
519c1d1c6900a085537864cb56ca65c08b1a1dbf
|
3a1f97eb78ea0cf4901e21614badc0c2f5b467ba
|
refs/heads/master
|
<repo_name>Hinsteny/WorkerMonitor<file_sep>/worker_monitor-worker/src/main/java/com/hisoka/worker_monitor/worker/quartz/CountOrderJob.java
package com.hisoka.worker_monitor.worker.quartz;
import org.hisoka.core.quartz.job.BaseJob;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
/**
*
* @author zhihongp
*
*/
@Component("countOrderJob")
public class CountOrderJob extends BaseJob {
@Override
public Object executeJob(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("CountOrderJob, executeJob");
JobDataMap jdm = ctx.getJobDetail().getJobDataMap();
System.out.println("CountOrderJob, JobDataMap=" + JSONObject.toJSONString(jdm, true));
if (jdm.containsKey("path")) {
String shpath = jdm.getString("path"); // 程序路径
System.out.println("CountOrderJob, shpath=" + shpath);
String command = /* "/bin/sh " + */ "\"" + shpath + "\"";
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("CountOrderJob, no key named path");
}
return null;
}
}
<file_sep>/worker_monitor-web/src/main/java/com/hisoka/worker_monitor/web/util/LoginUtil.java
package com.hisoka.worker_monitor.web.util;
import com.hisoka.worker_monitor.web.config.LoginConfig;
import com.hisoka.worker_monitor.web.config.LoginTicket;
import org.hisoka.common.util.cookie.CookieUtil;
import org.hisoka.common.util.http.URLUtil;
import org.hisoka.common.util.secret.MD5Util;
import org.hisoka.common.util.session.HttpSessionProxy;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Hinsteny
* @Describtion
* @date 2016/11/8
* @copyright: 2016 All rights reserved.
*/
public class LoginUtil {
public static final String USERNAMEKEY = "userName";
public static final String PASSWORDKEY = "<PASSWORD>";
public static final String cookiePath = "/";
public static LoginTicket getLoginTicketByCookie(HttpServletRequest request, LoginConfig loginConfig){
LoginTicket ticket = new LoginTicket();
String username = request.getParameter(USERNAMEKEY);
String password = request.getParameter(PASSWORDKEY);
ticket.setUserName(username);
ticket.setPassword(<PASSWORD>);
Cookie cookieV = CookieUtil.getCookie(request, loginConfig.loginCookieName);
Cookie cookieAuth = CookieUtil.getCookie(request, loginConfig.loginAuthKey);
ticket.setCookieV(cookieV);
ticket.setAuthKey(cookieAuth);
return ticket;
}
public static void doLogin(HttpServletRequest request, HttpServletResponse response, LoginTicket ticket, HttpSessionProxy session, LoginConfig loginConfig, String sessionName){
session.setAttribute(USERNAMEKEY, ticket.getUserName());
session.setAttribute(PASSWORDKEY, ticket.getPassword());
String domain = URLUtil.getServerRootDomain(request);
CookieUtil.writeCookie(response, CookieUtil.createCookie(sessionName, session.getId(), domain, cookiePath, false, false, loginConfig.getMaxKeepTime()));
CookieUtil.writeCookie(response, CookieUtil.createCookie(loginConfig.loginCookieName, ticket.getUserName(), domain, cookiePath, false, false, loginConfig.getMaxKeepTime()));
String str = (String) session.getAttribute(LoginUtil.USERNAMEKEY) + session.getAttribute(LoginUtil.PASSWORDKEY);
CookieUtil.writeCookie(response, CookieUtil.createCookie(loginConfig.loginAuthKey, MD5Util.encrypt(str), domain, cookiePath, false, false, loginConfig.getMaxKeepTime()));
}
public static void doLogout(HttpServletRequest request, HttpServletResponse response, LoginTicket ticket, HttpSessionProxy session){
session.removeAttribute(USERNAMEKEY);
session.removeAttribute(PASSWORDKEY);
String domain = URLUtil.getServerRootDomain(request);
CookieUtil.removeCookie(response, ticket.getCookieV(), domain, cookiePath);
CookieUtil.removeCookie(response, ticket.getAuthKey(), domain, cookiePath);
}
}
<file_sep>/worker_monitor-web/src/test/java/com/hisoka/worker_monitor/web/test/compent/RedisTest.java
//package com.sztx.worker_monitor.web.test.compent;
//
//import org.junit.After;
//import org.junit.Before;
//import org.junit.Test;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.connection.RedisConnection;
//import org.springframework.data.redis.core.RedisCallback;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.parser.Feature;
//import BaseTest;
//import com.sztx.se.dataaccess.redis.source.DynamicRedisSource;
//
//public class RedisTest extends BaseTest {
//
// @Autowired
// private DynamicRedisSource redisTemplate;
//
// @Before
// public void setUp() throws Exception {
//
// }
//
// @After
// public void tearDown() throws Exception {
//
// }
//
//// @Test
//// public void testRedis() {
//// boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
//// @Override
//// public Boolean doInRedis(RedisConnection connection) {
//// String key = "TEST_REDIS";
//// String vlaue = "test";
//// byte[] bytes = redisTemplate.getStringSerializer().serialize(key);
//// connection.set(bytes, redisTemplate.getStringSerializer().serialize(vlaue));
//// connection.expire(bytes, 1000);
//// return true;
//// }
//// });
////
//// Assert.assertTrue(result);
//// }
//
// @Test
// public void testRedisA() {
// final String key = "TEST_REDIS";
// redisTemplate.execute(key, new RedisCallback<Integer>() {
// @Override
// public Integer doInRedis(RedisConnection connection) {
// byte[] bytes = redisTemplate.getStringSerializer().serialize(key);
// byte[] rBytes = connection.get(bytes);
// Integer a = deserialize(Integer.class, rBytes);
//// connection.set(bytes, redisTemplate.getStringSerializer().serialize(vlaue));
//// connection.expire(bytes, 1000);
// return a;
// }
// });
// }
//
// @SuppressWarnings("unchecked")
// public <T> T deserialize(Class<T> type, byte[] bytes) {
// if (type == String.class) {
// return (T) redisTemplate.getStringSerializer().deserialize(bytes);
// } else {
// return JSON.parseObject(bytes, type, Feature.SortFeidFastMatch);
// }
// }
//}
<file_sep>/worker_monitor-web/src/test/resources/logback_unit.properties
logback.file.path=D:\\log\\worker_monitor
logback.sql.level=DEBUG
logback.slow.level=INFO
logback.mq.level=ERROR
logback.quartz.level=ERROR
logback.memcache.level=ERROR
logback.root.level=DEBUG
logback.appender.name=all_debug<file_sep>/worker_monitor-web/src/test/java/com/hisoka/worker_monitor/web/test/compent/MysqlTest.java
//package com.hisoka.worker_monitor.web.test.compent;
//
//import java.sql.SQLException;
//
//import com.hisoka.worker_monitor.web.test.BaseTest;
//import org.junit.After;
//import org.junit.Assert;
//import org.junit.Before;
//import org.junit.Test;
//import org.springframework.beans.factory.annotation.Autowired;
//
//import com.hisoka.worker_monitor.dataaccess.dao.mysql.UserMysqlDAO;
//import com.hisoka.worker_monitor.dataaccess.domain.User;
//import com.sztx.se.dataaccess.mysql.source.DynamicDataSource;
//
//public class MysqlTest extends BaseTest {
//// @Autowired
//// private DynamicDataSource dynamicDataSource;
//
// @Autowired
// private UserMysqlDAO umd;
//
// @Before
// public void setUp() throws Exception {
//
// }
//
// @After
// public void tearDown() throws Exception {
//
// }
//
//// @Test
//// public void testMysql() throws SQLException {
//// Connection connection = dynamicDataSource.getConnection();
//// boolean flag = connection.isValid(5000);
//// Assert.assertTrue(flag);
////
////
//// }
//
// @Test
// public void testMysql() throws SQLException {
// User ret =umd.findByUsername("wm");
// Assert.assertEquals(ret.getNick(), "wangmin");
// }
//}
<file_sep>/worker_monitor-core/src/main/java/com/hisoka/worker_monitor/core/service/UserService.java
package com.hisoka.worker_monitor.core.service;
import java.util.Date;
import com.hisoka.worker_monitor.dataaccess.domain.User;
import org.hisoka.core.service.BaseService;
public interface UserService extends BaseService {
User findByUsername(String username);
Integer addUser(String username, String password, String nick, Integer sex, Integer age, Date birthday, String address, String tel, String email,
String md5Key);
}
<file_sep>/worker_monitor-dataaccess/src/main/java/com/hisoka/worker_monitor/dataaccess/domain/User.java
package com.hisoka.worker_monitor.dataaccess.domain;
import java.util.Date;
public class User {
/**
* 系统
*/
public static final String SYS_USER = "SYS";
public static final String DEFAULT_PASSWORD = "<PASSWORD>";
public static final Integer STATUS_NORMAL = 1;
/**
*
*/
private static final long serialVersionUID = -9099613469600917361L;
private Integer id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 昵称
*/
private String nick;
/**
* 性别
*/
private Integer sex;
/**
* 年龄
*/
private Integer age;
/**
* 生日
*/
private Date birthday;
/**
* 地址
*/
private String address;
/**
* 电话
*/
private String tel;
/**
* 邮箱
*/
private String email;
/**
* 状态
*/
private Integer status;
/**
* 最后登陆时间
*/
private Date lastLoginTime;
/**
* 最后登陆ip
*/
private String lastLoginIp;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public String getLastLoginIp() {
return lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + <PASSWORD> + ", nick=" + nick + ", sex=" + sex + ", age=" + age + ", birthday="
+ birthday + ", address=" + address + ", tel=" + tel + ", email=" + email + ", status=" + status + ", lastLoginTime=" + lastLoginTime
+ ", lastLoginIp=" + lastLoginIp + "]";
}
}
<file_sep>/worker_monitor-web/src/main/resources/db_quartz.sql
--
-- PostgreSQL database dump
--
-- Dumped from database version 9.5.2
-- Dumped by pg_dump version 9.5.2
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: QRTZ_BLOB_TRIGGERS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_BLOB_TRIGGERS" (
"SCHED_NAME" character varying(120) NOT NULL,
"TRIGGER_NAME" character varying(200) NOT NULL,
"TRIGGER_GROUP" character varying(200) NOT NULL,
"BLOB_DATA" bytea
);
ALTER TABLE "QRTZ_BLOB_TRIGGERS" OWNER TO quartz_user;
--
-- Name: QRTZ_CALENDARS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_CALENDARS" (
"SCHED_NAME" character varying(120) NOT NULL,
"CALENDAR_NAME" character varying(200) NOT NULL,
"CALENDAR" bytea NOT NULL
);
ALTER TABLE "QRTZ_CALENDARS" OWNER TO quartz_user;
--
-- Name: QRTZ_CRON_TRIGGERS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_CRON_TRIGGERS" (
"SCHED_NAME" character varying(120) NOT NULL,
"TRIGGER_NAME" character varying(200) NOT NULL,
"TRIGGER_GROUP" character varying(200) NOT NULL,
"CRON_EXPRESSION" character varying(120) NOT NULL,
"TIME_ZONE_ID" character varying(80)
);
ALTER TABLE "QRTZ_CRON_TRIGGERS" OWNER TO quartz_user;
--
-- Name: QRTZ_FIRED_TRIGGERS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_FIRED_TRIGGERS" (
"SCHED_NAME" character varying(120) NOT NULL,
"ENTRY_ID" character varying(95) NOT NULL,
"TRIGGER_NAME" character varying(200) NOT NULL,
"TRIGGER_GROUP" character varying(200) NOT NULL,
"INSTANCE_NAME" character varying(200) NOT NULL,
"FIRED_TIME" bigint NOT NULL,
"SCHED_TIME" bigint NOT NULL,
"PRIORITY" integer NOT NULL,
"STATE" character varying(16) NOT NULL,
"JOB_NAME" character varying(200),
"JOB_GROUP" character varying(200),
"IS_NONCONCURRENT" character varying(1),
"REQUESTS_RECOVERY" character varying(1)
);
ALTER TABLE "QRTZ_FIRED_TRIGGERS" OWNER TO quartz_user;
--
-- Name: QRTZ_JOB_DETAILS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_JOB_DETAILS" (
"SCHED_NAME" character varying(120) NOT NULL,
"JOB_NAME" character varying(200) NOT NULL,
"JOB_GROUP" character varying(200) NOT NULL,
"DESCRIPTION" character varying(250),
"JOB_CLASS_NAME" character varying(250) NOT NULL,
"IS_DURABLE" character varying(1) NOT NULL,
"IS_NONCONCURRENT" character varying(1) NOT NULL,
"IS_UPDATE_DATA" character varying(1) NOT NULL,
"REQUESTS_RECOVERY" character varying(1) NOT NULL,
"JOB_DATA" bytea
);
ALTER TABLE "QRTZ_JOB_DETAILS" OWNER TO quartz_user;
--
-- Name: QRTZ_LOCKS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_LOCKS" (
"SCHED_NAME" character varying(120) NOT NULL,
"LOCK_NAME" character varying(40) NOT NULL
);
ALTER TABLE "QRTZ_LOCKS" OWNER TO quartz_user;
--
-- Name: QRTZ_PAUSED_TRIGGER_GRPS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_PAUSED_TRIGGER_GRPS" (
"SCHED_NAME" character varying(120) NOT NULL,
"TRIGGER_GROUP" character varying(200) NOT NULL
);
ALTER TABLE "QRTZ_PAUSED_TRIGGER_GRPS" OWNER TO quartz_user;
--
-- Name: QRTZ_SCHEDULER_STATE; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_SCHEDULER_STATE" (
"SCHED_NAME" character varying(120) NOT NULL,
"INSTANCE_NAME" character varying(200) NOT NULL,
"LAST_CHECKIN_TIME" bigint NOT NULL,
"CHECKIN_INTERVAL" bigint NOT NULL
);
ALTER TABLE "QRTZ_SCHEDULER_STATE" OWNER TO quartz_user;
--
-- Name: QRTZ_SIMPLE_TRIGGERS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_SIMPLE_TRIGGERS" (
"SCHED_NAME" character varying(120) NOT NULL,
"TRIGGER_NAME" character varying(200) NOT NULL,
"TRIGGER_GROUP" character varying(200) NOT NULL,
"REPEAT_COUNT" bigint NOT NULL,
"REPEAT_INTERVAL" bigint NOT NULL,
"TIMES_TRIGGERED" bigint NOT NULL
);
ALTER TABLE "QRTZ_SIMPLE_TRIGGERS" OWNER TO quartz_user;
--
-- Name: QRTZ_SIMPROP_TRIGGERS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_SIMPROP_TRIGGERS" (
"SCHED_NAME" character varying(120) NOT NULL,
"TRIGGER_NAME" character varying(200) NOT NULL,
"TRIGGER_GROUP" character varying(200) NOT NULL,
"STR_PROP_1" character varying(512),
"STR_PROP_2" character varying(512),
"STR_PROP_3" character varying(512),
"INT_PROP_1" integer,
"INT_PROP_2" integer,
"LONG_PROP_1" bigint,
"LONG_PROP_2" bigint,
"DEC_PROP_1" numeric(13,4),
"DEC_PROP_2" numeric(13,4),
"BOOL_PROP_1" character varying(1),
"BOOL_PROP_2" character varying(1)
);
ALTER TABLE "QRTZ_SIMPROP_TRIGGERS" OWNER TO quartz_user;
--
-- Name: QRTZ_TRIGGERS; Type: TABLE; Schema: public; Owner: quartz_user
--
CREATE TABLE "QRTZ_TRIGGERS" (
"SCHED_NAME" character varying(120) NOT NULL,
"TRIGGER_NAME" character varying(200) NOT NULL,
"TRIGGER_GROUP" character varying(200) NOT NULL,
"JOB_NAME" character varying(200) NOT NULL,
"JOB_GROUP" character varying(200) NOT NULL,
"DESCRIPTION" character varying(250),
"NEXT_FIRE_TIME" bigint,
"PREV_FIRE_TIME" bigint,
"PRIORITY" integer,
"TRIGGER_STATE" character varying(16) NOT NULL,
"TRIGGER_TYPE" character varying(8) NOT NULL,
"START_TIME" bigint NOT NULL,
"END_TIME" bigint,
"CALENDAR_NAME" character varying(200),
"MISFIRE_INSTR" smallint,
"JOB_DATA" bytea
);
ALTER TABLE "QRTZ_TRIGGERS" OWNER TO quartz_user;
--
-- Name: QRTZ_BLOB_TRIGGERS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_BLOB_TRIGGERS"
ADD CONSTRAINT "QRTZ_BLOB_TRIGGERS_pkey" PRIMARY KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_CALENDARS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_CALENDARS"
ADD CONSTRAINT "QRTZ_CALENDARS_pkey" PRIMARY KEY ("SCHED_NAME", "CALENDAR_NAME");
--
-- Name: QRTZ_CRON_TRIGGERS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_CRON_TRIGGERS"
ADD CONSTRAINT "QRTZ_CRON_TRIGGERS_pkey" PRIMARY KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_FIRED_TRIGGERS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_FIRED_TRIGGERS"
ADD CONSTRAINT "QRTZ_FIRED_TRIGGERS_pkey" PRIMARY KEY ("SCHED_NAME", "ENTRY_ID");
--
-- Name: QRTZ_JOB_DETAILS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_JOB_DETAILS"
ADD CONSTRAINT "QRTZ_JOB_DETAILS_pkey" PRIMARY KEY ("SCHED_NAME", "JOB_NAME", "JOB_GROUP");
--
-- Name: QRTZ_LOCKS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_LOCKS"
ADD CONSTRAINT "QRTZ_LOCKS_pkey" PRIMARY KEY ("SCHED_NAME", "LOCK_NAME");
--
-- Name: QRTZ_PAUSED_TRIGGER_GRPS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_PAUSED_TRIGGER_GRPS"
ADD CONSTRAINT "QRTZ_PAUSED_TRIGGER_GRPS_pkey" PRIMARY KEY ("SCHED_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_SCHEDULER_STATE_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_SCHEDULER_STATE"
ADD CONSTRAINT "QRTZ_SCHEDULER_STATE_pkey" PRIMARY KEY ("SCHED_NAME", "INSTANCE_NAME");
--
-- Name: QRTZ_SIMPLE_TRIGGERS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_SIMPLE_TRIGGERS"
ADD CONSTRAINT "QRTZ_SIMPLE_TRIGGERS_pkey" PRIMARY KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_SIMPROP_TRIGGERS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_SIMPROP_TRIGGERS"
ADD CONSTRAINT "QRTZ_SIMPROP_TRIGGERS_pkey" PRIMARY KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_TRIGGERS_pkey; Type: CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_TRIGGERS"
ADD CONSTRAINT "QRTZ_TRIGGERS_pkey" PRIMARY KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_BLOB_TRIGGERS_SCHED_NAME; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_BLOB_TRIGGERS_SCHED_NAME" ON "QRTZ_BLOB_TRIGGERS" USING btree ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_INST_JOB_REQ_RCVRY; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_INST_JOB_REQ_RCVRY" ON "QRTZ_FIRED_TRIGGERS" USING btree ("SCHED_NAME", "INSTANCE_NAME", "REQUESTS_RECOVERY");
--
-- Name: QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_JG; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_JG" ON "QRTZ_FIRED_TRIGGERS" USING btree ("SCHED_NAME", "JOB_GROUP");
--
-- Name: QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_J_G; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_J_G" ON "QRTZ_FIRED_TRIGGERS" USING btree ("SCHED_NAME", "JOB_NAME", "JOB_GROUP");
--
-- Name: QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_TG; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_TG" ON "QRTZ_FIRED_TRIGGERS" USING btree ("SCHED_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_TRIG_INST_NAME; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_TRIG_INST_NAME" ON "QRTZ_FIRED_TRIGGERS" USING btree ("SCHED_NAME", "INSTANCE_NAME");
--
-- Name: QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_T_G; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_FIRED_TRIGGERS_IDX_QRTZ_FT_T_G" ON "QRTZ_FIRED_TRIGGERS" USING btree ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_JOB_DETAILS_IDX_QRTZ_J_GRP; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_JOB_DETAILS_IDX_QRTZ_J_GRP" ON "QRTZ_JOB_DETAILS" USING btree ("SCHED_NAME", "JOB_GROUP");
--
-- Name: QRTZ_JOB_DETAILS_IDX_QRTZ_J_REQ_RECOVERY; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_JOB_DETAILS_IDX_QRTZ_J_REQ_RECOVERY" ON "QRTZ_JOB_DETAILS" USING btree ("SCHED_NAME", "REQUESTS_RECOVERY");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_C; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_C" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "CALENDAR_NAME");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_G; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_G" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "TRIGGER_GROUP");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_J; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_J" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "JOB_NAME", "JOB_GROUP");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_JG; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_JG" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "JOB_GROUP");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_NEXT_FIRE_TIME; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_NEXT_FIRE_TIME" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "NEXT_FIRE_TIME");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_NFT_MISFIRE; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_NFT_MISFIRE" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "MISFIRE_INSTR", "NEXT_FIRE_TIME");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_NFT_ST; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_NFT_ST" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "TRIGGER_STATE", "NEXT_FIRE_TIME");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_NFT_ST_MISFIRE; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_NFT_ST_MISFIRE" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "MISFIRE_INSTR", "NEXT_FIRE_TIME", "TRIGGER_STATE");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_NFT_ST_MISFIRE_GRP; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_NFT_ST_MISFIRE_GRP" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "MISFIRE_INSTR", "NEXT_FIRE_TIME", "TRIGGER_GROUP", "TRIGGER_STATE");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_N_G_STATE; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_N_G_STATE" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "TRIGGER_GROUP", "TRIGGER_STATE");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_N_STATE; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_N_STATE" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP", "TRIGGER_STATE");
--
-- Name: QRTZ_TRIGGERS_IDX_QRTZ_T_STATE; Type: INDEX; Schema: public; Owner: quartz_user
--
CREATE INDEX "QRTZ_TRIGGERS_IDX_QRTZ_T_STATE" ON "QRTZ_TRIGGERS" USING btree ("SCHED_NAME", "TRIGGER_STATE");
--
-- Name: QRTZ_BLOB_TRIGGERS_IBFK_1; Type: FK CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_BLOB_TRIGGERS"
ADD CONSTRAINT "QRTZ_BLOB_TRIGGERS_IBFK_1" FOREIGN KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP") REFERENCES "QRTZ_TRIGGERS"("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP") ON UPDATE RESTRICT ON DELETE RESTRICT;
--
-- Name: QRTZ_CRON_TRIGGERS_IBFK_1; Type: FK CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_CRON_TRIGGERS"
ADD CONSTRAINT "QRTZ_CRON_TRIGGERS_IBFK_1" FOREIGN KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP") REFERENCES "QRTZ_TRIGGERS"("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP") ON UPDATE RESTRICT ON DELETE RESTRICT;
--
-- Name: QRTZ_SIMPLE_TRIGGERS_IBFK_1; Type: FK CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_SIMPLE_TRIGGERS"
ADD CONSTRAINT "QRTZ_SIMPLE_TRIGGERS_IBFK_1" FOREIGN KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP") REFERENCES "QRTZ_TRIGGERS"("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP") ON UPDATE RESTRICT ON DELETE RESTRICT;
--
-- Name: QRTZ_SIMPROP_TRIGGERS_IBFK_1; Type: FK CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_SIMPROP_TRIGGERS"
ADD CONSTRAINT "QRTZ_SIMPROP_TRIGGERS_IBFK_1" FOREIGN KEY ("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP") REFERENCES "QRTZ_TRIGGERS"("SCHED_NAME", "TRIGGER_NAME", "TRIGGER_GROUP") ON UPDATE RESTRICT ON DELETE RESTRICT;
--
-- Name: QRTZ_TRIGGERS_IBFK_1; Type: FK CONSTRAINT; Schema: public; Owner: quartz_user
--
ALTER TABLE ONLY "QRTZ_TRIGGERS"
ADD CONSTRAINT "QRTZ_TRIGGERS_IBFK_1" FOREIGN KEY ("SCHED_NAME", "JOB_NAME", "JOB_GROUP") REFERENCES "QRTZ_JOB_DETAILS"("SCHED_NAME", "JOB_NAME", "JOB_GROUP") ON UPDATE RESTRICT ON DELETE RESTRICT;
--
-- Name: public; Type: ACL; Schema: -; Owner: postgres
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM postgres;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO PUBLIC;
--
-- PostgreSQL database dump complete
--
<file_sep>/worker_monitor-web/src/main/webapp/js/common.js
function getUrlParam(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var deepCopy = function(source) {
var result = {};
for (var key in source) {
result[key] = typeof source[key]==='object'? deepCopy(source[key]) : source[key];
}
return result;
}
<file_sep>/worker_monitor-core/src/main/java/com/hisoka/worker_monitor/core/service/InitStartService.java
package com.hisoka.worker_monitor.core.service;
import org.hisoka.core.service.StartupCallback;
import org.springframework.stereotype.Service;
@Service("startupCallback")
public class InitStartService implements StartupCallback {
@Override
public void businessHandle() {
System.out.println("worker_monitor startupCallback");
}
}
<file_sep>/worker_monitor-web/src/main/java/com/hisoka/worker_monitor/web/interceptor/ExportInterceptor.java
package com.hisoka.worker_monitor.web.interceptor;
import com.alibaba.fastjson.JSON;
import org.hisoka.common.constance.Application;
import org.hisoka.common.constance.Result;
import org.hisoka.common.constance.ResultCode;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 导出拦截器,对带有特定参数的请求进行拦截
* @author Hinsteny
* @Describtion
* @date 2016/10/19
* @copyright: 2016 All rights reserved.
*/
public class ExportInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
String exportFlag = request.getParameter(Application.EXPORT_FLAG);
try {
if ("excel".equals(exportFlag)) {
// handleExcelExport(request, response, handler, modelAndView);
} else if ("word".equals(exportFlag)) {
// do something ...
}
} catch (Exception e) {
Result result = new Result(ResultCode.COMMON_SYSTEM_ERROR, false);
result.setDescription(e.getMessage());
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String responseStr = JSON.toJSONString(result);
response.getWriter().println(responseStr);
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
<file_sep>/worker_monitor-dataaccess/src/main/java/com/hisoka/worker_monitor/dataaccess/dao/redis/impl/CaptchaRedisDAOImpl.java
//package com.sztx.worker_monitor.dataaccess.dao.redis.impl;
//
//import org.springframework.data.redis.connection.RedisConnection;
//import org.springframework.data.redis.core.RedisCallback;
//import org.springframework.stereotype.Repository;
//
//import com.sztx.worker_monitor.dataaccess.dao.redis.CaptchaRedisDAO;
//import com.sztx.juste.dataaccess.redis.impl.BaseRedisDAOImpl;
//
///**
// *
// * @author zhihongp
// *
// */
//@Repository("captchaRedisDAO")
//public class CaptchaRedisDAOImpl extends BaseRedisDAOImpl implements CaptchaRedisDAO {
// public static String PREFIX_TOKEN = "captcha:";
//
// @Override
// public boolean addCaptcha(final String username, final String captcha, final long timeOut) {
// boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
// @Override
// public Boolean doInRedis(RedisConnection connection) {
// String key = PREFIX_TOKEN + username + "_" + captcha;
// byte[] bytes = serialize(key);
// connection.set(bytes, serialize(captcha));
// connection.expire(bytes, timeOut);
// return true;
// }
// });
//
// return result;
// }
//
// @Override
// public String getCaptcha(final String username, final String captchaKey) {
// String result = redisTemplate.execute(new RedisCallback<String>() {
// @Override
// public String doInRedis(RedisConnection connection) {
// String key = PREFIX_TOKEN + username + "_" + captchaKey;
// byte[] bytes = connection.get(serialize(key));
// return deserialize(String.class, bytes);
// }
// });
//
// return result;
// }
//
// @Override
// public void removeCaptcha(final String username, final String captchaKey) {
// redisTemplate.execute(new RedisCallback<Boolean>() {
// @Override
// public Boolean doInRedis(RedisConnection connection) {
// String key = PREFIX_TOKEN + username + "_" + captchaKey;
// connection.del(serialize(key));
// return true;
// }
// });
// }
//
//}
<file_sep>/worker_monitor-dataaccess/src/main/java/com/hisoka/worker_monitor/dataaccess/dao/redis/LoginRedisDAO.java
//package com.sztx.worker_monitor.dataaccess.dao.redis;
//
//import com.sztx.juste.dataaccess.redis.BaseRedisDAO;
//
///**
// * 登录缓存DAO
// *
// * @author pzh
// *
// */
//public interface LoginRedisDAO extends BaseRedisDAO {
//
// /**
// * 添加登陆用户凭证到缓存
// *
// * @param username
// * @param ticket
// * @param maxLoginKeepTime
// * @param application
// * @return
// */
// boolean addLoginTicket(final String username, final String ticket, final int maxLoginKeepTime, final String application);
//
// /**
// * 查询是否包含缓存凭证
// *
// * @param username
// * @param ticket
// * @param application
// * @return
// */
// boolean containsLoginTicket(final String username, final String ticket, final String application);
//
// /**
// * 刷新用户缓存
// * @param username
// * @param maxLoginKeepTime
// * @param application
// * @return
// */
// boolean refreshLoginTicket(final String username, int maxLoginKeepTime, final String application);
//
// /**
// * 删除凭证
// *
// * @param username
// * @return
// */
// boolean removeLoginTicket(final String username, final String application);
//}
<file_sep>/worker_monitor-core/src/main/java/com/hisoka/worker_monitor/core/service/LogService.java
package com.hisoka.worker_monitor.core.service;
import java.util.List;
import com.hisoka.worker_monitor.dataaccess.domain.Log;
public interface LogService {
List<Log> findUnHandleLogs(Integer taskItemNum, String taskItems, Integer fetchNum);
boolean updateLog(Integer id, Integer oldStatus, Integer newStatus, Integer num);
}
<file_sep>/worker_monitor-core/src/main/java/com/hisoka/worker_monitor/core/service/impl/UserServiceImpl.java
package com.hisoka.worker_monitor.core.service.impl;
import java.util.Date;
import com.hisoka.worker_monitor.dataaccess.domain.User;
import org.apache.commons.lang.StringUtils;
import org.hisoka.common.exception.BusinessException;
import org.hisoka.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hisoka.worker_monitor.core.service.UserService;
import com.hisoka.worker_monitor.dataaccess.dao.mysql.UserMysqlDAO;
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl implements UserService {
@Autowired
private UserMysqlDAO userMysqlDAO;
public User findByUsername(String username) {
User user = userMysqlDAO.findByUsername(username);
return user;
}
//@Transactional
@Override
public Integer addUser(String username, String password, String nick, Integer sex, Integer age, Date birthday, String address, String tel, String email,
String md5Key) {
// 根据用户名查询是否已经存在
User oldUser = userMysqlDAO.findByUsername(username);
if (oldUser != null) {
throw new BusinessException("该用户已经存在");
}
User user = new User();
user.setUsername(username);
user.setPassword(<PASSWORD>);
user.setNick(StringUtils.isBlank(nick) ? username : nick);
user.setSex(sex);
user.setAge(age);
user.setBirthday(birthday);
user.setAddress(address);
user.setTel(tel);
user.setEmail(email);
user.setStatus(User.STATUS_NORMAL);
userMysqlDAO.save(user);
Integer userId = user.getId();
if (userId == null || userId.intValue() <= 0) {
throw new BusinessException("创建用户失败");
}
User thisUser = userMysqlDAO.findByUsername(username);
// String encryptPword = LoginUtil.generateMD5Password(username, password, thisUser.getCreateTime(), md5Key);
String encryptPword = <PASSWORD>;
thisUser.setPassword(<PASSWORD>);
userMysqlDAO.update(thisUser);
return userId;
}
}
<file_sep>/worker_monitor-core/src/main/java/com/hisoka/worker_monitor/core/service/RpcTestService.java
package com.hisoka.worker_monitor.core.service;
public interface RpcTestService {
String testRpc();
}
<file_sep>/worker_monitor-web/src/test/java/com/hisoka/worker_monitor/web/test/BaseTest.java
package com.hisoka.worker_monitor.web.test;
import javax.annotation.PostConstruct;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
//import com.sztx.se.core.service.UnitTestInitializeService;
@Ignore
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring-config.xml" })
@WebAppConfiguration
public class BaseTest {
//@Autowired
//protected UnitTestInitializeService unitTestInitialize;
@PostConstruct
public void init() throws Exception {
//unitTestInitialize.init();
}
}
<file_sep>/worker_monitor-web/src/main/java/com/hisoka/worker_monitor/web/controller/HomeController.java
package com.hisoka.worker_monitor.web.controller;
import com.hisoka.worker_monitor.core.service.UserService;
import com.hisoka.worker_monitor.dataaccess.domain.User;
import com.hisoka.worker_monitor.web.config.LoginConfig;
import com.hisoka.worker_monitor.web.config.LoginTicket;
import com.hisoka.worker_monitor.web.interceptor.LoginAuthInterceptor;
import com.hisoka.worker_monitor.web.util.LoginUtil;
import org.hisoka.common.constance.Result;
import org.hisoka.common.util.session.HttpSessionProxy;
import org.hisoka.core.session.apply.SessionManager;
import org.hisoka.core.session.config.SessionConfig;
import org.hisoka.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Hinsteny
* @Describtion
* @date 2016/10/19
* @copyright: 2016 All rights reserved.
*/
@Controller
public class HomeController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@Autowired
private LoginConfig loginConfig;
@Autowired
private UserService userService;
@Autowired
private SessionConfig sessionConfig;
@Autowired
private SessionManager sessionManager;
@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public ModelAndView home(Model model) {
model.addAttribute("title", "Quartz任务管理");
return new ModelAndView("index");
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(Model model) {
model.addAttribute("title", "登陆");
return new ModelAndView("login");
}
@RequestMapping(value = "/help", method = RequestMethod.GET)
public ModelAndView help(Model model) {
model.addAttribute("title", "帮助");
return new ModelAndView("help");
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public Result login(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam(value = "name") String username, @RequestParam(value = "pass") String password) {
Result result = new Result();
result.setSuccess(true);
LoginTicket ticket = new LoginTicket(username, password);
User user = userService.findByUsername(ticket.getUserName());
if (user != null){
HttpSessionProxy session = sessionManager.getSession(request, response, true, sessionConfig);
if (user.getPassword().equals(ticket.getPassword())){
LoginUtil.doLogin(request, response, ticket, session, loginConfig, sessionConfig.getName());
result.setCode("0");
result.setDescription("Success!");
} else {
LoginUtil.doLogout(request, response, ticket, session);
result.setCode("2");
result.setDescription("User password is not correct!");
}
sessionManager.saveSession(session, sessionConfig);
} else {
result.setCode("1");
result.setDescription("User not exist!");
}
return result;
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, Model model) {
LoginTicket ticket = LoginUtil.getLoginTicketByCookie(request, loginConfig);
HttpSessionProxy session = sessionManager.getSession(request, response, true, sessionConfig);
LoginUtil.doLogout(request, response, ticket, session);
return new ModelAndView("login");
}
}
<file_sep>/worker_monitor-core/src/main/java/com/hisoka/worker_monitor/core/mq/DemoMqMessageListener.java
package com.hisoka.worker_monitor.core.mq;
import org.hisoka.core.mq.consumer.MqMessageListener;
public class DemoMqMessageListener extends MqMessageListener {
@Override
public Object handleMessage(String messageId,String messageContent, String queue) {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/worker_monitor-web/src/main/java/com/hisoka/worker_monitor/web/controller/quartz/QuartzController.java
package com.hisoka.worker_monitor.web.controller.quartz;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.dubbo.config.support.Parameter;
import com.hisoka.worker_monitor.core.quartz.QuartzCommon;
import org.hisoka.common.constance.Result;
import org.hisoka.common.constance.ResultCode;
import org.hisoka.core.quartz.config.QuartzParameter;
import org.hisoka.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@RequestMapping("/quartz")
@Controller
public class QuartzController extends BaseController {
@Autowired(required = false)
private QuartzCommon quartzCommon;
@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public ModelAndView index(Model model) {
model.addAttribute("title", "定时任务管理");
return new ModelAndView("quartz/index");
}
@RequestMapping(value = {"/to_create"}, method = RequestMethod.GET)
public ModelAndView toCreate(Model model) {
model.addAttribute("title", "创建任务");
return new ModelAndView("quartz/add_job");
}
@RequestMapping(value = {"/to_cron"}, method = RequestMethod.GET)
public ModelAndView toCron(Model model) {
return new ModelAndView("quartz/cron");
}
@RequestMapping(value = {"/to_edit"}, method = RequestMethod.GET)
public ModelAndView toEdit(Model model, @RequestParam String jobGroup, @RequestParam String jobName) {
model.addAttribute("title", "编辑任务");
model.addAttribute("jobGroup", jobGroup);
model.addAttribute("jobName", jobName);
return new ModelAndView("quartz/edit_job");
}
// job管理
@RequestMapping(value = "/get_job_list")
public Result getJobList(HttpServletRequest request, Model model) {
List<QuartzParameter> jobs = quartzCommon.getAllJobs();
if (jobs != null) {
Result result = new Result(ResultCode.COMMON_SUCCESS, true);
result.setProperty("jobList", jobs);
return result;
} else {
return new Result(ResultCode.COMMON_SYSTEM_EXCEPTION, false);
}
}
@RequestMapping(value = "/pause_job", method=RequestMethod.POST)
public Result pauseJob(HttpServletRequest request, Model model) {
boolean ret = quartzCommon.pauseJob(getStringParameter("jobName"), getStringParameter("jobGroup"));
Result result = new Result(ret ? ResultCode.COMMON_SUCCESS : ResultCode.COMMON_SYSTEM_EXCEPTION, ret);
return result;
}
@RequestMapping(value = "/resume_job", method=RequestMethod.POST)
public Result resumeJob(HttpServletRequest request, Model model) {
boolean ret = quartzCommon.resumeJob(getStringParameter("jobName"), getStringParameter("jobGroup"));
return new Result(ret ? ResultCode.COMMON_SUCCESS : ResultCode.COMMON_SYSTEM_EXCEPTION, ret);
}
@RequestMapping(value = "/restart_job", method=RequestMethod.POST)
public Result restartJob(HttpServletRequest request, Model model) {
quartzCommon.pauseJob(getStringParameter("jobName"), getStringParameter("jobGroup"));
boolean ret = quartzCommon.resumeJob(getStringParameter("jobName"), getStringParameter("jobGroup"));
return new Result(ret ? ResultCode.COMMON_SUCCESS : ResultCode.COMMON_SYSTEM_EXCEPTION, ret);
}
@RequestMapping(value = "/delete_job", method=RequestMethod.POST)
public Result deleteJob(HttpServletRequest request, Model model) {
boolean ret = quartzCommon.deleteJob(getStringParameter("jobName"), getStringParameter("jobGroup"));
return new Result(ret ? ResultCode.COMMON_SUCCESS : ResultCode.COMMON_SYSTEM_EXCEPTION, ret);
}
@RequestMapping(value = "/get_group_name_list", method=RequestMethod.GET)
public Result getGroupList(HttpServletRequest request, Model model) {
List<QuartzParameter> jobs = quartzCommon.getAllJobs();
if (jobs != null) {
QuartzGroupList groupList = new QuartzGroupList(jobs);
Result result = new Result(ResultCode.COMMON_SUCCESS, true);
result.setProperty("groupList", groupList);
return result;
} else {
return new Result(ResultCode.COMMON_SYSTEM_EXCEPTION, false);
}
}
@RequestMapping(value = "/get_job_detail", method=RequestMethod.POST)
public Result getJobDetail(HttpServletRequest request, Model model) {
String jobGroup = getStringParameter("jobGroup", "");
String jobName = getStringParameter("jobName", "");
// 判断参数是否为空值
String missingParameter = "";
if ("".equals(jobGroup)) missingParameter += "任务组名, ";
if ("".equals(jobName)) missingParameter += "任务名, ";
if (!"".equals(missingParameter)) {
Result result = new Result(ResultCode.COMMON_SYSTEM_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00010", "参数: [" + missingParameter + "] 为空!");
result.setProperty("error", err);
return result;
}
List<QuartzParameter> jobs = quartzCommon.getAllJobs();
if (jobs == null) {
Result result = new Result(ResultCode.COMMON_BUSINESS_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00012", "系统异常!获取job列表失败");
result.setProperty("error", err);
return result;
}
QuartzParameter jobDetail = QuartzJobsFuncCtrl.findJobInList(jobs, jobGroup, jobName);
if (null == jobDetail) {
Result result = new Result(ResultCode.COMMON_BUSINESS_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00013", "不存在该任务!");
result.setProperty("error", err);
return result;
}
System.out.println("getJobDetail jobDetail=" + JSONObject.toJSONString(jobDetail));
Result result = new Result(ResultCode.COMMON_SUCCESS, true);
result.setProperty("jobDetail", jobDetail);
return result;
}
@RequestMapping(value = "/add_job", method=RequestMethod.POST)
public Result addJob(HttpServletRequest request, Model model) {
// 获取参数
QuartzParameter job = JSONObject.parseObject(getStringParameter("job", ""), QuartzParameter.class);
job.setTriggerGroup(job.getJobGroup());
job.setTriggerName(job.getJobName());
// 判断参数是否为空值
String missingParameter = "";
if ("".equals(job.getJobGroup())) missingParameter += "任务组名, ";
if ("".equals(job.getJobName())) missingParameter += "任务名, ";
if ("".equals(job.getExpression())) missingParameter += "表达式, ";
if ("".equals(job.getJobClassName())) missingParameter += "运行程序名, ";
if (!"".equals(missingParameter)) {
Result result = new Result(ResultCode.COMMON_SYSTEM_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00010", "参数: [" + missingParameter + "] 为空!");
result.setProperty("error", err);
return result;
}
// 判断任务是否重复
List<QuartzParameter> jobs = quartzCommon.getAllJobs();
if (jobs == null) {
Result result = new Result(ResultCode.COMMON_BUSINESS_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00012", "系统异常!获取job列表失败");
result.setProperty("error", err);
return result;
}
if (null != QuartzJobsFuncCtrl.findJobInList(jobs, job.getJobGroup(), job.getJobName())) {
Result result = new Result(ResultCode.COMMON_BUSINESS_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00011", "任务重复!");
result.setProperty("error", err);
return result;
}
// 添加job
//Map<String, String> extraInfo = new HashMap<String, String>();
//job.setExtraInfo(extraInfo);
System.out.println("addJob job = " + JSONObject.toJSONString(job));
boolean addRet = quartzCommon.saveOrUpdateJob(job);
// 返回
Result result = new Result(addRet ? ResultCode.COMMON_SUCCESS : ResultCode.COMMON_SYSTEM_EXCEPTION, addRet);
result.setProperty("quartzConfig", addRet);
return result;
}
@RequestMapping(value = "/edit_job", method=RequestMethod.POST)
public Result editJob(HttpServletRequest request, Model model) {
// 获取参数
QuartzParameter oldJob = JSONObject.parseObject(getStringParameter("oldJob", ""), QuartzParameter.class);
QuartzParameter job = JSONObject.parseObject(getStringParameter("job", ""), QuartzParameter.class);
job.setTriggerGroup(job.getJobGroup());
job.setTriggerName(job.getJobName());
oldJob.setTriggerGroup(oldJob.getJobGroup());
oldJob.setTriggerName(oldJob.getJobName());
boolean isJobGroupOrNameChanged = (!oldJob.getJobGroup().equals(job.getJobGroup()) || !oldJob.getJobName().equals(job.getJobName()));
// 判断参数是否为空值
String missingParameter = "";
if ("".equals(job.getJobGroup())) missingParameter += "任务组名, ";
if ("".equals(job.getJobName())) missingParameter += "任务名, ";
if ("".equals(job.getExpression())) missingParameter += "表达式, ";
if ("".equals(job.getJobClassName())) missingParameter += "运行程序名, ";
if ("".equals(oldJob.getJobGroup())) missingParameter += "原任务组名, ";
if ("".equals(oldJob.getJobName())) missingParameter += "原任务名, ";
if (!"".equals(missingParameter)) {
Result result = new Result(ResultCode.COMMON_SYSTEM_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00010", "参数: [" + missingParameter + "] 为空!");
result.setProperty("error", err);
return result;
}
// 判断原任务是否存在
List<QuartzParameter> jobs = quartzCommon.getAllJobs();
if (jobs == null) {
Result result = new Result(ResultCode.COMMON_BUSINESS_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00012", "系统异常!获取job列表失败");
result.setProperty("error", err);
return result;
}
if (null == QuartzJobsFuncCtrl.findJobInList(jobs, oldJob.getJobGroup(), oldJob.getJobName())){
Result result = new Result(ResultCode.COMMON_BUSINESS_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00014", "需要编辑的任务不存在!");
result.setProperty("error", err);
return result;
}
// 判断新任务是否存在
if (isJobGroupOrNameChanged && null != QuartzJobsFuncCtrl.findJobInList(jobs, job.getJobGroup(), job.getJobName())) {
Result result = new Result(ResultCode.COMMON_BUSINESS_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00015", "修改失败,已存在相同的任务!");
result.setProperty("error", err);
return result;
}
// 创建新任务
//Map<String, String> extraInfo = new HashMap<String, String>();
//job.setExtraInfo(extraInfo);
System.out.println("editJob job = " + JSONObject.toJSONString(job));
boolean addRet = quartzCommon.saveOrUpdateJob(job);
if (!addRet) {
Result result = new Result(ResultCode.COMMON_SYSTEM_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00016", "修改失败");
result.setProperty("error", err);
return result;
}
// 删除原任务
if (isJobGroupOrNameChanged) {
boolean deleteJobRet = quartzCommon.deleteJob(oldJob.getJobName(), oldJob.getJobGroup());
boolean deleteTriggerRet = quartzCommon.deleteTrigger(oldJob.getTriggerName(), oldJob.getTriggerGroup());
if (!deleteJobRet || !deleteTriggerRet) {
Result result = new Result(ResultCode.COMMON_SYSTEM_EXCEPTION, false);
QuartzErrorManage err = new QuartzErrorManage("00017", "修改成功,但原始任务删除失败!");
result.setProperty("error", err);
return result;
}
}
// 返回
Result result = new Result(ResultCode.COMMON_SUCCESS, true);
result.setProperty("jobDetail", job);
return result;
}
}
<file_sep>/worker_monitor-core/src/main/java/com/hisoka/worker_monitor/core/quartz/QuartzCommon.java
package com.hisoka.worker_monitor.core.quartz;
import java.util.List;
import org.hisoka.core.quartz.config.QuartzParameter;
import org.hisoka.core.quartz.manager.QuartzManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class QuartzCommon {
private static final Logger logger = LoggerFactory.getLogger(QuartzCommon.class);
private static final String schmeaName = "Scheduler";
@Autowired
private QuartzManager quartzManager;
public List<QuartzParameter> getAllJobs() {
try {
return quartzManager.getAllJobs();
} catch (Exception e) {
logger.error("", e);
return null;
}
}
public QuartzParameter getJob(String jobName, String jobGroup, String triggerName, String triggerGroup) {
try {
return quartzManager.getJob(schmeaName, jobName, jobGroup, triggerName, triggerGroup);
} catch (Exception e) {
logger.error("", e);
return null;
}
}
public boolean saveOrUpdateJob(QuartzParameter config) {
try {
quartzManager.saveOrUpdateJob(config.getSchedName(), config.getJobName(), config.getJobGroup(), config.getJobClassName(), config.getDescription(), config.getIsRecovery(),
config.getTriggerName(), config.getTriggerGroup(), config.getIsCronTrigger(), config.getExpression(), config.getStartAt(), config.getEndAt(), config.getExtraInfo());
return true;
} catch (Exception e) {
logger.error("", e);
return false;
}
}
public boolean pauseJob(String jobName, String jobGroup) {
try {
//quartzManager.pauseJob(schmeaName,jobName, jobGroup);
quartzManager.pauseTrigger(schmeaName, jobName, jobGroup);
return true;
} catch (Exception e) {
logger.error("", e);
return false;
}
}
public boolean resumeJob(String jobName, String jobGroup) {
try {
//quartzManager.resumeJob(schmeaName, jobName, jobGroup);
quartzManager.resumeTrigger(schmeaName, jobName, jobGroup);
return true;
} catch (Exception e) {
logger.error("", e);
return false;
}
}
public boolean deleteJob(String jobName, String jobGroup) {
try {
//quartzManager.deleteJob(schmeaName, jobName, jobGroup);
quartzManager.deleteTrigger(schmeaName, jobName, jobGroup);
return true;
} catch (Exception e) {
logger.error("", e);
return false;
}
}
public boolean pauseTrigger(String triggerName, String triggerGroup) {
try {
quartzManager.pauseTrigger(schmeaName, triggerName, triggerGroup);
return true;
} catch (Exception e) {
logger.error("", e);
return false;
}
}
public boolean resumeTrigger(String triggerName, String triggerGroup) {
try {
quartzManager.resumeTrigger(schmeaName, triggerName, triggerGroup);
return true;
} catch (Exception e) {
logger.error("", e);
return false;
}
}
public boolean deleteTrigger(String triggerName, String triggerGroup) {
try {
quartzManager.deleteTrigger(schmeaName, triggerName, triggerGroup);
return true;
} catch (Exception e) {
logger.error("", e);
return false;
}
}
}
<file_sep>/worker_monitor-web/src/main/webapp/js/angular_quartz_module.js
var quartzCommonModule = angular.module("quartzCommonModule",[]);
quartzCommonModule.showJobList = function($scope) {
$scope.getJobList(function(data){
$scope.jobList = data;
});
}
quartzCommonModule.controller("quartzCommonController",["$scope", "$http", function($scope,$http){
// 错误管理
$scope.isShowErrorList = false;
$scope.errorList = new Array();
$scope.addErrorInfo = function(info) {
var ei = {};
ei.dateStr = (new Date()).toLocaleString();
ei.info = info;
$scope.errorList.push(ei);
$scope.isShowErrorList = true;
};
// 获取job信息
$scope.getJobDetail = function (job, callback) {
callback(null);
$http({
method: "post",
url: "/quartz/get_job_detail",
params: {"jobGroup":job.jobGroup, "jobName":job.jobName}
})
.success(function(data, status) {
if (!data.success) {
if (data.hasOwnProperty("resultMap") && data.resultMap.hasOwnProperty("error")) {
$scope.addErrorInfo("获取任务任务详细信息失败! errorCode: " + data.resultMap.error.code + ", description: "+data.resultMap.error.description);
} else {
$scope.addErrorInfo("获取任务任务详细信息失败! 未知错误");
}
} else {
callback(data.resultMap.jobDetail);
}
})
.error(function(data, status) {
$scope.addErrorInfo("获取任务任务详细信息失败! 发送数据失败! ");
});
};
// 获取job列表
$scope.getJobList = function (callback) {
callback(null);
$http({
method: "GET",
url: "/quartz/get_job_list"
})
.success(function(data, status) {
if (data.hasOwnProperty("resultMap")) {
if (data.success != true)
$scope.addErrorInfo("获取列表失败, 请刷新");
else
callback(data.resultMap.jobList);
} else {
$scope.addErrorInfo("获取列表失败, 请刷新");
}
})
.error(function(data, status) {
$scope.addErrorInfo("获取列表失败, 请刷新");
});
};
// 获取job group名称列表
$scope.getJobGroupNameList = function(callback) {
callback(null);
$http({
method: "GET",
url: "/quartz/get_group_name_list"
})
.success(function(data, status) {
if (data.hasOwnProperty("resultMap")) {
var list = new Array();
for (var i=0; i<data.resultMap.groupList.jobGroups.length; i++) {
var groupName = data.resultMap.groupList.jobGroups[i];
list.push({id : groupName, label : groupName});
}
callback(list);
} else {
$scope.addErrorInfo("获取所有任务组名失败! 失败原因:返回数据出错! ");
}
})
.error(function(data, status) {
$scope.addErrorInfo("获取所有任务组名失败! 失败原因:发送数据失败! ");
});
};
// 添加任务
$scope.addJob = function(job, callback) {
$http({
method: "POST",
url: "/quartz/add_job",
params: {"job":job}
})
.success(function(data, status) {
if (data.success != true) {
if (data.hasOwnProperty("resultMap") && data.resultMap.hasOwnProperty("error")) {
$scope.addErrorInfo("添加任务 ["+job.jobGroup+":"+job.jobName+"] 失败! errorCode: "+data.resultMap.error.code+", description: "+data.resultMap.error.description);
} else {
$scope.addErrorInfo("添加任务 ["+job.jobGroup+":"+job.jobName+"] 失败! 未知错误");
}
if (callback != null) callback(false);
} else {
$scope.addErrorInfo("添加任务 ["+job.jobGroup+":"+job.jobName+"] 成功! ");
if (callback != null) callback(true);
}
})
.error(function(data, status) {
$scope.addErrorInfo("添加任务 ["+job.jobGroup+":"+job.jobName+"] 失败! 发送数据失败");
if (callback != null) callback(false);
});
};
// 打开编辑job页面
$scope.toEeditJob = function(job, callback) {
window.location.href = "/quartz/to_edit?jobGroup="+job.jobGroup + "&jobName=" + job.jobName;
};
// 编辑job
$scope.editJob = function(oldJob, job, callback) {
$http({
method: "post",
url: "/quartz/edit_job",
params: {"oldJob":oldJob, "job":job}
})
.success(function(data, status) {
if (!data.success) {
if (data.hasOwnProperty("resultMap") && data.resultMap.hasOwnProperty("error")){
$scope.addErrorInfo("修改任务 [" + job.jobGroup + ":" + job.jobName + "] 失败! errorCode: " + data.resultMap.error.code + ", description: " + data.resultMap.error.description);
} else {
$scope.addErrorInfo("修改任务 [" + job.jobGroup + ":" + job.jobName + "] 失败! 未知错误");
}
if (callback != null) callback(false);
} else {
$scope.addErrorInfo("修改任务 [" + job.jobGroup + ":"+job.jobName + "] 成功! ");
if (callback != null) callback(true);
}
})
.error(function(data, status) {
$scope.addErrorInfo("添加任务 [" + job.jobGroup+":" + job.jobName + "] 失败! 发送数据失败");
if (callback != null) callback(false);
});
};
// 暂停job
$scope.pauseJob = function(job, callback) {
$http({
method: "POST",
url: "/quartz/pause_job",
params: {"jobGroup":job.jobGroup, "jobName":job.jobName}
})
.success(function(data, status) {
if (data.success != true) {
$scope.addErrorInfo("暂停任务 ["+job.jobGroup+":"+job.jobName+"] 失败");
if (callback != null) callback(false);
} else {
if (callback != null) callback(true);
}
})
.error(function(data, status) {
$scope.addErrorInfo("暂停任务 ["+job.jobGroup+":"+job.jobName+"] 失败");
if (callback != null) callback(false);
});
};
// 重启job
$scope.restartJob = function(job, callback) {
$http({
method: "POST",
url: "/quartz/restart_job",
params: {"jobGroup":job.jobGroup, "jobName":job.jobName}
})
.success(function(data, status) {
if (data.success != true) {
$scope.addErrorInfo("重启任务 ["+job.jobGroup+":"+job.jobName+"] 失败");
if (callback != null) callback(false);
} else {
if (callback != null) callback(true);
}
})
.error(function(data, status) {
$scope.addErrorInfo("重启任务 ["+job.jobGroup+":"+job.jobName+"] 失败");
if (callback != null) callback(false);
});
};
// 删除job
$scope.deleteJob = function(job, callback) {
$http({
method: "POST",
url: "/quartz/delete_job",
params: {"jobGroup":job.jobGroup, "jobName":job.jobName}
})
.success(function(data, status) {
if (data.success != true) {
$scope.addErrorInfo("删除任务 ["+job.jobGroup+":"+job.jobName+"] 失败");
if (callback != null) callback(false);
} else {
if (callback != null) callback(true);
}
})
.error(function(data, status) {
$scope.addErrorInfo("删除任务 ["+job.jobGroup+":"+job.jobName+"] 失败");
if (callback != null) callback(false);
});
};
quartzCommonModule.showJobList($scope);
}]);<file_sep>/worker_monitor-web/src/main/java/com/hisoka/worker_monitor/web/controller/CompentController.java
package com.hisoka.worker_monitor.web.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.hisoka.worker_monitor.core.quartz.QuartzCommon;
import com.hisoka.worker_monitor.core.service.UserService;
import com.hisoka.worker_monitor.dataaccess.domain.User;
import org.hisoka.common.constance.Result;
import org.hisoka.common.constance.ResultCode;
import org.hisoka.core.quartz.config.QuartzParameter;
import org.hisoka.orm.redis.apply.DynamicRedisSource;
import org.hisoka.orm.redis.callback.RedisCallBack;
import org.hisoka.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSONObject;
/**
* @author Hinsteny
* @Describtion
* @date 2016/10/19
* @copyright: 2016 All rights reserved.
*/
@RequestMapping("/compent")
@Controller
public class CompentController extends BaseController {
@Autowired(required = false)
@Resource(name="userService")
private UserService userService;
@Autowired(required = false)
private DynamicRedisSource redisTemplate;
@Autowired(required = false)
private QuartzCommon quartzCommon;
@RequestMapping(value = "/testMysql")
public Result testMysql(HttpServletRequest request, Model model) {
String username = getStringParameter("username");
String password = getStringParameter("<PASSWORD>");
String nick = getStringParameter("nick");
Integer sex = getIntegerParameter("sex");
Integer age = getIntegerParameter("age");
Date birthday = getDateParameter("birthday");
String address = getStringParameter("address");
String tel = getStringParameter("tel");
String email = getStringParameter("email");
userService.addUser(username, password, nick, sex, age, birthday, address, tel, email, "2d1287777f4f45a881040167db74f276");
User user = userService.findByUsername(username);
// 返回页面
Result result = new Result(ResultCode.COMMON_SUCCESS, true);
result.setProperty("user", user);
return result;
}
@RequestMapping(value = "/testRedis")
public Result testRedis(HttpServletRequest request, Model model) {
final String routeKey = "TEST_REDIS";
String m = redisTemplate.execute(new RedisCallBack<String>() {
@Override
public String getKey(){
return routeKey;
}
@Override
public String doInRedis(RedisConnection connection, byte[] keyBytes) {
String vlaue = "redis";
connection.set(keyBytes, redisTemplate.getStringSerializer().serialize(vlaue));
connection.expire(keyBytes, 1000);
byte[] rBytes = connection.get(keyBytes);
String a = redisTemplate.getStringSerializer().deserialize(rBytes);
return a;
}
}, false);
// 返回页面
Result result = new Result(ResultCode.COMMON_SUCCESS, true);
result.setProperty("value", m);
return result;
}
@RequestMapping(value = "/testWorker")
public Result testWorker(HttpServletRequest request, Model model) {
QuartzParameter config = new QuartzParameter();
config.setIsRecovery(false);
config.setIsCronTrigger(true);
config.setExpression(getStringParameter("exp")); // "0 */1 * * * ?"
config.setJobName("订单统计任务");
config.setJobGroup("订单任务组");
config.setJobClassName("countOrderJob");
config.setDescription("统计每日的订单总量并且分组");
config.setTriggerName("每分钟执行的订单统计");
config.setTriggerGroup("订单触发器组");
Map<String, String> extraInfo = new HashMap<String, String>();
extraInfo.put("extra", "test");
extraInfo.put("path", getStringParameter("path"));
config.setExtraInfo(extraInfo);
System.out.println("testWorker config=" + JSONObject.toJSONString(config));
quartzCommon.saveOrUpdateJob(config);
// 返回页面
Result result = new Result(ResultCode.COMMON_SUCCESS, true);
result.setProperty("quartzConfig", config);
return result;
}
}
<file_sep>/worker_monitor-web/src/test/java/com/hisoka/worker_monitor/web/test/compent/HbaseTest.java
//package com.sztx.worker_monitor.web.test.compent;
//
//import org.junit.After;
//import org.junit.Before;
//import org.junit.Test;
//import org.springframework.beans.factory.annotation.Autowired;
//
//import com.sztx.se.dataaccess.hbase.source.DynamicHbaseSource;
//
//public class HbaseTest {
// @Autowired
// private DynamicHbaseSource hbaseTemplate;
//
// @Before
// public void setUp() throws Exception {
//
// }
//
// @After
// public void tearDown() throws Exception {
//
// }
//
// @Test
// public void testMemcache() {
//
// }
//}
<file_sep>/worker_monitor-dataaccess/src/main/java/com/hisoka/worker_monitor/dataaccess/dao/redis/CaptchaRedisDAO.java
//package com.sztx.worker_monitor.dataaccess.dao.redis;
//
//import com.sztx.juste.dataaccess.redis.BaseRedisDAO;
//
//
///**
// *
// * @author zhihongp
// *
// */
//public interface CaptchaRedisDAO extends BaseRedisDAO {
//
// boolean addCaptcha(final String username, final String captcha, final long timeOut);
//
// String getCaptcha(final String username, final String captchaKey);
//
// void removeCaptcha(final String username, final String captchaKey);
//
//}
<file_sep>/worker_monitor-web/src/main/java/com/hisoka/worker_monitor/web/controller/quartz/QuartzJobsFuncCtrl.java
package com.hisoka.worker_monitor.web.controller.quartz;
import org.hisoka.core.quartz.config.QuartzParameter;
import java.util.List;
public class QuartzJobsFuncCtrl {
static public QuartzParameter findJobInList(List<QuartzParameter> jobList, String jobGroup, String jobName) {
/* 查找所有的组名 以及订单触发器组名 */
for( int i = 0; i < jobList.size() ; i ++){
if(jobList.get(i).getJobGroup().equals(jobGroup) &&
jobList.get(i).getJobName().equals(jobName))
return jobList.get(i);
}
return null;
}
}<file_sep>/README.md
# worker-monitor(Quratz managerment system)
## Auther
* Hinsteny [Home](https://github.com/Hinsteny)
### Introduce
项目本身采用Maven管理, jdk1.8, 配置基础的SSM框架使用方法.
###
* Spring, Springmvc, mybatis,
* postgres
* redis,
### Config using
* git clone <EMAIL>:Hinsteny/WorkerMonitor.git
<file_sep>/worker_monitor-dataaccess/src/main/java/com/hisoka/worker_monitor/dataaccess/dao/redis/impl/LoginRedisDAOImpl.java
//package com.sztx.worker_monitor.dataaccess.dao.redis.impl;
//
//import org.apache.commons.lang.StringUtils;
//import org.springframework.data.redis.connection.RedisConnection;
//import org.springframework.data.redis.core.RedisCallback;
//import org.springframework.stereotype.Repository;
//
//import com.sztx.worker_monitor.dataaccess.dao.redis.LoginRedisDAO;
//import com.sztx.juste.dataaccess.redis.impl.BaseRedisDAOImpl;
//
///**
// *
// * @author zhihongp
// *
// */
//@Repository("loginRedisDAO")
//public class LoginRedisDAOImpl extends BaseRedisDAOImpl implements LoginRedisDAO {
//
// public static final String PREFIX_LOGIN_TICKET = "login_ticket";
//
// @Override
// public boolean addLoginTicket(final String username, final String ticket, final int maxLoginKeepTime, final String application) {
// boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
// @Override
// public Boolean doInRedis(RedisConnection connection) {
// String key = getKey(PREFIX_LOGIN_TICKET, username, application);
// byte[] skey = serialize(key);
// connection.set(skey, serialize(ticket));
// connection.expire(skey, maxLoginKeepTime);
// return true;
// }
// });
//
// return result;
// }
//
// @Override
// public boolean containsLoginTicket(final String username, final String ticket, final String application) {
// String result = redisTemplate.execute(new RedisCallback<String>() {
// @Override
// public String doInRedis(RedisConnection connection) {
// String key = getKey(PREFIX_LOGIN_TICKET, username, application);
// byte[] bytes = connection.get(serialize(key));
// return deserialize(String.class, bytes);
// }
// });
//
// if (StringUtils.isNotBlank(result) && ticket.equals(result)) {
// return true;
// } else {
// return false;
// }
// }
//
// @Override
// public boolean refreshLoginTicket(final String username, final int maxLoginKeepTime, final String application) {
// boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
// @Override
// public Boolean doInRedis(RedisConnection connection) {
// String key = getKey(PREFIX_LOGIN_TICKET, username, application);
// byte[] skey = serialize(key);
// connection.expire(skey, maxLoginKeepTime);
// return true;
// }
// });
//
// return result;
// }
//
// @Override
// public boolean removeLoginTicket(final String username, final String application) {
// boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
// @Override
// public Boolean doInRedis(RedisConnection connection) {
// String key = getKey(PREFIX_LOGIN_TICKET, username, application);
// byte[] skey = serialize(key);
// connection.del(skey);
// return true;
// }
// });
//
// return result;
// }
//
// private String getKey(String prifix, String sufix, String application) {
// return prifix + ":" + application + "_" + sufix;
// }
//
//}
<file_sep>/worker_monitor-web/src/main/java/com/hisoka/worker_monitor/web/excel/ExportUtil.java
package com.hisoka.worker_monitor.web.excel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hisoka.common.exception.SystemException;
public class ExportUtil {
public static enum ExcelType {XLS, XLSX}
public static void exportToOutputStream(List<ExportCellData> cellDataList,ExcelType xlsx, OutputStream outputStream) throws IOException {
createExport(cellDataList, xlsx).write(outputStream);
}
public static Workbook createExport(List<ExportCellData> cellDataList,ExcelType xlsx){
Workbook workbook;
if (ExcelType.XLS.equals(xlsx)) {
workbook = new HSSFWorkbook();
} else {
workbook = new XSSFWorkbook() ;
}
CellStyle cellHeadStyle = createHeadStyle(workbook);
CellStyle cellDataStyle = createDataStyle(workbook);
Sheet sheet = workbook.createSheet();
createRowAndCell(cellDataList,sheet,cellHeadStyle,cellDataStyle);
return workbook;
}
private static void createRowAndCell(List<ExportCellData> cellDataList,Sheet sheet, CellStyle cellHeadStyle,CellStyle cellDataStyle){
for(ExportCellData cellData:cellDataList){
Row row =sheet.getRow(cellData.getRow());
if(row==null){
row = sheet.createRow(cellData.getRow());
}
if(cellData.getEndRow()!=null&&cellData.getEndCol()!=null){
if(cellData.getEndRow()<cellData.getRow()||cellData.getEndCol()<cellData.getCol()){
throw new SystemException(String.format("栏位%s(%s,%s)合并行列(%s,%s)错误",cellData.getValue(),cellData.getRow(),cellData.getCol(),cellData.getEndRow(),cellData.getEndCol()));
}else{
sheet.addMergedRegion(new CellRangeAddress(cellData.getRow(),cellData.getEndRow(),cellData.getCol(),cellData.getEndCol()));
}
}
Cell cell = row.createCell(cellData.getCol());
cell.setCellValue(formatToString(cellData.getValue()));
if(cellData.getStyle()==1){
cell.setCellStyle(cellHeadStyle);
}else{
cell.setCellStyle(cellDataStyle);
}
}
}
private static CellStyle createHeadStyle(Workbook workbook){
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 12);
font.setFontName("新宋体");
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
style.setFont(font);
return style;
}
private static CellStyle createDataStyle(Workbook workbook){
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 12);
font.setFontName("新宋体");
style.setFont(font);
return style;
}
private static String formatToString(Object object) {
if (object == null) {
return "";
} else if (object instanceof Date) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) object);
} else {
return object.toString();
}
}
public static void main(String[] args) {
List<ExportCellData> list = new ArrayList<ExportCellData>();
list.add(new ExportCellData(0,0,"a0",1));
list.add(new ExportCellData(0,1,"a1"));
list.add(new ExportCellData(0,2,"a2"));
list.add(new ExportCellData(0,3,"a3"));
list.add(new ExportCellData(1,3,"a3",0,1,2));
Workbook workbook = createExport(list,ExcelType.XLSX);
try {
workbook.write(new FileOutputStream("e:\\test.xlsx"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
ec0995a47f14ac33cc2c43ac9680f79a2a91b6c7
|
[
"SQL",
"JavaScript",
"Markdown",
"INI",
"Java"
] | 29 |
Java
|
Hinsteny/WorkerMonitor
|
6e8d91ca021e00c6ac810999879ea0cf713f7d63
|
0cbfe7d4c40574dce294bae768f4725856f6bf17
|
refs/heads/main
|
<repo_name>stolgonai/e-comm<file_sep>/src/components/Home/Home.jsx
import dress from "../../assets/EveningDress.png";
import sport from "../../assets/sportDress.png";
import "./Home.css";
function Home() {
return (
<div className="homePage">
<div className="banner">
<h1>
Fashion <br />
sale
</h1>
<button>Check</button>
</div>
<div className="saleBlock">
<div className="aboutSale">
<h1 className="saleTitle">Sale</h1>
<p className="saleCaption">Super summer sale</p>
<button className="btn viewBtn">View all</button>
</div>
<main>
<div className="cardList">
<div className="card">
<img src={dress} alt="dress"></img>
<p className="saleCaption">D<NAME></p>
<h3 className="cardTitle">Evening Dress</h3>
<span className="cardPrice">12$</span>
</div>
<div className="card">
<img src={sport} alt="dress"></img>
<p className="saleCaption">Sitlly</p>
<h3 className="cardTitle">Sport Dress</h3>
<span className="cardPrice">19$</span>
</div>
</div>
</main>
</div>
</div>
);
}
export default Home;
<file_sep>/src/components/Auth/Login.jsx
import "./Auth.css";
function Login() {
return (
<div className="loginPage">
<header>
<button className="btn">
Back
</button>
<h1>Sign up</h1>
</header>
<main>
<form>
<label className="textField">
<input className="input" type="text" />
<span className="caption">Name</span>
<span className="icon">✔️</span>
</label>
<label className="textField">
<input className="input" type="email" />
<span className="caption">Email</span>
</label>
<label className="textField">
<input className="input" type="password" />
<span className="caption">Password</span>
</label>
</form>
</main>
</div>
);
}
export default Login;
<file_sep>/src/components/Shop/CategoryList.jsx
import newArr from '../../assets/newArr.svg'
import clothes from '../../assets/clothes.svg'
import shoes from '../../assets/shoes.svg'
import accesors from '../../assets/accesors.svg'
import searchIcon from '../../assets/search-icon.svg'
import goBackIcon from '../../assets/go-back-icon.svg'
function CategoryList() {
return (
<div className="categorList">
<div className="tabs">
<div className="back-icon">
<img src= {goBackIcon} alt="go back" />
</div>
<div className="title"> Categories </div>
<div className="search-icon">
<img src={searchIcon} alt="search icon" />
</div>
</div>
<nav className="chooseByGender">
<div id="active" className="gender">
<button className="btn genderBtn" > Women </button> </div>
<div className="gender">
<button className="btn genderBtn"> Men </button> </div>
<div className="gender">
<button className="btn genderBtn"> Kids </button> </div>
</nav>
<div className="catList">
<div className="salesBaner">
<h3 className="title">SUMMER SALES</h3>
<p className="discount">Up to 50% off </p>
</div>
<div className="lists">
<div className="departName">New Arrivals</div>
<img src={newArr} alt="nrearr" />
</div>
<div className="lists">
<div className="departName"> Clothes </div>
<img src={clothes} alt="nrearr" />
</div>
<div className="lists">
<div className="departName">Shoes</div>
<img src={shoes} alt="nrearr" />
</div>
<div className="lists">
<div className="departName"> Accesories </div>
<img src={accesors} alt="nrearr" />
</div>
</div>
</div>
)
}
export default CategoryList<file_sep>/src/components/ui/Modal/Modal.jsx
import './Modal.css'
function Modal({ onClose, children, btnText }) {
return (
<div>
<div className="modal-bg" onClick={onClose}></div>
<div className="modal">
<div className="line"></div>
{children}
<div className="footerBtn">
<button className="btn footerModalBtn"> {btnText} </button>
</div>
</div>
</div>
)
}
export default Modal;<file_sep>/src/components/Shop/Shop.jsx
import CategoryList from './CategoryList'
import Womens from './Womens'
import './Shop.css'
function Shop() {
return (
<div className="shopPage">
<CategoryList />
<Womens />
</div>
)
}
export default Shop<file_sep>/src/components/Auth/Register.jsx
import fbIcon from '../../assets/facebookicon.svg'
import googleIcon from '../../assets/googleicon.svg'
import backIcon from '../../assets/backBtn.svg'
import nextIcon from '../../assets/nextBtn.svg'
function Register(){
return(
<div className='registerPage'>
<header>
<button className="btn">
<img src={backIcon} alt="go to back" />
</button>
<h1>Login</h1>
</header>
<main>
<form>
<label className="textField">
<input className="input" type="email" placeholder='<EMAIL>'/>
<span className="emailCaption">Email</span>
<span className="icon">✔️</span>
</label>
</form>
<div className="next">
<a className='nextLink'>Forgot your password?</a>
<button className='btn nextBtn'>
<img src={nextIcon} alt="" />
</button>
</div>
<div className='loginBtnDiv'>
<button className='btn loginBtn'>LOGIN</button>
</div>
</main>
<footer>
<span className='footerText'>Or login with social account</span>
<div className="social">
<button className="btn google">
<img src={googleIcon} alt="google" />
</button>
<button className="btn facebook">
<img src={fbIcon} alt="facebook" />
</button>
</div>
</footer>
</div>
)
}
export default Register;<file_sep>/src/components/Navbar/Navbar.jsx
import { HomeIcon, ShopIcon } from "../icons";
import shopIcon from "../../assets/shopicon.svg";
import bagIcon from "../../assets/bagicon.svg";
import favoritesIcon from "../../assets/favoritesicon.svg";
import profileIcon from "../../assets/profileicon.svg";
import './Navbar.css'
function Navbar({ navigate }) {
return (
<nav className="navbar">
<button className="btn navbar-btn" onClick={() => navigate("HOME")}>
<HomeIcon active={false} />
<p>Home</p>
</button>
<button className="btn navbar-btn" onClick={() => navigate("SHOP")}>
<ShopIcon active={false} />
<p>Shop</p>
</button>
<button className="btn navbar-btn" onClick={() => navigate("BAG")}>
<img src={bagIcon} alt="bagicon" />
<p>Bag</p>
</button>
<button className="btn navbar-btn" onClick={() => navigate("FAVORITES")}>
<img src={favoritesIcon} alt="favoritesicon" />
<p>Favorites</p>
</button>
<button className="btn navbar-btn" onClick={() => navigate("PROFILE")}>
<img src={profileIcon} alt="profileicon" />
<p>Profile</p>
</button>
</nav>
)
}
export default Navbar<file_sep>/src/components/icons/index.js
export { default as HomeIcon } from './HomeIcon'
export { default as ShopIcon } from './ShopIcon'<file_sep>/src/components/icons/HomeIcon.jsx
function HomeIcon({ active }) {
return (
<svg width="29" height="24" viewBox="0 0 29 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
fill={active ? "#DB3022" : "none"}
stroke={active ? "none" : "#DADADA"}
strokeWidth={active ? "0" : "2px"}
fill-rule="evenodd"
clip-rule="evenodd" d="M11.2941 24V15.5294H16.9412V24H24V12.7059H28.2353L14.1176 0L0 12.7059H4.23529V24H11.2941Z"/>
</svg>
)
}
export default HomeIcon
|
fb8349e3e9ddb240bdbb295f5bc0e4e850150fd4
|
[
"JavaScript"
] | 9 |
JavaScript
|
stolgonai/e-comm
|
0a8462b989c9ca627f17723e842da5be5515f7fd
|
607515b9de5a5bcd0f5a7666b088cbde8e4674aa
|
refs/heads/master
|
<repo_name>bnguyen467/code-quiz<file_sep>/assets/script.js
// Question library took from w3schools.com
const question = [
{
question: '1. What is HTML?',
answers: [
{ quesContent: 'Hyper Text Markup Language', correct: true},
{ quesContent: 'Hyperlinks and Text Markup Language', correct: false},
{ quesContent: 'Home Tool Markup Language', correct: false},
{ quesContent: 'HighText Machine Langague', correct: false},
],
},
{
question: '2. Choose the correct HTML element for the largest heading:',
answers: [
{ quesContent: '<head>', correct: false},
{ quesContent: '<heading>', correct: false},
{ quesContent: '<h1>', correct: true},
{ quesContent: '<h6>', correct: false},
],
},
{
question: '3. Which of the following characters indicate closing of a tag?',
answers: [
{ quesContent: '.', correct: false},
{ quesContent: '/', correct: true},
{ quesContent: '\\', correct: false},
{ quesContent: '!', correct: false},
],
},
{
question: '4. Which of the following attributes is used to add link to any element?',
answers: [
{ quesContent: 'href', correct: true},
{ quesContent: 'ref', correct: false},
{ quesContent: 'link', correct: false},
{ quesContent: 'newref', correct: false},
],
},
{
question: '5. What is CSS?',
answers: [
{ quesContent: 'Computer Style Sheets', correct: false},
{ quesContent: 'Colorful Style Sheets', correct: false},
{ quesContent: 'Creative Style Sheets', correct: false},
{ quesContent: 'Cascading Style Sheets', correct: true},
],
},
{
question: '6. The # symbol specifies that the selector is?',
answers: [
{ quesContent: 'class', correct: false},
{ quesContent: 'tag', correct: false},
{ quesContent: 'id', correct: true},
{ quesContent: 'first', correct: false},
],
},
{
question: '7. How do you change the text color of an element?',
answers: [
{ quesContent: 'text-color=', correct: false},
{ quesContent: 'color: ', correct: true},
{ quesContent: 'background-color: ', correct: false},
{ quesContent: 'text-color: ', correct: false},
],
},
{
question: '8. What is the correct JavaScript syntax to write "Hello World"?',
answers: [
{ quesContent: 'system.out.println("Hello World)', correct: false},
{ quesContent: 'println("Hello World")', correct: false},
{ quesContent: 'document.write("Hello World)', correct: true},
{ quesContent: 'response.write("Hello World")', correct: false},
],
},
{
question: '9. Using _______ statement is how you test for a specific condition.',
answers: [
{ quesContent: 'select', correct: false},
{ quesContent: 'if', correct: true},
{ quesContent: 'switch', correct: false},
{ quesContent: 'for', correct: false},
],
},
{
question: '10. Which of these is not a logical operator?',
answers: [
{ quesContent: '!', correct: false},
{ quesContent: '&', correct: true},
{ quesContent: '&&', correct: false},
{ quesContent: '||', correct: false},
],
},
]
// All buttons
const startButton = document.getElementById("startBtn");
const nextButton = document.getElementById("nextBtn");
const submitButton = document.getElementById("submitBtn");
const homeButton = document.getElementById("homeBtn");
// Instruction, questionDisplay, questions, showscore, score, answers, result, time, finish quiz, final score, remaining time, user name
const instruction = document.getElementById("instruction");
const questionDisplay = document.getElementById("questionDisplay");
const questionElement = document.getElementById('question');
const answerElement = document.getElementById('answer');
const showResult = document.getElementById('showResult');
const showScoreBar = document.getElementById('showScore');
const scoreElement = document.getElementById('score');
const timeElement = document.getElementById('timeCount');
const finishQuiz = document.getElementById('finishQuiz');
const finalScore = document.getElementById('finalScore');
const remainTime = document.getElementById('remainTime');
const userName = document.getElementById('userName');
// Declare global variables current question, score, second, time
let currentIndex, score, second, time;
let tableElem = document.createElement('table');
// When start button is clicked
startButton.addEventListener('click', startQuiz);
// When next button is clicked
nextButton.addEventListener('click', nextQuestion);
// When submit button is clicked
submitButton.addEventListener('click', function(){
event.preventDefault();
// Replace submit button by home button
submitButton.classList.add('hide');
homeButton.classList.remove('hide');
// Passing an objective of score and time to submitScore function
submitScore({
Username: userName.value,
Score: score,
RemainingTime: second
})
});
// When home button is clicked
homeButton.addEventListener('click', function(){
// Show start button and instruction again
startButton.classList.remove('hide');
instruction.classList.remove('hide');
// Hide home button and score board
homeButton.classList.add('hide');
finishQuiz.classList.add('hide');
// Remove the leader board
tableElem.parentNode.removeChild(tableElem);
// Make sure time is back to 100 when play again
second = 100;
timeElement.textContent = second;
resetQuestionBody();
})
function nextQuestion()
{
if(currentIndex < question.length - 1)
{
currentIndex++;
showResult.classList.add('hide');
resetQuestionBody();
showQuestion();
}
else
endQuiz();
}
function startQuiz()
{
// Hide instructions and start button
instruction.classList.add('hide');
startButton.classList.add('hide');
// Show question, score, next button
questionDisplay.classList.remove('hide');
showScoreBar.classList.remove('hide');
nextButton.classList.remove('hide');
// set index to first question, score to 0
currentIndex = 0;
score = 0;
second = 100;
// Make sure score is back to 0 start again
scoreElement.innerHTML = score;
// Call next question function
showQuestion();
startTimer();
}
function showQuestion()
{
// Get question at the current index
questionElement.textContent = question[currentIndex].question;
// Loop through question answers using forEach loop
// Then create a button for each answer
question[currentIndex].answers.forEach(x => {
const button = document.createElement('button')
button.innerText = x.quesContent;
button.classList.add('answerButton');
// Mark the true answer
if (x.correct) {
button.dataset.correct = x.correct;
}
button.addEventListener('click', selectAnswer);
answerElement.append(button);
})
}
function selectAnswer(x)
{
let selectedAnswer = x.target;
let correctAnswer = selectedAnswer.dataset.correct;
showResult.classList.remove('hide');
if(correctAnswer)
{
score++;
scoreElement.innerHTML = score;
showResult.innerHTML = "The answer is correct"
}
else
{
second -= 10;
showResult.innerHTML = "The answer is not correct";
}
// automatically go to next question after 1 seconds and end quiz if passed question 10th
setTimeout(() => {
if(second <= 0)
endQuiz();
else if(currentIndex < question.length)
nextQuestion();
else
endQuiz();
}, 1000);
}
// This function will remove the anwer buttons before go to next question
function resetQuestionBody()
{
while (answerElement.firstChild) {
answerElement.removeChild(answerElement.firstChild)
}
}
// Set timer
function startTimer()
{
// Count down 1 second
time = setInterval(() =>{
second--;
timeElement.textContent = second;
}, 1000)
}
// end quiz
function endQuiz()
{
// Stop timer
clearInterval(time);
// Hide questionDisplay and nextButton
questionDisplay.classList.add('hide');
showScoreBar.classList.add('hide');
showResult.classList.add('hide');
nextButton.classList.add('hide');
// Show score board and submit button
finishQuiz.classList.remove('hide');
submitButton.classList.remove('hide');
// Output final score and time
finalScore.textContent = score;
remainTime.textContent = second;
}
// When submit button is clicked, score is submited
function submitScore(submission)
{
// Get the array from the storage, set to empty array if there is nothing
let leaderBoard = JSON.parse(localStorage.getItem('leaderBoard')) || [];
// Add new input user name and info. to array
leaderBoard.push(submission);
// Put into storage
localStorage.setItem('leaderBoard', JSON.stringify(leaderBoard));
// Sort the array by score
leaderBoard.sort(function(a, b){
return b.score - a.score;
});
// Create a table to display leader board
// tableElem = document.createElement('table');
tableElem.classList.add('customTable');
tableElem.innerHTML = `
<thead class="bodyText tableHead">
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Score</th>
<th scope="col">Time Left</th>
</tr>
</thead>
`;
let bodyElem = document.createElement('tbody');
bodyElem.classList.add('customTable');
for (let i = 0; i < leaderBoard.length; i++) {
let rowElem = document.createElement('tr')
rowElem.innerHTML = `
<th scope="row">${i + 1}</th>
<td>${leaderBoard[i].Username}</td>
<td>${leaderBoard[i].Score}</td>
<td>${leaderBoard[i].RemainingTime}s</td>
`;
bodyElem.append(rowElem);
}
tableElem.append(bodyElem);
document.getElementById('container').append(tableElem);
}
<file_sep>/README.md
# Coding Quiz
## Welcome to my Coding Quiz Challenge
### This is a basic coding quiz about HTML, CSS, and Javascript
- There are 10 questions and limit time is 100 seconds.
- Everytime you get an incorrect answer, the time will be reduced by 10 seconds.
- You can click on "Next" button to go to next question without answering, you will receive 0 point and the time will not be reduced.
- You cannot go back to the previous question.
- You will know you get the right or wrong answer after choosing an answer.
- After finishing 10th question,it will show:
- Your score on the scale of 10.
- The remaining time you have.
- Ask you to enter your name.
- When you have submitted your name and score, a board with names, scores, and times of other users that done the quiz before will show up.
- You can do the quiz again by clicking the "Back to Home Screen" button.
Website link: https://bnguyen467.github.io/code-quiz/

|
a4087ff4c16f784c5b6c3d71911e33c5a1c07304
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
bnguyen467/code-quiz
|
80c7b2e02bebf909a2309c7419d9765acbb18192
|
d11daee981d50abe41f2f1e3ded67ff6a92b191e
|
refs/heads/master
|
<repo_name>Artery/Portfolio<file_sep>/HotKeySystem/HotKeySystem example/Commands/ProjectCommands/CreateHotKeyListTempFileCommand.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows;
using HotKeySystem_example.Utility;
using log4net;
using HotKeySystem_example.ViewModels;
namespace HotKeySystem_example.Commands.ProjectCommands
{
public class CreateHotKeyListTempFileCommand : CommandBase
{
private readonly HelpWindowViewModel m_HelpWindowViewModel;
private static bool s_HotKeyListCreated = false;
private static bool s_fileNameCreated = false;
private static string s_fileExtension = ".txt";
private static string s_fileName = "HotKeyList" + s_fileExtension;
public CreateHotKeyListTempFileCommand(HelpWindowViewModel helpWindowViewModel)
{
if (!s_fileNameCreated)
{
GenerateFileName();
}
m_HelpWindowViewModel = helpWindowViewModel;
}
private static void GenerateFileName()
{
var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
if (assemblyPath == null)
{
s_fileName = Path.GetTempPath() + s_fileName;
}
else
{
var uri = new Uri(assemblyPath);
assemblyPath = uri.LocalPath;
s_fileName = assemblyPath + "\\" + s_fileName;
}
s_fileNameCreated = true;
}
public override void Execute(object parameter)
{
var logger = LogManager.GetLogger("CreateHotKeyListTempFileCommand");
string errorMessage = String.Empty;
bool errorOccured = false;
if (!CreateHotKeyListFile(logger))
{
errorMessage += "Fehler beim Erstellen der " + s_fileName + "!\n";
errorOccured = true;
}
if (!OpenHotKeyListInTxtEditor(logger))
{
if (!File.Exists(s_fileName))
{
s_HotKeyListCreated = false;
}
errorMessage += "Fehler beim Öffnen der " + s_fileName + "!\n";
errorOccured = true;
}
if (errorOccured)
{
errorMessage += "Bitte versuchen Sie es erneut!";
MessageBoxResult result = MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private bool CreateHotKeyListFile(ILog logger)
{
if (!s_HotKeyListCreated)
{
try
{
System.IO.File.Delete(s_fileName);
string fileContent = GenerateHotKeyListFileContent();
System.IO.File.WriteAllText(@s_fileName, fileContent);
logger.Info("Generated new " + s_fileName);
s_HotKeyListCreated = true;
}
catch (Exception)
{
logger.Error("Failed generating new " + s_fileName);
return false;
}
}
return true;
}
private static bool OpenHotKeyListInTxtEditor(ILog logger)
{
try
{
if (!s_HotKeyListCreated)
{
throw new Exception();
}
Process.Start(@s_fileName);
}
catch (Exception)
{
logger.Error("Failed to open " + s_fileName);
return false;
}
return true;
}
public override bool CanExecute(object parameter)
{
return true;
}
private string GenerateHotKeyListFileContent()
{
string fileContent = "HotKeySystem example - Tastenkürzel";
var Tabs = m_HelpWindowViewModel.Tabs;
Tabs.MoveCurrentToFirst();
do
{
fileContent += "\n\n";
var tab = (HelpWindowViewModel.HotKeyCategoryTab) Tabs.CurrentItem;
fileContent += tab.Header + "\n\n";
var hotkeys = tab.HotKeys;
string fullTabString = String.Empty;
hotkeys.MoveCurrentToFirst();
do
{
var hotkey = hotkeys.CurrentItem as HelpWindowViewModel.HotKeyInfo;
fullTabString += "\t" +
string.Format(
"{0,-" + (m_HelpWindowViewModel.HotKeyDisplayStringMaxLength + 5).ToString() +
"}",
hotkey.DisplayString) + hotkey.Description + "\n";
} while (hotkeys.MoveCurrentToNext());
hotkeys.MoveCurrentToFirst();
fileContent += fullTabString;
} while (Tabs.MoveCurrentToNext());
Tabs.MoveCurrentToFirst();
return fileContent;
}
public static bool HotKeyListCreated
{
get
{
return s_HotKeyListCreated;
}
}
}
}<file_sep>/Code snippets/ChangeLayerOrderCommand.cs
using System;
using System.Linq;
//Code snippet from another project
//This command moves items of a ListBox (WPF-App)
//The ListBox has a Collection of Layers (items), a layer can be active or inactive, which indicates if it is visible in the ListBox
//The ZValue determines the position in the ListBox (descending order), 1 ist the lowest item
//The method is generalized to support increasing and decreasing with the same code
//I really liked the way how I generalized the problem to reuse the same code
public class ChangeLayerOrderCommand
{
//True will lead to increasing, false to decreasing order
public void Execute(bool increaseLayerOrder)
{
var selectedLayer = Project.SelectedLayer;
var showInactiveLayers = Project.ShowInactiveLayers;
var layers = Project.Layers;
var orderedLayers = increaseLayerOrder ? layers.OrderBy(l => l.ZValue) : layers.OrderByDescending(l => l.ZValue);
//Delegate to compare two ints
Func<int, int, bool, bool> compareValues = (lhs, rhs, greater) => greater ? lhs > rhs : lhs < rhs;
var lastLayerToSwap = orderedLayers.FirstOrDefault(l => compareValues(l.ZValue, selectedLayer.ZValue, increaseLayerOrder)
&& (l.IsActive || showInactiveLayers));
//If inactive layers are not visible, they will be "skipped" when moving down the selected layer
//But when the selected layer is the last visible layer it will not be moved beneath lower inactive layers and vice versa for moving upwards
/* Example1:
* before moving l1 downwards after moving l1
* l1 (active, selected layer) l2 (inactive)
* l2 (inactive) l3 (inactive)
* l3 (inactive) l4 (active)
* l4 (active) (lastLayerToSwap) l1 (active, selected layer)
*
* Example2:
* before moving l1 downwards after moving l1
* l4 (active) l4 (active)
* l1 (active, selected layer) l1 (active, selected layer)
* l2 (inactive) l3 (inactive)
* lastLayerToSwap is null in this case
*/
//And vice versa for moving upwards
//If inactive layers visible, they will be treated like active layers
if (lastLayerToSwap != null || showInactiveLayers)
{
var zValues = layers.Select(l => l.ZValue).DefaultIfEmpty(0);
var fallbackZValueBound = increaseLayerOrder ? zValues.Max() + 1 : zValues.Min() - 1;
var zValueBound = lastLayerToSwap != null ? lastLayerToSwap.ZValue : fallbackZValueBound;
var nextInactiveLayers = orderedLayers.Where(l => !l.IsActive
&& compareValues(l.ZValue, selectedLayer.ZValue, increaseLayerOrder)
&& compareValues(zValueBound, l.ZValue, increaseLayerOrder)).ToList();
foreach (var layer in nextInactiveLayers)
{
if (increaseLayerOrder) { SwapZValues(layer, selectedLayer); }
else { SwapZValues(selectedLayer, layer); }
}
if (lastLayerToSwap != null)
{
if (increaseLayerOrder) { SwapZValues(lastLayerToSwap, selectedLayer); }
else { SwapZValues(selectedLayer, lastLayerToSwap); }
}
}
if (Project.SynchronizeSelectedLayer)
{
Project.UpdateLayers();
}
}
private static void SwapZValues(MapLayerViewModel layer1, MapLayerViewModel layer2)
{
int z = layer1.ZValue;
layer1.ZValue = layer2.ZValue;
layer2.ZValue = z;
}
}
<file_sep>/Code snippets/SQL_OpenGeoDB_Bundesland-rekursiv.sql
/*
Das untenstehende Beispiel ist eine SQL-Abfrage auf die OpenGeoDB (http://opengeodb.org), welche verschiedene Daten aller gespeicherten Deutschen Städte anzeigen sollen, inklusive des zugehörigem Bundeslandes.
Die OpenGeoDB hat eine offene, modulare und hierarische Struktur (siehe http://opengeodb.org/wiki/Datenbank), dadurch ist es etwas kniffilig an die Bundesland Information heranzukommen.
Das untenstehende rekursive SQL-Statement ist nicht super komplex, aber es hat mich einige Zeit gekostet eine korrekte Lösung zu finden, welche das gewünschte Ergebnis liefert.
Die Sturktur der OpenGeoDB ist, dass eine Location aus einer ID und einem Type besteht. Eine Location kann eine Stadt, ein Bundesland oder auch ein Ort sein, wie z.B. das Marine-Ehrenmal von Laboe.
Eine Location kann nun modular aus vielen verschiedenen Daten wie z.B. der Einwohnerzahl als Integer-Wert oder einem Namen als Text bestehen.
Die hierarische Struktur der einzelnen Orte wird durch die sogenannten Ebenen/Layer festgelegt, dabei hat jede Layer-Tiefe einen bestimmten Zweck,
z.B. Layer 100200000 ist ein Staat, Layer 1007000000 dagegen ist eine Ortschaft. Damit ist jede Location "TeilVon" einer anderen Location, aber die Layer sind nicht zwangsläufig durchgängig.
Z.B. nicht jede Ortschaft untersteht einer politischen Gliederung und nicht jeder Landkreis untersteht einem Regierungsbezirk. (http://opengeodb.org/wiki/Types)
Auch können bestimmte Locations mehrfach vertreten sein z.B. die Stadt Berlin ist sowohl eine Ortschaft als auch ein Bundesland.
All diese Besonderheiten gab es zu beachten, beim durchgehen der einzelnen Ebenen, um zu jedem Ort auch sein passendes Bundesland zu finden.
*/
--id ist die ID des Bundeslandes, layer die Ebene des Bundeslandes und originid die ID des ursprünglichen Ortes
with GetUpperLayers(id, layer, originid) as
(
(
--Anchor
--Es wird gleich mit der überliegenden Ebene gestartet, deswegen werden alle Layer zwischen Postleitzahlgebiet und Landkreis selektiert,
--um sich so schon gleich einen Schritt zu sparen.
SELECT td_id.text_val, td_layer.text_val, td_id.loc_id
FROM geodb_textdata AS td_id, geodb_textdata AS td_layer
WHERE
td_layer.loc_id = td_id.text_val
AND td_id.text_type = 400100000
AND td_layer.text_type = 400200000
AND td_layer.text_val BETWEEN 5 AND 8
)
UNION ALL
(
--Recursive member
--Nun wird sich rekursiv immer weiter an der "TeilVon"-Eigenschaft hochgehangelt.
--Dabei müssen aber auch alle Fälle behandelt werden, bei denen z.B. ein Layer übersprungen wird,
--weil z.B. ein ursprünglicher Ort gar nicht Teil eines Regierungsbezirks ist
--Das heißt manche Orte werden früher schon ihr zugehöriges Bundesland erreichen als andere
SELECT td_teilvon.text_val, td_layer.text_val, upl.originid
FROM GetUpperLayers upl, geodb_textdata td_teilvon, geodb_textdata td_layer
WHERE
td_teilvon.loc_id = upl.id
AND td_teilvon.text_type = 400100000
AND td_layer.text_type = 400200000
AND td_layer.text_val >= 3
AND td_layer.loc_id = td_teilvon.text_val
)
),
--Hier werden nur noch die relevanten Informationen selektiert
GetBundeslandIDName(originid, bland_name, layer) as
(
SELECT upl.originid, bland_name.text_val, upl.layer
FROM GetUpperLayers AS upl LEFT JOIN geodb_textdata AS bland_name
ON upl.id = bland_name.loc_id
WHERE upl.layer = 3 AND bland_name.text_type = 500100000
)
--Große gesamt Abfrage
SELECT gtv.loc_id AS LocationId, plz.text_val AS Plz, name.text_val AS Name,
typ.text_val AS Typ, telv.text_val AS Vorwahl, einw.int_val AS EinwohnerAnzahl, gbidn.name AS Bundesland
FROM dbo.geodb_textdata AS gtv LEFT OUTER JOIN
dbo.geodb_textdata AS name ON gtv.loc_id = name.loc_id LEFT OUTER JOIN
dbo.geodb_textdata AS typ ON gtv.loc_id = typ.loc_id LEFT OUTER JOIN
dbo.geodb_textdata AS plz ON gtv.loc_id = plz.loc_id LEFT OUTER JOIN
dbo.geodb_textdata AS telv ON gtv.loc_id = telv.loc_id LEFT OUTER JOIN
dbo.geodb_intdata AS einw ON gtv.loc_id = einw.loc_id LEFT OUTER JOIN
dbo.geodb_locations AS loc ON gtv.loc_id = loc.loc_id LEFT OUTER JOIN
GetBundeslandIDName AS gbidn ON loc.loc_id = gbidn.originid
WHERE (name.text_type = 500100000) AND (plz.text_type = 500300000) AND (typ.text_type = 400300000)
AND (telv.text_type = 500400000) AND (einw.int_type = 600700000) AND (gtv.text_type = 400100000)
ORDER BY name<file_sep>/HotKeySystem/HotKeySystem example/Utility/ShowDialogCommand.cs
using System;
using System.Windows;
namespace HotKeySystem_example.Utility
{
[Serializable]
public class ShowDialogCommand<T> : CommandBase where T : Window, new()
{
public ShowDialogCommand()
{
}
public ShowDialogCommand(object dataContext)
{
DataContext = dataContext;
}
public object DataContext { get; set; }
public bool? DialogResult { get; set; }
public override bool CanExecute(object parameter)
{
return true;
}
public override void Execute(object parameter)
{
var window = Find();
if (window == null)
{
window = new T();
}
window.Owner = Application.Current.MainWindow;
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
if (DataContext != null)
{
window.DataContext = DataContext;
}
if (window.IsLoaded)
{
window.Activate();
}
else
{
DialogResult = window.ShowDialog();
}
}
protected Window Find()
{
foreach (Window window in Application.Current.Windows)
{
if (window is T)
{
return window;
}
}
var window1 = new T();
return window1;
}
}
}<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/HotKeyProviderBase.cs
using log4net;
using System;
using System.Linq;
namespace HotKeySystem_example.HotKeySystem
{
//Provider class for creating, storing and providing HotKeys
public abstract class HotKeyProviderBase
{
//Enum to specify LoggerWarnMessage
protected enum DefaultReturnTypes { NULL = 0, DEFAULT_GESTURE };
protected HotKeyList<HotKeyBase> m_HotKeys = new HotKeyList<HotKeyBase>();
public virtual HotKeyList<HotKeyBase> HotKeys
{
get { return m_HotKeys; }
}
//Returns exisiting hotkey, otherwise tries to create new one
public virtual T GetHotKey<T>(Type commandType)
where T : HotKeyBase, new()
{
var hotkey = m_HotKeys.FirstOrDefault(item => item.CommandType.Equals(commandType) && item is T) as T
?? CreateHotKey<T>(commandType) as T;
ValidateHotKey(commandType, hotkey);
return hotkey;
}
//Returns a list of existing hotkeys for the same commandType, otherwise tries to create it
public virtual List<T> GetHotKeys<T>(Type commandType)
where T : HotKeyBase, new()
{
var hotkeys = m_HotKeys.Where(item => item.CommandType.Equals(commandType) && item is T).Select(hotkey => hotkey as T).ToList();
if (hotkeys.Count == 0)
{
hotkeys = CreateMultipleHotKeys<T>(commandType);
}
foreach (var hotkey in hotkeys)
{
if (hotkey == null)
{
ValidateHotKey(commandType, hotkey);
}
}
return hotkeys;
}
//Checks if a hotkey is valid or null, throws ArgumentNullException if null
protected virtual void ValidateHotKey<T>(Type commandType, T hotkey)
{
if (hotkey == null)
{
throw new ArgumentNullException("HotKeyProviderBase - GetHotKey<"
+ typeof(T).FullName + ">(" + commandType.FullName
+ "): Fetching hotkey from internal List or trying to create it resulted in null argument!");
}
}
//Returns exisiting hotkey, otherwise tries to create new one or returns default-value null
public virtual T GetHotKeyOrNull<T>(Type commandType)
where T : HotKeyBase, new()
{
return TryGetHotKey<T>(commandType, DefaultReturnTypes.NULL);
}
//Returns exisiting hotkey, otherwise tries to create new one or returns default-gesture 'None'
public virtual T GetHotKeyOrDefault<T>(Type commandType)
where T : HotKeyBase, new()
{
return TryGetHotKey<T>(commandType, DefaultReturnTypes.DEFAULT_GESTURE) ?? new T();
}
protected virtual T TryGetHotKey<T>(Type commandType, DefaultReturnTypes defaultReturnType)
where T : HotKeyBase, new()
{
T hotkey = null;
try
{
hotkey = GetHotKey<T>(commandType);
}
catch (Exception e)
{
LogManager.GetLogger("HotKeyProviderBase").Warn(
GetWarnMessage("TryGetHotKey", commandType, typeof(T), e.Message)
+ "\n"
+ GetDefaultTypeMessage(defaultReturnType));
}
return hotkey;
}
protected virtual string GetWarnMessage(string subMethodName, Type commandType, Type hotkeyType, string ExceptionMessage)
{
return "HotKeyProviderBase - " + subMethodName + ": Could not create HotKey of Type " + hotkeyType.FullName
+ " and for CommandType: " + commandType.FullName
+ "\nInnerExceptionMessage: " + ExceptionMessage;
}
protected virtual string GetDefaultTypeMessage(DefaultReturnTypes defaultReturnType)
{
var defaultTypeMessage = "Returning ";
//For more specified log-message
switch (defaultReturnType)
{
case DefaultReturnTypes.NULL:
defaultTypeMessage += "null";
break;
case DefaultReturnTypes.DEFAULT_GESTURE:
defaultTypeMessage += "default('none')-gesture";
break;
default:
defaultTypeMessage += defaultReturnType.ToString();
break;
}
return defaultTypeMessage;
}
protected abstract T CreateHotKey<T>(Type commandType) where T : HotKeyBase, new();
protected abstract List<T> CreateMultipleHotKeys<T>(Type commandType) where T : HotKeyBase, new();
}
}
<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/HotKeyLocalizer.cs
using System;
namespace HotKeySystem_example.HotKeySystem
{
//Provides simple and primitive localization for HotKeys
public static class HotKeyLocalizer
{
public static string LocalizeDisplayString(string displayString)
{
//+ is the delimiter for composite shortcuts like Control+S
//; is the delimiter for Commands with multiple hotkeys
var displayStringParts = displayString.Split(new string[] { "+", ";" }, StringSplitOptions.RemoveEmptyEntries);
//Replace all substrings which could be localized
foreach (string substring in displayStringParts)
{
var localizedString = Properties.LocalizedKeyNames.ResourceManager.GetString(substring);
if(localizedString != null)
{
displayString = displayString.Replace(substring, localizedString);
}
}
return displayString;
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/HotKeys/MouseHotKey.cs
using System;
using System.Windows.Input;
namespace HotKeySystem_example.HotKeySystem
{
//HotKey-class for a MouseGesture-HotKey
public class MouseHotKey : HotKeyBase
{
protected static readonly MouseGestureConverter s_MouseConverter = new MouseGestureConverter();
protected MouseGesture m_MouseGesture;
public MouseHotKey()
{
new MouseGesture(MouseAction.None);
}
public MouseHotKey(HotKeyConfig config)
: this(config.CommandType, config.hotkeyGestureString, config.Description)
{
}
public MouseHotKey(Type commandType, string hotkeyGestureString, string description)
{
CommandType = commandType;
Description = description;
MouseGesture = CreateGestureFromString<MouseGesture>(hotkeyGestureString);
HotKeyDisplayString = GetDisplayStringFromGesture(MouseGesture);
}
public MouseHotKey(Type commandType, MouseGesture mouseGesture, string description)
{
CommandType = commandType;
Description = description;
MouseGesture = mouseGesture;
HotKeyDisplayString = GetDisplayStringFromGesture(m_MouseGesture);
}
public virtual MouseGesture MouseGesture { get; set; }
public virtual string GetDisplayStringFromGesture(MouseGesture gesture)
{
//There is no build-in "GetDisplayString"-Method, so the displayString needs to be composed
var displayString = gesture.MouseAction.ToString();
if(!gesture.Modifiers.ToString().Equals(ModifierKeys.None))
{
displayString = gesture.Modifiers.ToString() + "+" + displayString;
}
return displayString;
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/HotKeyProvider.cs
using System;
namespace HotKeySystem_example.HotKeySystem
{
//Specified HotKeyProvider
public class HotKeyProvider : HotKeyProviderBase
{
//Singleton-Pattern based on MapInputTracker
#region Singleton
public static HotKeyProvider Instance
{
get { return Nested.Instance; }
}
// ReSharper disable ClassNeverInstantiated.Local
private class Nested
{
internal static readonly HotKeyProvider Instance = new HotKeyProvider();
}
#endregion
//Fetches the gestureString from HotKeySettings (part of the app.config)
protected string FetchGestureString<T>(Type commandType)
where T : HotKeyBase, new()
{
var commandName = commandType.Name;
var typeName = typeof(T).Name;
//Fetch hotkey data from resource and config files
string hotkeyGestureString = null;
try
{
hotkeyGestureString = Properties.HotKeySettings.Default[commandName + typeName] as string;
}
catch (Exception)
{
throw new HotKeyNotDeclaredException("MapEditorHotKeyProvider - CreateHotKey<"
+ typeName + ">(" + commandName
+ "): Requested HotKey is not declared in HotKeySettings/App.config!");
}
return hotkeyGestureString;
}
//Fetches the description from HotKeysDescriptions (part of the app.config)
protected string FetchDescription<T>(Type commandType)
where T : HotKeyBase, new()
{
return Properties.HotKeysDescriptions.ResourceManager.GetString(commandType.Name) ?? String.Empty;
}
//Create a single HotKey
protected override T CreateHotKey<T>(Type commandType)
{
var description = FetchDescription<T>(commandType);
var hotkeyGestureString = FetchGestureString<T>(commandType);
return InternCreateHotKey<T>(commandType, hotkeyGestureString, description);
}
//Create multiple (list) of hotkeys
protected override List<T> CreateMultipleHotKeys<T>(Type commandType)
{
var description = FetchDescription<T>(commandType);
//Delimiter is hardcoded, another approach should be considered!
var hotkeyGestureStrings = FetchGestureString<T>(commandType).Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
List<T> hotkeys = new List<T>();
foreach (var gestureString in hotkeyGestureStrings)
{
hotkeys.Add(InternCreateHotKey<T>(commandType, gestureString, description));
}
return hotkeys;
}
//Method that actually creates a hotkey
protected T InternCreateHotKey<T>(Type commandType, string hotkeyGestureString, string description)
where T : HotKeyBase, new()
{
//Create new hotkey
var newHotKey = HotKeyAdapter.GetNewHotKey<T>(new HotKeyConfig(commandType, hotkeyGestureString, description));
if (newHotKey != null)
{
//Localize DisplayString of new hotkey
newHotKey.HotKeyDisplayString = HotKeyLocalizer.LocalizeDisplayString(newHotKey.HotKeyDisplayString);
m_HotKeys.Add(newHotKey);
}
return newHotKey;
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/HotKeys/HotKeyBase.cs
using System;
using System.Windows.Input;
namespace HotKeySystem_example.HotKeySystem
{
//Base class for a HotKey, which is linked to a specific command
public abstract class HotKeyBase
{
//Type of the linked command
public virtual Type CommandType { get; set; }
//Displayed shortcut e.g.: 'Ctrl+A' or 'Umschalttaste+Linksklick'
public virtual string HotKeyDisplayString { get; set; }
//Description what the HotKeyNEW does e.g.: 'Close current project'
public virtual string Description { get; set; }
public virtual string Tooltip
{
get { return Description + " (" + HotKeyDisplayString + ")"; }
}
public virtual T CreateGestureFromString<T>(string gestureString)
where T : InputGesture
{
return GestureConverterAdapter.GetGestureConverter(typeof(T)).ConvertFromString(gestureString) as T;
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/ViewModels/MainWindowViewModel.cs
using HotKeySystem_example.Commands.ProjectCommands;
using HotKeySystem_example.Commands.WindowCommands;
using System.ComponentModel;
using System.Windows;
namespace HotKeySystem_example.ViewModels
{
public class MainWindowViewModel : INotifyPropertyChanged
{
private readonly ShowHelpCommand m_ShowHelp;
private readonly FancyBegruessungCommand m_FancyBegruessung;
private Visibility m_FancyBegruessungVisibility;
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
public MainWindowViewModel()
{
m_ShowHelp = new ShowHelpCommand();
m_FancyBegruessung = new FancyBegruessungCommand(this);
m_FancyBegruessungVisibility = Visibility.Hidden;
}
public ShowHelpCommand ShowHelp
{
get { return m_ShowHelp; }
}
public FancyBegruessungCommand FancyBegruessung
{
get { return m_FancyBegruessung; }
}
public Visibility FancyBegruessungVisibility
{
get { return m_FancyBegruessungVisibility; }
set
{
if (m_FancyBegruessungVisibility != value)
{
m_FancyBegruessungVisibility = value;
OnPropertyChanged("FancyBegruessungVisibility");
}
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/Exceptions/HotKeyNotDeclaredException.cs
using System;
namespace HotKeySystem_example.HotKeySystem
{
public class HotKeyNotDeclaredException : Exception
{
public HotKeyNotDeclaredException()
:base()
{
}
public HotKeyNotDeclaredException(string message)
:base(message)
{
}
public HotKeyNotDeclaredException(string message, Exception innerException)
:base(message, innerException)
{
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/Commands/WindowCommands/ShowHelpCommand.cs
using HotKeySystem_example.HotKeySystem;
using HotKeySystem_example.Utility;
using HotKeySystem_example.ViewModels;
using HotKeySystem_example.Windows;
namespace HotKeySystem_example.Commands.WindowCommands
{
public class ShowHelpCommand : ShowDialogCommand<HelpWindow>
{
private KeyHotKey m_KeyHotKey;
public KeyHotKey KeyHotKey
{
get { return m_KeyHotKey; }
set { m_KeyHotKey = value; }
}
public ShowHelpCommand()
: base(new HelpWindowViewModel())
{
m_KeyHotKey = HotKeyProvider.Instance.GetHotKeyOrDefault<KeyHotKey>(this.GetType());
}
}
}<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/AdapterClasses/GestureConverterAdapter.cs
using System;
using System.ComponentModel;
using System.Windows.Input;
namespace HotKeySystem_example.HotKeySystem
{
//Adapter-class for GestureConverters to provide GestureConverter-object for specific HotKey-Types
public static class GestureConverterAdapter
{
public static TypeConverter GetGestureConverter(Type gestureType)
{
TypeConverter typeConverter = null;
if (gestureType.Equals(typeof(KeyGesture)))
{
typeConverter = new KeyGestureConverter();
}
else if (gestureType.Equals(typeof(MouseGesture)))
{
typeConverter = new MouseGestureConverter();
}
else
{
throw new NotImplementedException("GestureConverterAdapter could not provide requested GestureConverter for Gesture-Type: " + gestureType.FullName);
}
return typeConverter;
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/HelperClasses/HotKeyConfig.cs
using System;
namespace HotKeySystem_example.HotKeySystem
{
//Initializer-class for HotKeys
public class HotKeyConfig
{
public Type CommandType { get; set; }
public string Description { get; set; }
public string hotkeyGestureString { get; set; }
public HotKeyConfig(Type commandType, string hotkeyGestureString, string description)
{
this.CommandType = commandType;
this.Description = description;
this.hotkeyGestureString = hotkeyGestureString;
}
}
}
<file_sep>/Code snippets/Ruby_Array_Merging.rb
=begin
Folgende Annahme:
Es existiert eine unbestimmte Anzahl von Assets (technischen Anlagen). Jedes dieser Assets besteht aus 1 bis n Sub-Assets.
Jedes Sub-Asset hat entweder 1 ODER 4 verschiedene Zeitreihen, welche Auskunft über verschiedene technische Informationen geben, in Form von float-Werten.
Die untenstehende Methode soll ein 1D-float-Array zurückgeben, in dem für ein Asset pro Zeitschritt ein Wert enthalten ist.
Wird zum Beispiel ein Zeitraum betrachtet, welcher 5 Zeitschritte lang ist, dann könnte eine mögliche Rückgabe folgendermaßen aussehen: [1.0, 2.0, 3.0, 4.0, 5.0]
Es können folgende 3 Fälle eintreten:
1. Für den Fall, dass ein Asset nur aus einem Sub-Asset besteht und dieses nur 1 Zeitreihe besitzt, kann diese einfach zurückgeben werden.
2. Für den Fall, dass ein Asset nur aus einem Sub-Asset besteht und dieses 4 Zeitreihen besitzt, müssen diese Zeitreihen zu einer "kombiniert" werden.
3. Für den Fall, dass ein Asset aus mehreren Sub-Assets besteht und diese jeweils 4 Zeitreihen besitzen, müssen die Zeitreihen zu einer pro Sub-Asset und
anschließend zu einer "gesamt" Zeitreihe "kombiniert" werden
Die Herausforderung an diesem Problem war, dass es festgelegt war, wie die Zeitreihen-Daten übergeben werden (1D-float-Array) und wie der Output aussehen soll (ebenfalls 1D-float-Array).
Die Werte aus dem 1D-float-Array mussten nun möglichst effektiv und kompakt kombiniert werden.
Die ganze Methode ist recht kompliziert im Detail, was ein Manko ist. Aber ich finde sie ist eine ziemlich coole Variante mit relativ wenigen Zeilen ans Ziel zu kommen,
was sie zu der kompaktesten Variante macht, die ich gefunden habe.
=end
#Methode kompakt, nur kurz kommentiert:
#Variante mit Beispielwerten und umfangreich kommentiert auf der nächsten Seite.
def self.build_pav_array(rts_identifier, from_time, to_time, extended_formular, num_sub_assets, time_series)
# Anfordern der Zeitreihen-Werte als 1D-float-Array
pav_array = DailyEvent.get_time_series_as_float(rts_identifier, from_time, to_time, time_series)
num_timestamps = pav_array.count / (num_sub_assets * time_series.count)
pav_array = pav_array.each_slice(num_timestamps).to_a
if extended_formular
# Kombinieren der Zeitreihen-Werte für jeden Zeitschritt zu einem Wert pro Zeitschritt und Sub-Asset
pav_array = pav_array.each_slice(time_series.count).to_a.
map{|ses_chunk, pav_chunk, avc_chunk, rl_chunk| pav_chunk.zip(rl_chunk, ses_chunk, avc_chunk).
map{|pav_element, rl_element, ses_element, avc_element| (pav_element + rl_element * ses_element ) * avc_element}}
end
# Zusammenfassen der Werte jedes Sub-Asset zu einem Wert pro Zeitschritt
return pav_array.transpose.map {|element| element.reduce(:+)}
end
#Das untenstehende Beispiel ist für den kompliziertesten Fall 3.
#Beispielhafte Werte:
# input: rts_identifier => "Asset1"
# from_time => t+0 (vereinfacht, normalerweise als Datetime z.B. 01.01.2016 00:00 +0100)
# to_time => t+2 (vereinfacht, normalerweise als Datetime z.B. 01.01.2016 00:03 +0100)
# extended_formular => true
# num_sub_assets => 2
# time_series => [SES, PAv, AvC, RL]
# output: [8.0, 8.2, 8.4]
def self.build_pav_array(rts_identifier, from_time, to_time, extended_formular, num_sub_assets, time_series)
# Anfordern der Daten als float-Array
# Die Daten kommen immer als ein großes 1D-Array zurück und sind nach Sub-Asset und nach Zeitreihen-Typ(beide absteigend) sortiert
# Die "Herausforderung" war es an dieser Stelle das Array "korrekt" zu bearbeiten, da die Daten nicht anders "beschafft" werden können
# SES, PAv, AvC und RL sind die Bezeichnungen der Zeitreihen, ihre Bedeutung ist nicht relevant für dieses Beispiel
pav_array = DailyEvent.get_time_series_as_float(rts_identifier, from_time, to_time, time_series)
# | Sub-Asset1 || Sub-Asset2 |
# |t+0 t+1 t+2| t+0 t+1 t+2| t+0 t+1 t+2| t+0 t+1 t+2||t+0 t+1 t+2| t+0 t+1 t+2| t+0 t+1 t+2| t+0 t+1 t+2|
# | SES | PAv | AvC | RL || SES | PAv | AvC | RL |
# => [0.0, 0.0, 0.0, 5.0, 5.1, 5.2, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 3.1, 3.2, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0]
# Zu Testzwecken einfach die obere Zeile auskommentieren und die Zeile unten benutzen:
# pav_array = [0.0, 0.0, 0.0, 5.0, 5.1, 5.2, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 3.1, 3.2, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0]
# Hier wird die Anzahl der Werte pro Zeitreihe ermittelt.
# Jede Zeitreihe hat zwar gleich viele Elemente, aber allein aus der from_time und to_time lässt sich die Anzahl nicht ablesen.
# Da die Auflösung der Zeitschritte unterschiedlich sein kann, z.B. minutenweise oder auch stundenweise (ein Wert pro Minute bzw. ein Wert pro Stunde)
num_timestamps = pav_array.count / (num_sub_assets * time_series.count)
# => 3
# Es wird nun jede Zeitreihe in einen eigenen Block/Chunk "zerschnitten"
# Da jede Zeitreihe in diesem Beispiel 3 Werte beinhaltet, werden 3er Blöcke/Chunks gebildet
pav_array = pav_array.each_slice(num_timestamps).to_a
# | Sub-Asset1 || Sub-Asset2 |
# |t+0 t+1 t+2| t+0 t+1 t+2 | t+0 t+1 t+2| t+0 t+1 t+2 || t+0 t+1 t+2| t+0 t+1 t+2 | t+0 t+1 t+2| t+0 t+1 t+2 |
# | SES | PAv | AvC | RL || SES | PAv | AvC | RL |
# => [[0.0, 0.0, 0.0], [5.0, 5.1, 5.2], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [3.0, 3.1, 3.2], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]
if extended_formular
# Nun werden die Zeitreihen-Chunks aufgeteilt in Chunks pro Sub-Asset
pav_array = pav_array.each_slice(time_series.count).to_a
# | Sub-Asset1 || Sub-Asset2 |
# |t+0 t+1 t+2| t+0 t+1 t+2 | t+0 t+1 t+2| t+0 t+1 t+2 || t+0 t+1 t+2 |t+0 t+1 t+2| t+0 t+1 t+2| t+0 t+1 t+2 |
# | SES | PAv | AvC | RL || SES | PAv | AvC | RL |
# => [[[0.0, 0.0, 0.0], [5.0, 5.1, 5.2], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0], [3.0, 3.1, 3.2], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]]
# Jetzt muss für jeden Zeitschritt ein Wert pro Sub-Asset errechnet werden
# Also in unserem Beispiel muss am Ende ein 2D-Array herauskommen
# Je ein Wert pro Zeitschritt und pro Sub-Asset also 2x3 Werte ([[5.0, 5.1, 5.2], [3.0, 3.1, 3.2]])
# Das Komplizierte hierbei ist, dass die Zeitreihen z.B. nicht einfach aufsummiert werden können,
# sondern mit einer speziellen Formel zusammen gerechnet werden müssen:
# Formel: (PAv + RL * SES) * AvC
# map ist ähnlich zu einer for-each-loop aus anderen Programmier-Sprachen
# Es werden nun zuerst "Zeitschritt-Chunks" gebildet, das bedeutet, je ein Wert aus jeder Zeitreihe eines Sub-Assets wird zu einem Chunk zusammengefasst
# Z.B. aus [[SES_1, SES_2], [PAv_1, PAv_2]], ... wird [[SES_1, PAv_1, ...], [SES_2, PAv_2, ...]]
# Die untenstehenden drei Code-Zeilen sind eine, sie wurden der übersichthalber mit Absätzen getrennt
pav_array = pav_array.map{|ses_chunk, pav_chunk, avc_chunk, rl_chunk| pav_chunk.
zip(rl_chunk, ses_chunk, avc_chunk).
# | Sub-Asset1 || Sub-Asset2 |
# | t+0 | | t+1 | | t+2 | || t+0 | | t+1 | | t+2 |
# |PAv, RL, SES, AvC| |PAv, RL, SES, AvC| |PAv, RL, SES, AvC| ||PAv, RL, SES, AvC| |PAv, RL, SES, AvC| |PAv, RL, SES, AvC||
# => [[[5.0, 0.0, 0.0, 1.0], [5.1, 0.0, 0.0, 1.0], [5.2, 0.0, 0.0, 1.0]], [[3.0, 0.0, 0.0, 1.0], [3.1, 0.0, 0.0, 1.0], [3.2, 0.0, 0.0, 1.0]]]
# Anschließend wird aus den 4 Werten eines "Zeitschritt-Chunks" ein einzelner Wert berechnet
map{|pav_element, rl_element, ses_element, avc_element| (pav_element + rl_element * ses_element ) * avc_element}}
# | Sub-Asset1 || Sub-Asset2 |
# |t+0 t+1 t+2 || t+0 t+1 t+2|
# | new PAv || new PAv |
# => [[5.0, 5.1, 5.2], [3.0, 3.1, 3.2]]
end
# Zu guter Letzt können die Werte der Sub-Assets einfach pro Zeitschritt aufsummiert werden
return pav_array.transpose.map {|element| element.reduce(:+)}
# | Sub-Asset1+Sub-Asset2 |
# |t+0 t+1 t+2 |
# | new PAv |
# => [8.0, 8.2, 8.4 ]
end<file_sep>/HotKeySystem/HotKeySystem example/Commands/ProjectCommands/FancyBegruessungCommand.cs
using HotKeySystem_example.HotKeySystem;
using HotKeySystem_example.Utility;
using HotKeySystem_example.ViewModels;
namespace HotKeySystem_example.Commands.ProjectCommands
{
public class FancyBegruessungCommand : CommandBase
{
private MainWindowViewModel m_ViewModel;
private KeyHotKey m_KeyHotKey;
public KeyHotKey KeyHotKey
{
get { return m_KeyHotKey; }
set { m_KeyHotKey = value; }
}
public FancyBegruessungCommand(MainWindowViewModel viewModel)
{
m_KeyHotKey = HotKeyProvider.Instance.GetHotKeyOrDefault<KeyHotKey>(this.GetType());
m_ViewModel = viewModel;
}
public override void Execute(object parameter)
{
m_ViewModel.FancyBegruessungVisibility = System.Windows.Visibility.Visible;
}
public override bool CanExecute(object parameter)
{
return true;
}
}
}<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/HotKeys/KeyHotKey.cs
using System;
using System.Globalization;
using System.Threading;
using System.Windows.Input;
namespace HotKeySystem_example.HotKeySystem
{
//HotKey-class for a KeyGesture-HotKey
public class KeyHotKey : HotKeyBase
{
//Converter to convert strings to KeyGestures
protected static readonly KeyGestureConverter s_KeyConverter = new KeyGestureConverter();
public KeyHotKey()
{
KeyGesture = new KeyGesture(Key.None);
}
public KeyHotKey(HotKeyConfig config)
: this(config.CommandType, config.hotkeyGestureString, config.Description)
{
}
public KeyHotKey(Type commandType, string hotkeyGestureString, string description)
{
CommandType = commandType;
Description = description;
KeyGesture = CreateGestureFromString<KeyGesture>(hotkeyGestureString);
HotKeyDisplayString = GetDisplayStringFromGesture(KeyGesture);
}
public KeyHotKey(Type commandType, KeyGesture keyGesture, string description)
{
CommandType = commandType;
Description = description;
KeyGesture = keyGesture;
HotKeyDisplayString = GetDisplayStringFromGesture(KeyGesture);
}
public virtual KeyGesture KeyGesture { get; set; }
public virtual string GetDisplayStringFromGesture(KeyGesture gesture, CultureInfo cultureInfo = null)
{
return gesture.GetDisplayStringForCulture(cultureInfo ?? Thread.CurrentThread.CurrentUICulture);
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/HelperClasses/HotKeyList.cs
using System.Collections.Generic;
namespace HotKeySystem_example.HotKeySystem
{
public class HotKeyList<T> : List<T> where T : HotKeyBase
{
public void AddIfNotNull(T item)
{
if(item != null)
{
Add(item);
}
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/ViewModels/HelpWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Data;
using System.Configuration;
using HotKeySystem_example.Commands.ProjectCommands;
using HotKeySystem_example.HotKeySystem;
namespace HotKeySystem_example.ViewModels
{
public class HelpWindowViewModel
{
//Package-Class for a specific hotkey-group-tab e.g. "Hilfe"
public class HotKeyCategoryTab
{
public HotKeyCategoryTab(string header, ICollectionView hotkeys)
{
Header = header;
HotKeys = hotkeys;
}
public string Header { get; set; }
public ICollectionView HotKeys { get; private set; }
}
public class HotKeyInfo
{
public HotKeyInfo(string displayString, string description)
{
DisplayString = displayString;
Description = description;
}
public string DisplayString {get; set;}
public string Description { get; set; }
}
public ICollectionView Tabs { get; private set; }
private readonly CreateHotKeyListTempFileCommand m_CreateHotKeyListTempFileCommand;
private int m_HotKeyDisplayStringMaxLength = 0;
public HelpWindowViewModel()
{
m_CreateHotKeyListTempFileCommand = new CreateHotKeyListTempFileCommand(this);
Tabs = CreateHotKeyCategoryTabsCollection(ref m_HotKeyDisplayStringMaxLength);
}
public CreateHotKeyListTempFileCommand CreateHotKeyListTempFileCommand
{
get { return m_CreateHotKeyListTempFileCommand; }
}
public int HotKeyDisplayStringMaxLength
{
get
{
return m_HotKeyDisplayStringMaxLength;
}
}
//Creates the whole HotKeyCategoryTabCollection which is bound in the HelpWindow
private static ICollectionView CreateHotKeyCategoryTabsCollection(ref int hotKeyDisplayStringMaxLength)
{
var groupedHotkeys = new Dictionary<string, List<HotKeyInfo>>();
var tabs = new List<HotKeyCategoryTab>();
var hotkeys = Properties.HotKeySettings.Default.Properties;
foreach (SettingsProperty item in hotkeys)
{
var commandName = item.Name.Split(new string[] { "Command" }, StringSplitOptions.RemoveEmptyEntries)[0] + "Command";
var displayString = HotKeyLocalizer.LocalizeDisplayString(new SettingsPropertyValue(item).PropertyValue as string);
var description = Properties.HotKeysDescriptions.ResourceManager.GetString(commandName);
var category = Properties.HotKeysCategories.ResourceManager.GetString(commandName);
if (description != null && category != null)
{
//Extension for Commands with multiple HotKeys
var splittedDisplayString = displayString.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var splittedDescription = description.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var splittedCategory = category.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var hotkeyInfoData = splittedDisplayString.Zip(
splittedDescription.Zip(splittedCategory, (desc, cat) => new Tuple<string, string>(desc, cat)),
(dispStr, desc_cat) => new Tuple<string, string, string>(dispStr, desc_cat.Item1, desc_cat.Item2));
//item1 = displayString, item2 = description, item3 = category
foreach (var hotkeyInfoDate in hotkeyInfoData)
{
var hotkeyInfo = new HotKeyInfo(hotkeyInfoDate.Item1, hotkeyInfoDate.Item2);
//Create new HotKeyCategory, if not existing
if (!groupedHotkeys.ContainsKey(hotkeyInfoDate.Item3))
{
groupedHotkeys.Add(hotkeyInfoDate.Item3, new List<HotKeyInfo>());
tabs.Add(new HotKeyCategoryTab(hotkeyInfoDate.Item3,
CollectionViewSource.GetDefaultView(groupedHotkeys[hotkeyInfoDate.Item3])));
}
groupedHotkeys[hotkeyInfoDate.Item3].Add(hotkeyInfo);
//Used to determine the with and tabs for the outputfile
if (hotkeyInfo.DisplayString.Length > hotKeyDisplayStringMaxLength)
{
hotKeyDisplayStringMaxLength = hotkeyInfo.DisplayString.Length;
}
}
}
}
//Sorting alphabetically
SortHotKeyCategory(groupedHotkeys);
return CollectionViewSource.GetDefaultView(tabs);
}
private static void SortHotKeyCategory(Dictionary<string, List<HotKeyInfo>> groupedHotkeys)
{
foreach (var item in groupedHotkeys)
{
item.Value.Sort((x, y) => string.Compare(x.DisplayString, y.DisplayString));
}
}
}
}
<file_sep>/HotKeySystem/HotKeySystem example/HotKeySystem/AdapterClasses/HotKeyAdapter.cs
using System;
namespace HotKeySystem_example.HotKeySystem
{
//Adapter-class for HotKeys to provide HotKey-object of specific type
public static class HotKeyAdapter
{
public static HotKeyBase GetNewHotKey(Type hotkeyType, HotKeyConfig config)
{
HotKeyBase hotkey = null;
if (hotkeyType.Equals(typeof(KeyHotKey)))
{
hotkey = new KeyHotKey(config);
}
else if (hotkeyType.Equals(typeof(MouseHotKey)))
{
hotkey = new MouseHotKey(config);
}
else
{
throw new NotImplementedException("HotKeyAdapter could not provide requested HotKey of Type: " + hotkeyType.FullName);
}
return hotkey;
}
public static T GetNewHotKey<T>(HotKeyConfig config)
where T : HotKeyBase, new()
{
return Activator.CreateInstance(typeof(T), config) as T;
}
}
}
<file_sep>/HotKeySystem/ReadMe.txt
Dies ist ein kleines HotKey-System was ich für command-based WPF-Anwendungen geschrieben habe.
Die Grundidee ist es hotkeys über die app.config dynamisch änderbar zu machen, um sie nicht hard-zu-coden.
Ein Hotkey besteht immer aus einer Gesture z.B. Key- oder MouseGesture und einem zugehörigen Command, welcher durch das Tastenkürzel aktiviert wird.
Optional können Hotkeys auch noch eine Beschreibung tragen, was ganz hilfreich ist, um sie lokalisiert und z.B. in einem Hilfe-Fenster anzuzeigen.
Ein Command fordert beim HotKeyProvider einen hotkey an. Dieser überprüft, ob der angeforderte hotkey schon existiert und gibt ihn dann zurück.
Sollte der hotkey nicht existiert, dann erstellt der HotKeyProvider diesen und speichert ihn ab.
Durch das System kann man schnell neue Hotkeys erstellen und hat sie dynamisch änderbar und gebündelt in der app.config bzw. in der .xaml des jeweiligen Fensters stehen.
PS: F1 fürs Hilfe-Fenster drücken ;)<file_sep>/README.md
# Portfolio
Das ist eine Sammlung von kleinen Projekten und Codebeispielen, welche ich geschrieben habe.
- Im PDF findet sich eine Auswahl meiner Gaming Projekte
- Im Ordner Code snippets befinden sich ein paar kleinere Codebeispiele, die ich ganz cool finde
- Im Ordner HotKeySystem ist ein kleines HotKeySystem für command-based WPF-Anwendungen
|
420794d45fd68a5556954ca0d81f3c6eec4443d8
|
[
"SQL",
"Ruby",
"Markdown",
"C#",
"Text"
] | 22 |
C#
|
Artery/Portfolio
|
8f9c6e0aaf452ad7b23c3cda46935f5e09abde56
|
c9f1e452ed807181fd1005057e069b6d99fc8556
|
refs/heads/master
|
<file_sep>// let numDrumBtns = document.querySelectorAll(".drum").length;
// for (let i = 0; i < numDrumBtns; i++) {
// document.querySelectorAll(".drum")[i].addEventListener("click", function () {
// alert("Button clicked!");}
// );
// }
//Buttons Array
let keys = [
{ key: "q", soundForKey: "sounds/8 Bits/Boom1.wav" },
{ key: "w", soundForKey: "sounds/8 Bits/Clap.wav" },
{ key: "e", soundForKey: "sounds/8 Bits/Click1.wav" },
{ key: "i", soundForKey: "sounds/808/Hihat_open_2.wav" },
{ key: "o", soundForKey: "sounds/808/Hihat1_closed.wav" },
{ key: "p", soundForKey: "sounds/808/Kick.wav" },
{ key: "a", soundForKey: "sounds/808/Snare.wav" },
{ key: "s", soundForKey: "sounds/Claps/Clap1.WAV" },
{ key: "d", soundForKey: "sounds/Crash/Crash_1.WAV" },
{ key: "j", soundForKey: "sounds/Hihats/Hihat_1_closed.wav" },
{ key: "k", soundForKey: "sounds/Kicks/Hard_Kick_1.WAV" },
{ key: "l", soundForKey: "sounds/Percussion/Conga_1.wav" },
{ key: "z", soundForKey: "sounds/Percussion/FX1.wav" },
{ key: "x", soundForKey: "sounds/tom-1.mp3" },
{ key: "c", soundForKey: "sounds/tom-2.mp3" },
{ key: "n", soundForKey: "sounds/tom-3.mp3" },
{ key: "m", soundForKey: "sounds/tom-4.mp3" },
{ key: ",", soundForKey: "sounds/Percussion/Perc10.wav" }
];
//Detecting Button Press
let numDrumBtns = document.querySelectorAll(".drum").length;
for (let i = 0; i < numDrumBtns; i++) {
document.querySelectorAll(".drum")[i].addEventListener("click", btnClicked);
}
function btnClicked() {
let btnInnerHTML = this.innerHTML;
makeSound(btnInnerHTML);
btnAnimation(btnInnerHTML);
// alert("Button clicked!");
// this.style.color = "white";
}
document.addEventListener("keydown", function(event) {
let index = keys.findIndex(item => item.key === event.key);
// If the key exists in the array, update the sound
if (index !== -1) {
makeSound(event.key);
btnAnimation(event.key);
} else {
console.log("Key not found in the soundboard.");
}
});
function changeSound(key, newSound) {
// Find the index of the key in the soundboardArray
let index = keys.findIndex(item => item.key === key);
// If the key exists in the array, update the sound
if (index !== -1) {
keys[index].soundForKey = new Audio(newSound);
console.log("Sound changed successfully!");
} else {
console.log("Key not found in the soundboard.");
}
}
function makeSound(key) {
// Find the sound file associated with the key
let sound = keys.find(item => item.key === key);
// If the key exists in the array, play the sound
if (sound) {
let audio = new Audio(sound.soundForKey);
audio.play();
} else {
console.log("Key not found in the soundboard.");
}
}
function btnAnimation(currentKey) {
let activeButton = document.querySelector("." + currentKey);
// activeButton.setAttribute("class", ".pressed");
activeButton.classList.add("pressed");
setTimeout(function() {
activeButton.classList.remove("pressed");
}, 100);
}
|
0b9356b49749734ed0bd07a370cd1fb27f064710
|
[
"JavaScript"
] | 1 |
JavaScript
|
MicahDitto/Drum-Kit-Website
|
837f4ce4542e17e54cf070d1ae3687ca9a43b981
|
0f7601ec28b1fc118bb78f0d39f6285931a34b29
|
refs/heads/master
|
<repo_name>roman-cf/WF-JS-Day2-Roman-Barbara<file_sep>/basic/js/basic1.js
var randTemp = (Math.floor(Math.random()*45))-5;
if (randTemp<10){
wetterausgabe ="kalt";
bgColor= "blue"
txtColor= "white"
}else if(randTemp<32){
wetterausgabe ="angenehm";
bgColor="yellowgreen";
txtColor="black";
}else{
wetterausgabe ="heiss";
bgColor="orange";
txtColor="red";
}
document.getElementById("wettertext").innerHTML = randTemp + "°C ist " + wetterausgabe;
document.querySelector("#wettertext").style.backgroundColor = bgColor;
document.querySelector("#wettertext").style.color = txtColor;
document.querySelector("#wetterpic").style.backgroundImage = "url('./img/" +wetterausgabe+".jpg')";
<file_sep>/basic/js/basic2.js
var testArr = [1,7,-3,9];
testArr.sort();
document.getElementById("text").innerHTML = testArr[(testArr.length)-1];
<file_sep>/basic/js/basic3.js
var testArr = [1,3,7,10,2];
var start = testArr[0];
for (i=1; i < testArr.length; i++){
start*=testArr[i];
}
document.getElementById("text").innerHTML = "Das Produkt aus "+ testArr + " ist: " +start
|
db5589858eab3d0ffc8a95ecfd8ba5903bf30c41
|
[
"JavaScript"
] | 3 |
JavaScript
|
roman-cf/WF-JS-Day2-Roman-Barbara
|
6569dcbaec0f423ba243928abf2efcd23195900f
|
73ebfb48db51d79452be055be38f2b087b82ea66
|
refs/heads/master
|
<file_sep># GroupDomain
GroupDomain is a plugin for adding users to a group if their email address matches a white list of domains.
## Installation
Follow [Install a Plugin](https://meta.discourse.org/t/install-a-plugin/19157)
how-to from the official Discourse Meta, using `git clone https://github.com/literatecomputing/discourse-group-domain.git`
as the plugin command.
## Usage
In site settings, you must set `group_domain_whitelist` to a set of email domains that should be added to the group and `group_domain_group` to the name of the group that users should be added to.
If `group_domain_strict` is set the plugin will remove users from the group if their email address changes to a non-white-listed address (if unset, if you change your address from a whitelisted domainn to another one, you will stay in the group).
`group_domain_update_frequency` is how often a process will run that will update all users (mostly userful if you change the set of whitelisted domains and want to update users' group membership). If `group_domain_strict` is unset, it will process only users whose address matches one of the whitelisted domains and add those users to the group. If `group_domain_strict` is set, the plugin will process all users and add or remove them to the group. Rather than waiting for the event to be run, you can trigger GroupDomainUpdater::UpdateGroupDomain in Sidekiq.
## Feedback
If you have issues or suggestions for the plugin, please bring them up on
[Discourse Meta](https://meta.discourse.org).
## TODO
disallow activation without domains and group set up
tests
<file_sep>import { acceptance } from "helpers/qunit-helpers";
acceptance("GroupDomain", { loggedIn: true });
test("GroupDomain works", async assert => {
await visit("/admin/plugins/group-domain");
assert.ok(false, "it shows the GroupDomain button");
});
<file_sep>module GroupDomainUpdater
class UpdateGroupDomain < ::Jobs::Scheduled
every SiteSetting.group_domain_update_frequency.hours
def execute(args)
if SiteSetting.group_domain_enabled
GroupDomain.process_whitelist_for_all_users
end
end
end
end
<file_sep># name: GroupDomain
# about: add to Group if email is in a given Domain
# version: 0.1
# authors: pfaffman
# url: https://github.com/pfaffman/discourse-group-domain
register_asset "stylesheets/common/group-domain.scss"
enabled_site_setting :group_domain_enabled
PLUGIN_NAME ||= "GroupDomain".freeze
after_initialize do
load File.expand_path('app/jobs/group_domain_daily.rb', __dir__)
# see lib/plugin/instance.rb for the methods available in this context
module ::GroupDomain
class Engine < ::Rails::Engine
engine_name PLUGIN_NAME
isolate_namespace GroupDomain
end
def self.process_whitelist_for_all_users
user_ids = []
if SiteSetting.group_domain_strict
# process all users
user_ids = User.human_users.pluck(:id)
else
# get just the users likely matching with matching whitelist
SiteSetting.group_domain_whitelist.split("|").each do |domain|
user_ids = user_ids + UserEmail.where("email like '%#{domain}'").pluck(:user_id)
end
end
user_ids.each do |uid|
user = User.find(uid)
GroupDomain.add_to_group_if_in_whitelisted_domain(user)
end
end
def self.add_to_group_if_in_whitelisted_domain(user)
group = Group.find_by(name: SiteSetting.group_domain_group)
exit unless group
whitelisted = false
SiteSetting.group_domain_whitelist.split("|").each do |domain|
user.emails.each do |e|
whitelisted |= e.ends_with?(domain)
end
end
if whitelisted
gu = GroupUser.find_by(group_id: group.id, user_id: user.id)
GroupUser.create(group_id: group.id, user_id: user.id) unless gu
end
if !whitelisted && SiteSetting.group_domain_strict
gu = GroupUser.find_by(user_id: user.id, group_id: group.id)
gu.destroy! if gu
end
end
end
require_dependency "application_controller"
class GroupDomain::ActionsController < ::ApplicationController
requires_plugin PLUGIN_NAME
before_action :ensure_logged_in
def list
render json: success_json
end
end
GroupDomain::Engine.routes.draw do
get "/list" => "actions#list"
end
Discourse::Application.routes.append do
mount ::GroupDomain::Engine, at: "/group-domain"
end
DiscourseEvent.on(:user_created) do |user|
GroupDomain.add_to_group_if_in_whitelisted_domain(user)
end
self.add_model_callback(UserEmail, :after_commit, on: :update) do
user = User.find(self.user_id)
GroupDomain.add_to_group_if_in_whitelisted_domain(user)
end
end
<file_sep>require 'rails_helper'
# these do'nt work, but I don't understand why
describe User do
before do
Jobs.run_immediately!
SiteSetting.group_domain_enabled = true
SiteSetting.group_domain_whitelist = ['gmail.com']
#SiteSetting.group_domain_group = group.name
end
let(:uncool_user) { Fabricate(:user) }
let(:cool_user) { Fabricate(:user, email: '<EMAIL>') }
# describe 'when a user is created' do
# it 'cool user should be in the cool group' do
# expect :cool_user.groups.where(id: :group.id).count.to eq(1)
# end
# it 'uncool user should not be in the cool group' do
# expect :uncool_user.groups.where(id: :group.id).count.to eq(0)
# end
# end
end
|
ae6a86ba039802c4df588c6d8096e50adeeafd28
|
[
"Markdown",
"JavaScript",
"Ruby"
] | 5 |
Markdown
|
literatecomputing/discourse-group-domain
|
493d9f681fd770fa3608e6d57447c7fa41b92cbb
|
b571cc9e00d0e89a0178ac85a5d379fb47aac8c9
|
refs/heads/master
|
<repo_name>MaryArbs/anagram-detector-online-web-ft-110419<file_sep>/lib/anagram.rb
class Anagram
attr_accessor :word
def initialize(word)
@word= word
end
def match(array)
array.select do |word|
word.split("").sort == @word.split("").sort
end
end
end
|
cade3313383a8a1334826bac4b9dd17db8972057
|
[
"Ruby"
] | 1 |
Ruby
|
MaryArbs/anagram-detector-online-web-ft-110419
|
ec33b25ce563c5ef413c02f85e217c61a6c6680c
|
a79e2da7ff8966adfd1bb58d8f26081016190c34
|
refs/heads/master
|
<repo_name>gustavo-gimenez/universal-webpack<file_sep>/index.es6.js
export { default as server } from './es6/server'
export { default as server_configuration } from './es6/server configuration'
export { default as client_configuration } from './es6/client configuration'
export { default as prepare } from './es6/prepare'
export { default as devtools } from './es6/devtools'
// for camelCased guys
export { default as serverConfiguration } from './es6/server configuration'
export { default as clientConfiguration } from './es6/client configuration'
|
23495caf0fde569051584b127e28a7c98c730bdd
|
[
"JavaScript"
] | 1 |
JavaScript
|
gustavo-gimenez/universal-webpack
|
b04892589ed48eb4c160d2924b328bee177a9554
|
c762ddb0f4f9bbc68ad0ff8252d4adf1d0908156
|
refs/heads/master
|
<repo_name>edernegrete/crypto-watcher-server<file_sep>/src/app.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const Koa = require('koa');
const logger = require('koa-logger');
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const koaRequest = require('koa-http-request');
const cors = require('@koa/cors');
const app = new Koa();
app.use(bodyParser());
app.use(cors());
app.use(koaRequest({
dataType: 'json'
}));
app.use(async(ctx, next) => next().catch((err) => {
if (err.status === 401) {
ctx.status = 401;
const errMessage = err.originalError
? err.originalError.message
: err.message;
ctx.body = {
error: errMessage
};
ctx.set('X-Status-Reason', errMessage);
} else {
throw err;
}
}));
// Logger
app.use(async(ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
if (process.env.NODE_ENV !== 'test') {
app.use(logger());
}
router.get('/bitso/:id', async(ctx) => {
const bitso = await ctx.get(`https://api.bitso.com/v3/ticker/?book=${ctx.params.id}_mxn`, null, {
'User-Agent': 'koa-http-request'
});
ctx.body = bitso;
});
router.get('/coinlore/:id', async(ctx) => {
const getId = id => {
switch (id) {
case 'btc':
return 90;
case 'eth':
return 80;
case 'xrp':
return 58;
default:
return 90;
}
};
const coinlore = await ctx.get(`https://api.coinlore.com/api/ticker/?id=${getId(ctx.params.id)}`, null, {
'User-Agent': 'koa-http-request'
});
ctx.body = coinlore;
});
router.get('/coincap/:id', async(ctx) => {
const coincap = await ctx.get('https://api.coincap.io/v2/markets', null, {
'User-Agent': 'koa-http-request'
});
const data = coincap.data.filter(item => ctx.params.id.toUpperCase() === item.baseSymbol && item.exchangeId === 'acx');
ctx.body = data;
});
app.use(router.routes());
app.use(router.allowedMethods());
module.exports = app;
<file_sep>/src/app.spec.js
//TODO ADD UNIT TEST
|
b4d04558baa97dc87b61e148520dd461db339a36
|
[
"JavaScript"
] | 2 |
JavaScript
|
edernegrete/crypto-watcher-server
|
5d77caadaddeae3d61400563daf571db8b6f8206
|
94c82ba433f1e6dab126847999532a3e2dadea89
|
refs/heads/master
|
<repo_name>nlgreen/cs203<file_sep>/Greeter/Greeter/src/greeter/GreeterTester.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package greeter;
/**
* A simple tester for Greeters
* @author natgreen
*/
public class GreeterTester {
/**
* Main method to start from
* @param args
*/
public static void main(String[] args)
{
// Test for making a simple Greeter and outputting its greeting
Greeter worldGreeter = new Greeter("World");
String greeting = worldGreeter.sayHello();
System.out.println(greeting);
// Test for changing the Greeter's name and outputting its greeting
worldGreeter.setName("Fred");
System.out.println(worldGreeter.sayHello());
// Test for setting two variables as references to the same Greeter
Greeter greeterDupe = worldGreeter;
greeterDupe.setName("Imposter");
// Should be an imposter now
System.out.println(worldGreeter.sayHello());
// A new Greeter named Kyle that switches with the imposter
Greeter newGreeter = new Greeter("Kyle");
newGreeter.swapNames(worldGreeter);
// Demonstrating that the names have been switched
System.out.println("This should be an Imposter: " +
newGreeter.sayHello());
System.out.println("This should be Kyle: " +
worldGreeter.sayHello());
}
}
<file_sep>/Greeter/Greeter/src/greeter/Greeter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package greeter;
/**
* A class for creating simple greetings
* @author natgreen
*
*/
public class Greeter {
/**
* Constructs a Greeter object that can greet a person or entity
* @param aName The name of the person or entity to be addressed
*/
public Greeter (String aName)
{
name = aName;
}
/**
* Greets with a "Hello" message
* @return A message containing "Hello" and the name of the person or
* entity addressed
*/
public String sayHello()
{
return "Hello, " + name + "!";
}
/**
* Changes the name of the Greeter to a new name
* @param newName The new name that the Greeter will refer to
*/
public void setName(String newName)
{
name = newName;
}
/**
* Swaps the names of two Greeters
* @param other The Greeter that will swap names with whichever Greeter
* called the method
*/
public void swapNames(Greeter other)
{
String tempName = this.name;
this.name = other.name;
other.name = tempName;
}
private String name;
}
<file_sep>/Greeter (firsttry)/src/greeter/Greeter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package greeter;
/**
* A class for producing simple greetings.
*/
/**
*
* @author natgreen
*/
public class Greeter {
/**
* Constructs a Greeter object that can greet a person or entity.
*
* @param aName the name of the person or entity who should be addressed in
* the greetings.
*/
public Greeter(String aName) {
name = aName;
}
/**
* Greet with a "Hello" message.
*
* @return a message containing "Hello" and the name of the greeted person
* or entity.
*/
public String sayHello() {
return "Hello, " + name + "!";
}
private String name;
public static void main(String[] args) {
Greeter worldGreeter = new Greeter("World");
String greeting = worldGreeter.sayHello();
System.out.println(greeting);
for(int x=0; x<5;x++)
{
System.out.println(x);
}
//System.out.println(x+5);
}
}
|
2d46dbe576bc4f637a506746b0c31ebbf8ad972a
|
[
"Java"
] | 3 |
Java
|
nlgreen/cs203
|
f3dda86f46ec09fcedfe34e93633af4e41df1433
|
4946f035292152567d98398452d0499740bd7134
|
refs/heads/master
|
<file_sep>package com.zendev.latihanintent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnLogin, btnData, btnInputData, btnBroadcast, btnImplicit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin = findViewById(R.id.btn_activity_login);
btnLogin.setOnClickListener(this);
btnData = findViewById(R.id.btn_activity_data);
btnData.setOnClickListener(this);
btnInputData = findViewById(R.id.btn_activity_input_data);
btnInputData.setOnClickListener(this);
btnBroadcast = findViewById(R.id.btn_broadcast_receiver);
btnBroadcast.setOnClickListener(this);
btnImplicit = findViewById(R.id.btn_implicit);
btnImplicit.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_activity_login:
Intent moveLogin = new Intent(MainActivity.this, LoginActivity.class);
startActivity(moveLogin);
break;
case R.id.btn_activity_data:
Intent moveData = new Intent(MainActivity.this, DataActivity.class);
moveData.putExtra(DataActivity.EXTRA_IMG, R.drawable.ic_launcher_background);
moveData.putExtra(DataActivity.EXTRA_JUDUL, "Universitas Putra Indonesia");
moveData.putExtra(DataActivity.EXTRA_DESKRIPSI, "Universitas Putra Indonesia adalah universitas yang berada di kota padang");
startActivity(moveData);
break;
case R.id.btn_activity_input_data:
Intent moveInputData = new Intent(MainActivity.this, InputDataActivity.class);
startActivity(moveInputData);
break;
case R.id.btn_broadcast_receiver:
Intent moveBroadcast = new Intent(MainActivity.this, BroadcastReceiverActivity.class);
startActivity(moveBroadcast);
break;
case R.id.btn_implicit:
Intent moveImplicit = new Intent(MainActivity.this, ImplicitActivity.class);
startActivity(moveImplicit);
}
}
}
<file_sep>package com.zendev.latihanintent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class BroadcastReceiverActivity extends AppCompatActivity {
TextView tvBaterai;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast_receiver);
tvBaterai = findViewById(R.id.tv_baterai);
this.registerReceiver(this.broadcastReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int bateraiLevel = intent.getIntExtra("level", 0);
tvBaterai.setText("Baterai Anda : " + String.valueOf(bateraiLevel) + "%");
}
};
}
<file_sep>package com.zendev.latihanintent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class DataActivity extends AppCompatActivity {
public static final String EXTRA_IMG = "extra_img";
public static final String EXTRA_JUDUL = "extra_judul";
public static final String EXTRA_DESKRIPSI = "extra_deskripsi";
ImageView imgGambar;
TextView tvJudul, tvDeskripsi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
tvJudul = findViewById(R.id.tv_judul);
tvDeskripsi = findViewById(R.id.tv_deskripsi);
imgGambar = findViewById(R.id.img_gambar);
int gambar = getIntent().getIntExtra(EXTRA_IMG, 0);
String judul = getIntent().getStringExtra(EXTRA_JUDUL);
String deskripsi = getIntent().getStringExtra(EXTRA_DESKRIPSI);
imgGambar.setImageResource(gambar);
tvJudul.setText(judul);
tvDeskripsi.setText(deskripsi);
}
}
|
151d6c4b9d5d9127c0df9c080b02719751983da2
|
[
"Java"
] | 3 |
Java
|
ukmitcybernetix/LatihanIntent
|
0ff0a1e563f93854be03dea31a7f8fb719ff1e0a
|
d070c0c0516e5b46cf46702f95b9e4fbac0b0dbf
|
refs/heads/master
|
<file_sep>import Basic
import xcodeproj
final class ProjectFileListFactory: FileListProducing {
func make(path: AbsolutePath) throws -> AnySequence<String> {
var files = try XcodeProj(path: path)
.pbxproj
.objects
.fileReferences
.values
.compactMap { $0.path }
let iterator = AnyIterator {
files.isEmpty ? nil : files.removeLast()
}
return AnySequence(iterator)
}
}
<file_sep>import struct Basic.AbsolutePath
import class Foundation.NSString
func main(
command: Command?,
usagePrinter: UsagePrinting,
fileListFactory: FileListProducing,
projectFileListFactory: FileListProducing
) throws {
guard let command = command
else {
usagePrinter.printUsage()
return
}
let filesOfInterest: [String]
switch command {
case let .list(.all, xcodeprojPath):
filesOfInterest = try Array(fileListFactory.make(path: xcodeprojPath.parentDirectory))
case let .list(.project, xcodeprojPath):
filesOfInterest = try Array(Set(projectFileListFactory.make(path: xcodeprojPath)))
case let .list(.suspicious, xcodeprojPath):
let allFiles = try fileListFactory.make(path: xcodeprojPath.parentDirectory)
let projectFiles = try Set(projectFileListFactory.make(path: xcodeprojPath))
//filesOfInterest = allFiles.subtracting(projectFiles)
var suspiciousFiles = [String]()
for file in allFiles {
if !projectFiles.contains(where: file.localizedCaseInsensitiveContains) {
suspiciousFiles.append(file)
}
}
filesOfInterest = suspiciousFiles
}
for path in filesOfInterest.sorted() {
print(path)
}
}
let commandLineArgumentsParser = CommandLineArgumentsParser()
let command = commandLineArgumentsParser.parse(arguments: CommandLine.arguments.dropFirst())
try main(
command: command,
usagePrinter: commandLineArgumentsParser,
fileListFactory: GitFileListFactory(),
projectFileListFactory: ProjectFileListFactory()
)
<file_sep>// swift-tools-version:4.1
import PackageDescription
let package = Package(
name: "xccheck",
dependencies: [
.package(url: "https://github.com/apple/swift-package-manager.git", .upToNextMajor(from: "0.2.0")),
.package(url: "https://github.com/tuist/xcodeproj.git", .upToNextMajor(from: "5.0.0-rc2"))
],
targets: [
.target(
name: "xccheck",
dependencies: ["Utility", "xcodeproj"]),
]
)
<file_sep>import struct Basic.AbsolutePath
enum Command {
case list(ListKind, AbsolutePath)
enum ListKind {
case all
case project
case suspicious
}
}
protocol CommandLineArgumentsParsing {
func parse() -> Command?
}
protocol UsagePrinting {
func printUsage()
}
<file_sep>import struct Basic.AbsolutePath
protocol FileListProducing {
func make(path: AbsolutePath) throws -> AnySequence<String>
}
<file_sep>import var Basic.stderrStream
import class Utility.ArgumentParser
import class Utility.PositionalArgument
import struct Utility.PathArgument
final class CommandLineArgumentsParser: UsagePrinting {
let main: ArgumentParser
let listAll: ListParser
let listProject: ListParser
let listSuspicious: ListParser
init() {
self.main = ArgumentParser(usage: "<command> <xcodeproj-file>", overview: "Xcode project utility")
self.listAll = ListParser.add(kind: .all, to: main)
self.listProject = ListParser.add(kind: .project, to: main)
self.listSuspicious = ListParser.add(kind: .suspicious, to: main)
}
func parse<S: Sequence>(arguments: S) -> Command?
where S.Element == String
{
let args = try? main.parse(Array(arguments))
let subparser = args?.subparser(main)
if subparser == listAll.name,
let xcodeprojPath = args?
.get(listAll.xcodeproj)?
.path
{
return .list(.all, xcodeprojPath)
}
if subparser == listProject.name,
let xcodeprojPath = args?
.get(listProject.xcodeproj)?
.path
{
return .list(.project, xcodeprojPath)
}
if subparser == listSuspicious.name,
let xcodeprojPath = args?
.get(listSuspicious.xcodeproj)?
.path
{
return .list(.suspicious, xcodeprojPath)
}
return nil
}
func printUsage() {
main.printUsage(on: stderrStream)
}
final class ListParser {
let kind: Command.ListKind
var name: String { return ListParser.description(of: kind).name }
let xcodeproj: PositionalArgument<PathArgument>
private init(kind: Command.ListKind, xcodeproj: PositionalArgument<PathArgument>) {
self.kind = kind
self.xcodeproj = xcodeproj
}
static func add(kind: Command.ListKind, to parent: ArgumentParser) -> ListParser {
let (name, overview) = description(of: kind)
let parser = parent.add(subparser: name, overview: overview)
let xcodeproj = parser.add(positional: "xcodeproj", kind: PathArgument.self, optional: false, usage: "Xcode project file")
return ListParser(kind: kind, xcodeproj: xcodeproj)
}
private static func description(of kind: Command.ListKind) -> (name: String, overview: String) {
switch kind {
case .all:
return ("list-all", "List files")
case .project:
return ("list-contents", "List project contents")
case .suspicious:
return ("list-suspicious", "List suspicious files")
}
}
}
}
<file_sep>import Basic
final class GitFileListFactory: FileListProducing {
func make(path: AbsolutePath) throws -> AnySequence<String> {
let processResult = try Process
.popen(args: "git", "ls-files", "-z", path.asString)
let data = try processResult.output.dematerialize()
var files = try stringList(data)
let iterator = AnyIterator {
files.isEmpty ? nil : files.removeLast()
}
return AnySequence(iterator)
}
func stringList(_ utf8data: [Int8]) throws -> [String] {
var offset = 0
var list = [String]()
while offset < utf8data.count {
let string = try self.string(utf8data.suffix(from: offset))
list.append(string)
offset += string.lengthOfBytes(using: .utf8) + 1
}
return list
}
func string<S: Sequence>(_ utf8data: S) throws -> String
where S.Element == Int8
{
guard let string = String(validatingUTF8: Array(utf8data))
else { throw Failure.illegalUTF8Sequence }
return string
}
private enum Failure: Error {
case illegalUTF8Sequence
}
}
<file_sep># xccheck
A diagnostic tool for Xcode projects.
# Build and run
Use Swift Package Manager to build the project or generate an Xcode project file to get into a convenient environment.
```
$ swift package generate-xcodeproj && open xccheck.xcodeproj
```
See `swift run xccheck -h` for usage information.
|
46de97454f1e37c74bbedbc7360a61e2cfe64e76
|
[
"Swift",
"Markdown"
] | 8 |
Swift
|
werediver/xccheck
|
212126546c3bb73f2a9c6eeadc16690bcec3b3b1
|
7372e367c745c1b796355a72dcb220b3bdde1229
|
refs/heads/develop
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { BroadcastService } from './../shared/broadcast.service';
import { PokemonsService } from './pokemons.service';
@Component({
selector : 'pokemons-component',
templateUrl : './pokemons.html',
styleUrls : [ './pokemons.scss' ]
})
export class PokemonsComponent implements OnInit {
public generations : Array<any> = [{}, {}];
public pokemonImage : boolean;
////////////////////
constructor (
private broadcastService : BroadcastService,
private pokemonsService : PokemonsService
) {}
////////////////////
ngOnInit () : void {
this.getGeneration();
}
////////////////////
public get species () : any {
const filtered = this.generations.filter(generation => generation.selected);
return filtered[0] ? filtered[0].species : [];
}
public get pokemon () : any {
let filtered = (this.generations.filter(generation => generation.selected));
filtered = filtered[0] ? filtered[0].species.filter(specie => specie.selected) : [];
return filtered[0] ? filtered[0].pokemon : [];
}
////////////////////
public getGeneration (i : number = 0) : void {
this.pokemonsService.getGeneration(i + 1)
.subscribe(generation => this.fillGeneration(i, generation));
}
public setGeneration (i : number) : void {
this.generations.forEach((generation, j : number) => this.generations[j].selected = i === j);
this.getSpecie(i, 0);
}
public setSpecie (i : number) : void {
this.generations.forEach((generation, j : number) => {
if (generation.selected)
generation.species.forEach((specie, l : number) => {
this.generations[j].species[l].selected = i === l;
this.getSpecie(j, i);
});
});
}
////////////////////
private fillGeneration (i : number, generation? : any) : void {
this.generations[i].species = generation;
this.generations[i].species[0].selected = true;
this.setGeneration(i);
this.getSpecie(i, 0);
}
private getSpecie (i : number, j : number) : void {
if (!this.generations[i].species[j].pokemon) {
// this.pokemonImage = false;
this.broadcastService.loader.next(true);
this.pokemonsService.getSpecie(this.generations[i].species[j].url)
.subscribe(specie => this.getPokemon(i, j, specie));
}
}
private getPokemon (i : number, j : number, specie) : void {
this.generations[i].species[j].pokemon = specie;
this.pokemonsService.getPokemon(this.generations[i].species[j].pokemon.id)
.subscribe(pokemon => this.fillPokemon(i, j, pokemon));
}
private fillPokemon (i : number, j : number, pokemon) : void {
this.generations[i].species[j].pokemon.image = pokemon.sprites.front_default;
this.generations[i].species[j].pokemon.types = pokemon.types;
this.broadcastService.loader.next(false);
}
}<file_sep>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { BASE_API } from './../shared/base-api.cont';
@Injectable()
export class PokemonsService {
constructor (private http : Http) {}
////////////////////
public getGeneration (generation : number) : Observable<any> {
return this.http.get(`${BASE_API}generation/${generation}`)
.pipe(map((response : Response) => response.json().pokemon_species));
}
public getSpecie (path : string) {
return this.http.get(path)
.pipe(map((response : Response) => response.json()));
}
public getPokemon (id : number) {
return this.http.get(`${BASE_API}pokemon/${id}`)
.pipe(map((response : Response) => response.json()));
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BroadcastService } from './shared/broadcast.service';
import { PokemonsService } from './pokemons/pokemons.service';
import { LanguagePipe } from './shared/language.pipe';
import { PokemonsComponent } from './pokemons/pokemons.component';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations : [
LanguagePipe,
PokemonsComponent,
AppComponent
],
imports : [
BrowserModule,
HttpModule,
BrowserAnimationsModule,
AppRoutingModule
],
providers : [
BroadcastService,
PokemonsService
],
bootstrap : [ AppComponent ]
})
export class AppModule { }
<file_sep>import { Component } from '@angular/core';
import { trigger, transition, style, animate } from '@angular/animations';
import { BroadcastService } from './shared/broadcast.service';
@Component({
selector : 'app-root',
templateUrl : './app.component.html',
animations : [
trigger('loader', [
transition(':enter', [
style({ opacity : 0 }),
animate('200ms ease', style({ opacity : 1 }))
]),
transition(':leave', [
style({ opacity : 1 }),
animate('100ms ease', style({ opacity : 0 }))
])
])
]
})
export class AppComponent {
public loader : boolean;
////////////////////
constructor (private broadcastService : BroadcastService) {
this.loader = true;
this.broadcastService.loader
.subscribe((loader : boolean) => this.loader = loader);
}
}<file_sep>import { Pipe } from '@angular/core';
@Pipe({ name : 'language' })
export class LanguagePipe {
transform (languages : Array<any>, language : string, property : string) : string {
if (languages)
for (let i = 0; i < languages.length; i++) {
if (languages[i].language.name === language)
return languages[i][property];
}
}
}
|
2018c7c495a188f60da679466d848785d688cc02
|
[
"TypeScript"
] | 5 |
TypeScript
|
paulo-campos/iBureau
|
d6f7eb106585d1c860ea235686f408337ed41ce2
|
d7411cbe4d281c5e970f83650051bbdeced25b26
|
refs/heads/master
|
<repo_name>tallisson/fluxo_carga<file_sep>/vsf.h
#ifndef VSF_H_
#define VSF_H_
#include "v-control.h"
#include "graph.h"
#include "jacobian.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
#include <armadillo>
namespace ns3
{
class Vsf : public VControl
{
public:
Vsf();
virtual ~Vsf();
static TypeId GetTypeId(void);
virtual bool DoControl (mat jac, Ptr<Graph> graph);
static const double LIMIAR = 0.01;
};
}
#endif /* VSF_H_ */
<file_sep>/branch.h
#ifndef BRANCH_H_
#define BRANCH_H_
#include "ns3/double.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
#include <map>
#include <string>
namespace ns3
{
/*
* Struct to store branches variables
*/
struct branch
{
public:
uint32_t m_ni;
uint32_t m_nf;
uint32_t m_area;
uint32_t m_zona;
uint32_t m_circ;
uint32_t m_tipo;
uint32_t m_ordtap;
uint32_t m_postap;
double m_r;
double m_x;
double m_bsh;
double m_line_rating1;
double m_line_rating2;
double m_line_rating3;
double m_t_ctrl;
double m_side;
double m_tap;
double m_def;
double m_tapmin;
double m_tapmax;
double m_passo;
double m_ctrl_min;
double m_ctrl_max;
double m_g;
double m_b;
};
typedef branch DBranch_t;
class Branch : public Object {
private:
DBranch_t m_branch;
double m_p_km;
double m_p_mk;
double m_q_km;
double m_q_mk;
double m_p_km_L;
double m_p_mk_L;
double m_q_km_L;
double m_q_mk_L;
double m_l;
public:
Branch();
virtual ~Branch();
static TypeId GetTypeId();
void SetBranch(DBranch_t branch);
DBranch_t GetBranch() const;
/*double CalcPkm(DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM, double theta_km);
double CalcPmk(DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM, double theta_km);
double CalcQkm(DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM, double theta_km);
double CalcQmk(DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM, double theta_km);*/
double CalcPkmL(DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM);
double CalcPmkL(DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM);
double CalcQkmL(DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM);
double CalcQmkL(DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM);
double CalcL (DoubleValue vK, DoubleValue vM,
DoubleValue aK, DoubleValue aM);
void Print(void);
};
}
#endif /* BRANCH_H_ */
<file_sep>/load-flow.h
#ifndef LOAD_FLOW_H_
#define LOAD_FLOW_H_
#include "graph.h"
#include "jacobian.h"
#include "mismatches.h"
#include "utils.h"
#include "control.h"
#include "q-control.h"
#include "report.h"
#include "max-q.h"
#include "vsf.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
#include <string>
namespace ns3
{
class LoadFlow : public Object
{
private:
Ptr<Graph> m_graph;
Ptr<Control> m_qControl;
Ptr<Mismatch> m_mismatches;
Ptr<Jacobian> m_jac;
Ptr<Report> m_report;
Ptr<VControl> m_vControl;
Sts_t m_sts;
double m_precision;
double m_totalL;
uint32_t m_iter;
uint32_t m_maxIter;
vec m_losses;
vec m_b;
void InitX0(void);
void InitJ(void);
void CalcLosses(void);
bool m_verbose;
std::string m_dir;
std::string m_file;
public:
LoadFlow(void);
virtual ~LoadFlow(void);
static TypeId GetTypeId(void);
Ptr<Graph> GetGraph(void) const;
//void SetGraph(Ptr<Graph> graph);
Ptr<Control> GetQControl(void) const;
void SetQControl(Ptr<Control> qControl);
void SetVControl (Ptr<VControl> vControl);
void Prepare(std::string cdf);
void Execute();
void SetPrecision(double precision);
void SetDir(std::string dir);
void SetFile(std::string file);
void Reset (void);
};
}
#endif /* LOAD_FLOW */
<file_sep>/io-utils.h
#ifndef IO_UTILS_H_
#define IO_UTILS_H_
#include "ns3/object.h"
#include "ns3/type-id.h"
#include "ns3/graph.h"
#include <vector>
#include <string>
namespace ns3
{
struct data
{
public:
std::string m_label;
double m_value;
};
typedef data Data_t;
class IOUtils : public Object {
public:
IOUtils();
virtual ~IOUtils();
static TypeId GetTypeId();
static std::string Print(std::vector<Data_t> values, uint8_t numSpace = 8);
static std::string Format(double v, uint32_t p = 5, uint32_t maxS = 10);
static std::string Format (std::string v, uint32_t maxS = 9);
static std::string WriteCdf(Ptr<Graph> graph, double getBase);
static std::string WriteCnz(Ptr<Graph> graph, double getBase);
static void WriteFile (std::string filename, uint32_t choose, Ptr<Graph> graph, double base = 100);
static const std::string SEP;
};
}
#endif /* BRANCH_H_ */
<file_sep>/v-control.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2016 UFPI (Universidade Federal do Piauí)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: <NAME> <<EMAIL>>
* Author: <NAME> <<EMAIL>>
*/
#include "v-control.h"
#include <ns3/assert.h>
#include <ns3/double.h>
#include <ns3/log.h>
namespace ns3
{
Ptr<Bus>
VControl::MaxDsv (Ptr<Graph> graph)
{
Ptr<Bus> maxBus = graph->GetBus (1);
double maxDsv = maxBus->GetDsv ();
for (uint32_t i = 1; i <= graph->GetNumBus (); i++)
{
Ptr<Bus> bus = graph->GetBus (i);
if (bus->GetType () != Bus::LOAD &&
bus->GetType () != Bus::LOSS_CONTROL_REACT)
{
continue;
}
if (bus->GetDsv () > maxDsv)
{
maxBus = bus;
maxDsv = bus->GetDsv ();
}
}
return maxBus;
}
uint32_t
VControl::MaxV (Ptr<Graph> graph, arma::vec vt, Ptr<Bus> modBus)
{
double maxQ = vt (0);
uint32_t maxBus = 1;
for (uint32_t i = 0; i < vt.n_elem; ++i)
{
Ptr<Bus> crtBus = graph->GetBus (i+1);
if (crtBus->GetType () == Bus::LOAD ||
crtBus->GetType () == Bus::LOSS_CONTROL_REACT)
{
continue;
}
crtBus->SetCrt (vt (i));
DoubleValue v;
crtBus->GetAttribute ("VCalc", v);
if (v.Get () == Bus::MAX_VOLTAGE_ONS && modBus->GetStatus () == Bus::MIN_VOLTAGE_VIOLATION)
{
continue;
}
if (v.Get () == Bus::MIN_VOLTAGE_GR && modBus->GetStatus () == Bus::MAX_VOLTAGE_VIOLATION)
{
continue;
}
if (vt (i) > maxQ)
{
maxQ = vt (i);
maxBus = i + 1;
}
}
return maxBus;
}
TypeId
VControl::GetTypeId(void)
{
static TypeId tid = TypeId ("ns3::VControl")
.SetParent<Object> ()
;
return tid;
}
}
<file_sep>/graph.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2016 UFPI (Universidade Federal do Piauí)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: <NAME> <<EMAIL>>
* Author: <NAME> <<EMAIL>>
*/
#include "graph.h"
#include "ns3/log.h"
#include "ns3/uinteger.h"
#include "ns3/double.h"
namespace ns3
{
NS_LOG_COMPONENT_DEFINE ("Graph");
NS_OBJECT_ENSURE_REGISTERED (Graph);
Graph::Graph () :
m_numBus(0), m_numBranch(0),
m_numPQ (0), m_numPV (0),
m_numSlack (0)
{
}
Graph::~Graph ()
{
m_buses.clear ();
m_numBus = 0;
m_numBranch = 0;
m_numPQ = 0;
m_numPV = 0;
m_numSlack = 0;
}
TypeId
Graph::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::Graph")
.SetParent<Object> ()
.AddConstructor<Graph> ()
.AddAttribute("NumBus",
"Number of Buses",
UintegerValue (0), /* TODO */
MakeDoubleAccessor (&Graph::m_numBus),
MakeDoubleChecker<uint32_t> ())
.AddAttribute("NumBranch",
"Number of Branches",
UintegerValue (0), /* TODO */
MakeDoubleAccessor (&Graph::m_numBranch),
MakeDoubleChecker<uint32_t> ())
.AddAttribute("NumPQ",
"Number of PQ buses",
UintegerValue (0), /* TODO */
MakeDoubleAccessor (&Graph::m_numPQ),
MakeDoubleChecker<uint32_t> ())
.AddAttribute("NumPV",
"Number of PQ buses",
UintegerValue (0), /* TODO */
MakeDoubleAccessor (&Graph::m_numPV),
MakeDoubleChecker<uint32_t> ())
.AddAttribute("NumSlack",
"Number of Slack buses",
UintegerValue (1), /* TODO */
MakeDoubleAccessor (&Graph::m_numSlack),
MakeDoubleChecker<uint32_t> ())
;
return tid;
}
void
Graph::AddBus(Ptr<Bus> bus)
{
uint32_t id = bus->GetBus ().m_nin;
m_buses.insert (std::pair<uint32_t, Ptr<Bus> > (id, bus));
m_numBus++;
if (bus->GetBus ().m_tipo == Bus::SLACK)
{
bus->SetType (Bus::SLACK);
bus->SetAttribute ("VCalc", DoubleValue (bus->GetBus ().m_v));
bus->SetAttribute ("ACalc", DoubleValue (bus->GetBus ().m_ang));
m_numSlack++;
}
if (bus->GetBus ().m_tipo == Bus::GENERATION)
{
bus->SetType (Bus::GENERATION);
bus->SetAttribute ("VCalc", DoubleValue (bus->GetBus ().m_v));
bus->SetAttribute ("PCalc", DoubleValue (bus->GetBus ().m_pg));
m_numPV++;
}
if (bus->GetBus ().m_tipo == Bus::LOAD
|| bus->GetBus ().m_tipo == Bus::LOSS_CONTROL_REACT)
{
if (bus->GetBus ().m_tipo == 0)
{
bus->SetType (Bus::LOAD);
}
else if(bus->GetBus ().m_tipo == 4)
{
bus->SetType (Bus::LOSS_CONTROL_REACT);
}
bus->SetAttribute ("PCalc", DoubleValue (bus->GetBus ().m_pg));
bus->SetAttribute ("QCalc", DoubleValue (bus->GetBus ().m_qg));
m_numPQ++;
}
}
void
Graph::Assoc(Ptr<Branch> branch)
{
uint32_t idK = branch->GetBranch ().m_nf;
uint32_t idM = branch->GetBranch ().m_ni;
std::map<uint32_t, Ptr<Bus> >::iterator itK, itM;
Ptr<Bus> busK = m_buses.find(idK)->second;
Ptr<Bus> busM = m_buses.find(idM)->second;
busK->AddBranch (branch, busM);
busM->AddBranch (branch, busK);
m_branches.push_back (branch);
m_numBranch++;
}
std::map<uint32_t, Ptr<Bus> >
Graph::GetBuses() const
{
return m_buses;
}
uint32_t
Graph::GetNumBus() const
{
return m_numBus;
}
uint32_t
Graph::GetNumBranch() const
{
return m_numBranch;
}
Ptr<Bus>
Graph::GetBus(uint32_t idBus)
{
std::map<uint32_t, Ptr<Bus> >::iterator it = m_buses.find (idBus);
Ptr<Bus> bus = 0;
if (it != m_buses.end ())
{
bus = it->second;
}
return bus;
}
std::vector<Ptr<Branch> >
Graph::GetBranches() const
{
return m_branches;
}
uint32_t
Graph::GetPosSlack(void) const
{
return m_posSlack;
}
void
Graph::SetPosSlack (uint32_t posSlack)
{
m_posSlack = posSlack;
}
uint32_t
Graph::GetNumPQ () const
{
return m_numPQ;
}
void
Graph::SetNumPQ (uint32_t numPQ)
{
m_numPQ = numPQ;
}
uint32_t
Graph::GetNumPV () const
{
return m_numPV;
}
void
Graph::SetNumPV (uint32_t numPV)
{
m_numPV = numPV;
}
}
<file_sep>/graph.h
#ifndef GRAPH_H_
#define GRAPH_H_
#include "branch.h"
#include "bus.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
#include <string>
#include <map>
namespace ns3 {
class Graph : public Object
{
private:
uint32_t m_numBus;
uint32_t m_numBranch;
uint32_t m_numPQ;
uint32_t m_numPV;
uint32_t m_numSlack;
uint32_t m_posSlack;
//uint32_t m_noSlack;
std::map<uint32_t, Ptr<Bus> > m_buses;
std::vector<Ptr<Branch> > m_branches;
public:
Graph();
virtual ~Graph();
static TypeId GetTypeId (void);
void AddBus(Ptr<Bus> bus);
void Assoc(Ptr<Branch> branch);
uint32_t GetPosSlack(void) const;
void SetPosSlack (uint32_t posSlack);
std::map<uint32_t, Ptr<Bus> > GetBuses() const;
Ptr<Bus> GetBus(uint32_t idBus);
std::vector<Ptr<Branch> > GetBranches() const;
uint32_t GetNumBus() const;
uint32_t GetNumBranch() const;
uint32_t GetNumPQ() const;
void SetNumPQ (uint32_t numPQ);
void SetNumPV (uint32_t numPV);
uint32_t GetNumPV() const;
};
}
#endif // GRAPH_H_
<file_sep>/bus.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2016 UFPI (Universidade Federal do Piauí)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: <NAME> <<EMAIL>>
* Author: <NAME> <<EMAIL>>
*/
#include "bus.h"
#include "ns3/log.h"
#include "ns3/uinteger.h"
#include "ns3/double.h"
#include "ns3/boolean.h"
#include "ns3/io-utils.h"
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <sstream>
namespace ns3
{
NS_LOG_COMPONENT_DEFINE ("Bus");
NS_OBJECT_ENSURE_REGISTERED (Bus);
Bus::Bus() :
m_tap (Bus::IMP), m_crt (0.0)
{
m_dsv = 0;
m_isControlled = false;
}
Bus::~Bus()
{
}
TypeId
Bus::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::Bus")
.SetParent<Object> ()
.AddConstructor<Bus> ()
.AddAttribute("ACalc",
"Calculated Angle",
DoubleValue (0), /* TODO */
MakeDoubleAccessor (&Bus::m_aCalc),
MakeDoubleChecker<double> ())
.AddAttribute("VCalc",
"Calculated Voltage",
DoubleValue (0), /* TODO */
MakeDoubleAccessor (&Bus::m_vCalc),
MakeDoubleChecker<double> ())
.AddAttribute("QCalc",
"Calculated Q",
DoubleValue (0), /* TODO */
MakeDoubleAccessor (&Bus::m_qgCalc),
MakeDoubleChecker<double> ())
.AddAttribute("PCalc",
"Calculated P",
DoubleValue (0), /* TODO */
MakeDoubleAccessor (&Bus::m_pgCalc),
MakeDoubleChecker<double> ())
;
return tid;
}
void
Bus::SetBus(DBus_t bus)
{
m_bus = bus;
}
DBus_t
Bus::GetBus() const
{
return m_bus;
}
void
Bus::SetType(Bus::Type type)
{
m_type = type;
}
Bus::Type
Bus::GetType(void)
{
return m_type;
}
void
Bus::AddBranch(Ptr<Branch> branch, Ptr<Bus> neighbor)
{
m_branches.push_back (branch);
m_neighbors.push_back (neighbor);
}
std::vector<Ptr<Branch> >
Bus::GetBranches () const
{
return m_branches;
}
double
Bus::CalcPg (void)
{
double pgK = 0;
for (uint32_t i = 0; i < m_branches.size (); i++)
{
Ptr<Branch> branch = m_branches.at (i);
Ptr<Bus> busM = m_neighbors.at (i);
DBranch_t dataBranch = branch->GetBranch ();
DoubleValue aM, vM;
busM->GetAttribute ("ACalc", aM);
busM->GetAttribute ("VCalc", vM);
double theta_km = m_aCalc - aM.Get ();
double vK = m_vCalc;
if (m_bus.m_nin == dataBranch.m_nf)
{
pgK += ( dataBranch.m_g * (1 / pow(dataBranch.m_tap, 2)) *
pow(vK, 2) - (1 / dataBranch.m_tap) * vK * vM.Get () *
( dataBranch.m_g * cos (theta_km - dataBranch.m_def) +
dataBranch.m_b * sin (theta_km - dataBranch.m_def) ) );
}
else
{
pgK += ( dataBranch.m_g * pow(vK, 2) - (1 / dataBranch.m_tap) *
vK * vM.Get () * ( dataBranch.m_g * cos(theta_km + dataBranch.m_def) +
dataBranch.m_b * sin(theta_km + dataBranch.m_def) ) );
}
}
pgK += - GetBus ().m_gsh * pow(m_vCalc, 2) + GetBus ().m_pc;
m_pgCalc = pgK;
return m_pgCalc;
}
double
Bus::CalcQg (void)
{
double qgK = 0;
for (uint32_t i = 0; i < m_branches.size (); i++)
{
Ptr<Branch> branch = m_branches.at (i);
Ptr<Bus> busM = m_neighbors.at (i);
DBranch_t dataBranch = branch->GetBranch ();
DoubleValue aM, vM;
busM->GetAttribute ("ACalc", aM);
busM->GetAttribute ("VCalc", vM);
double theta_km = m_aCalc - aM.Get ();
double vK = m_vCalc;
if (m_bus.m_nin == dataBranch.m_ni)
{
qgK += ( -(dataBranch.m_b * (1 / pow(dataBranch.m_tap, 2)) + dataBranch.m_bsh) *
pow(vK, 2) + (1 / dataBranch.m_tap) * vK * vM.Get () *
( dataBranch.m_b * cos (theta_km - dataBranch.m_def) -
dataBranch.m_g * sin (theta_km - dataBranch.m_def) ) );
}
else
{
qgK += ( -dataBranch.m_b * pow(vK, 2) + ( 1 / dataBranch.m_tap) * vK *vM.Get () *
( dataBranch.m_b * cos (theta_km + dataBranch.m_def) - dataBranch.m_g *
sin (theta_km + dataBranch.m_def) ) );
}
}
qgK += - GetBus ().m_bsh * pow(m_vCalc, 2) + GetBus ().m_qc;
m_qgCalc = qgK;
return m_qgCalc;
}
std::vector<Ptr<Bus> >
Bus::GetNeighbors (void) const
{
return m_neighbors;
}
void
Bus::SetTap(Bus::TapType tap)
{
m_tap = tap;
}
Bus::TapType
Bus::GetTap(void) const
{
return m_tap;
}
void
Bus::Print(void)
{
std::cout << m_bus.m_nin << "\t" << IOUtils::Format(m_vCalc) << IOUtils::Format(m_aCalc) << std::endl;
}
void
Bus::SetCrt(double crt)
{
m_crt = crt;
}
double
Bus::GetCrt(void) const
{
return m_crt;
}
double
Bus::CalcDsv (void)
{
DoubleValue v;
GetAttribute("VCalc", v);
m_dsv = 0;
if(v.Get () < Bus::MIN_VOLTAGE_ONS)
{
m_dsv = Bus::MIN_VOLTAGE_ONS - v.Get ();
m_status = MIN_VOLTAGE_VIOLATION;
m_isControlled = true;
}
if (v.Get () > Bus::MAX_VOLTAGE_ONS)
{
m_dsv = v.Get () - Bus::MAX_VOLTAGE_ONS;
m_status = MAX_VOLTAGE_VIOLATION;
m_isControlled = true;
}
return m_dsv;
}
double
Bus::GetDsv(void)
{
return m_dsv;
}
Bus::Violation
Bus::GetStatus (void)
{
return m_status;
}
bool
Bus::IsControlled(void)
{
return m_isControlled;
}
}
<file_sep>/q-control.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2016 UFPI (Universidade Federal do Piauí)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: <NAME> <<EMAIL>>
* Author: <NAME> <<EMAIL>>
*/
#include "q-control.h"
#include "graph.h"
#include <ns3/double.h>
#include <ns3/log.h>
#include <ns3/uinteger.h>
#include <ns3/assert.h>
#include <map>
#include <math.h>
#include <vector>
namespace ns3
{
QControl::QControl ()
{
}
QControl::~QControl ()
{
}
TypeId
QControl::GetTypeId(void)
{
static TypeId tid = TypeId ("ns3::QControl")
.SetParent<Object> ()
.AddConstructor<QControl> ()
;
return tid;
}
bool
QControl::DoControl (Ptr<Graph> graph)
{
// Cálculo da geração de potência reativa e teste de violação dos limites:
bool update = false;
for (uint32_t i = 0; i < graph->GetNumBus (); i++)
{
Ptr<Bus> busK = graph->GetBus (i + 1);
if (busK->GetType () == Bus::SLACK ||
busK->GetType () == Bus::GENERATION)
{
double qg = 0;
std::vector<Ptr<Branch> > branches = busK->GetBranches ();
std::vector<Ptr<Bus> > neighbors = busK->GetNeighbors ();
for (uint32_t i = 0; i < branches.size (); i++)
{
DBranch_t dataBranch = branches.at (i)->GetBranch ();
Ptr<Bus> busM = neighbors.at (i);
DoubleValue vK, vM, aK, aM;
busK->GetAttribute ("VCalc", vK);
busM->GetAttribute ("VCalc", vM);
busK->GetAttribute ("ACalc", aK);
busM->GetAttribute ("ACalc", aM);
double theta_km = aK.Get () - aM.Get ();
//if (busK->GetBus ().m_nin == dataBranch.m_ni)
if (dataBranch.m_tipo == 1 && busK->GetTap () == Bus::TAP)
{
/*
* s.bus.qg(k) =
* (-(s.branch.b(km)*(1/(s.branch.tap(km)^2))+s.branch.bsh(km))*
* s.bus.v(k)^2 + (1/s.branch.tap(km))*s.bus.v(k)*s.bus.v(m) *
* (s.branch.b(km)*cos(akm - s.branch.def(km))-s.branch.g(km)*sin(akm - s.branch.def(km)))) +
* s.bus.qg(k);
*/
double a = -(dataBranch.m_b * (1 / pow(dataBranch.m_tap, 2)) + dataBranch.m_bsh);
double b = pow(vK.Get (), 2);
double c = (1 / dataBranch.m_tap) * vK.Get () * vM.Get ();
double d = dataBranch.m_b * cos(theta_km - dataBranch.m_def) - dataBranch.m_g *
sin(theta_km - dataBranch.m_def);
qg = (a * b + c * d) + qg;
}
else
{
/*
* s.bus.qg(k) = (-s.branch.b(km)*s.bus.v(k)^2 + (1/s.branch.tap(km)) *
* s.bus.v(k)*s.bus.v(m)*(s.branch.b(km)*cos(akm + s.branch.def(km)) -
* s.branch.g(km)*sin(akm + s.branch.def(km)))) + s.bus.qg(k);
*/
qg = (-(dataBranch.m_b) * pow(vK.Get (), 2) +
(1 / dataBranch.m_tap) * vK.Get () * vM.Get () *
(dataBranch.m_b * cos (theta_km + dataBranch.m_def) - dataBranch.m_g *
sin(theta_km + dataBranch.m_def)) ) + qg;
}
}
DoubleValue vK, aK, qgK;
busK->GetAttribute ("VCalc", vK);
busK->GetAttribute ("ACalc", aK);
// s.bus.qg(k) = - s.bus.bsh(k)*s.bus.v(k)^2 + s.bus.qc(k) + s.bus.qg(k);
qg = - busK->GetBus ().m_bsh * pow(vK.Get (), 2) + busK->GetBus ().m_qc + qg;
/*std::cout << "Bus" << busK->GetBus ().m_nin << ", Qg = " << qg << ", qgMin = " << busK->GetBus ().m_qgmin <<
", qgMax = " << busK->GetBus ().m_qgmax << ", ThetaK = " << aK.Get () << std::endl;*/
if (busK->GetBus ().m_nin == 2)
{
std::cout << "Qg = " << qg << std::endl;
}
if (qg < busK->GetBus ().m_qgmin)
{
qg = busK->GetBus ().m_qgmin;
busK->SetType (Bus::LOSS_CONTROL_REACT);
update = true;
}
else if (qg > busK->GetBus ().m_qgmax)
{
qg = busK->GetBus ().m_qgmax;
busK->SetType (Bus::LOSS_CONTROL_REACT);
update = true;
}
qgK.Set(qg);
busK->SetAttribute ("QCalc", qgK);
}
}
if (update)
{
UpdateOrd (graph);
}
return update;
}
bool
QControl::DoRestore (Ptr<Graph> graph)
{
// Verificando quais barras recuperaram controle de reativo:
bool update = false;
for (uint32_t i = 0; i < graph->GetNumBus (); i++)
{
Ptr<Bus> busK = graph->GetBus (i + 1);
if (busK->GetType () == Bus::LOSS_CONTROL_REACT)
{
DoubleValue vK, qgK;
busK->GetAttribute("VCalc", vK);
busK->GetAttribute("QCalc", qgK);
if (qgK.Get () == busK->GetBus ().m_qgmin &&
vK.Get () <= busK->GetBus ().m_v)
{
std::cout << "Min = " << vK.Get () << ", " << busK->GetBus ().m_v << std::endl;
busK->SetAttribute("QCalc", DoubleValue (0));
busK->SetType (Bus::GENERATION);
update = true;
}
if (qgK.Get () == busK->GetBus ().m_qgmax &&
vK.Get () >= busK->GetBus ().m_v)
{
std::cout << "Max = " << vK.Get () << ", " << busK->GetBus ().m_v << std::endl;
busK->SetAttribute("QCalc", DoubleValue (0));
busK->SetType (Bus::GENERATION);
update = true;
}
}
}
if (update)
{
UpdateOrd (graph);
}
return update;
}
void
QControl::UpdateOrd(Ptr<Graph> graph)
{
uint32_t cont = 0;
uint32_t cont1 = 0;
uint32_t cont2 = 0;
uint32_t npv = 0;
uint32_t npq = 0;
for (uint32_t i = 0; i < graph->GetNumBus (); i++)
{
Ptr<Bus> bus = graph->GetBus (i+1);
DBus_t oldBus = bus->GetBus ();
DBus_t newBus = oldBus;
if (bus->GetType () == Bus::GENERATION)
{
newBus.m_ord = cont++;
newBus.m_ordPV = cont1++;
newBus.m_posPQ = i;
bus->SetBus (newBus);
npv++;
}
if (bus->GetType () == 1 || bus->GetType () == Bus::LOAD ||
bus->GetType () == Bus::LOSS_CONTROL_REACT)
{
newBus.m_ord = cont++;
newBus.m_ordPQ = cont2++;
newBus.m_posPQ = i;
bus->SetBus (newBus);
npq++;
}
graph->SetNumPQ (npq);
graph->SetNumPV (npv);
}
}
}
<file_sep>/control.h
#ifndef CONTROL_H_
#define CONTROL_H_
#include "graph.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
namespace ns3
{
class Control : public Object
{
public:
/*Control();
virtual ~Control();*/
static TypeId GetTypeId(void);
virtual bool DoControl (Ptr<Graph> graph) = 0;
virtual bool DoRestore (Ptr<Graph> graph) = 0;
};
}
#endif /* CONTROL_H_ */
<file_sep>/v-control.h
#ifndef V_CONTROL_H_
#define V_CONTROL_H_
#include "graph.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
#include <armadillo>
namespace ns3
{
class VControl : public Object
{
public:
static TypeId GetTypeId(void);
Ptr<Bus> MaxDsv (Ptr<Graph> graph);
uint32_t MaxV (Ptr<Graph> graph, arma::vec vt, Ptr<Bus> modBus);
virtual bool DoControl (arma::mat jqv, Ptr<Graph> graph) = 0;
};
}
#endif /* V_CONTROL_H_ */
<file_sep>/vsf.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2016 UFPI (Universidade Federal do Piauí)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: <NAME> <<EMAIL>>
* Author: <NAME> <<EMAIL>>
*/
#include "vsf.h"
#include "graph.h"
#include <ns3/double.h>
#include <ns3/log.h>
#include <ns3/uinteger.h>
#include <ns3/assert.h>
#include <armadillo>
#include <map>
#include <math.h>
#include <vector>
using namespace arma;
namespace ns3
{
NS_LOG_COMPONENT_DEFINE ("Vsf");
NS_OBJECT_ENSURE_REGISTERED (Vsf);
Vsf::Vsf ()
{
}
Vsf::~Vsf ()
{
}
TypeId
Vsf::GetTypeId(void)
{
static TypeId tid = TypeId ("ns3::Vsf")
.SetParent<Object> ()
.AddConstructor<Vsf> ()
;
return tid;
}
bool
Vsf::DoControl (mat jqv, Ptr<Graph> graph)
{
bool control = false;
vec deltaV = zeros<vec> (jqv.n_cols);
for (uint32_t i = 1; i <= graph->GetNumBus (); i++)
{
Ptr<Bus> bus = graph->GetBus (i);
if (bus->GetType () != Bus::LOAD &&
bus->GetType () != Bus::LOSS_CONTROL_REACT)
{
continue;
}
double dsv = bus->CalcDsv();
if (dsv != 0)
{
deltaV (i - 1) = dsv;
control = true;
}
}
if (control == true)
{
Ptr<Bus> maxVlt = MaxDsv (graph);
mat invJqv = inv (jqv);
subview_col<double> s = invJqv.col(maxVlt->GetBus ().m_nin - 1);
vec vsf = zeros<vec> (s.n_elem);
for(uint32_t i = 0; i < s.n_elem; i++)
{
vsf (i) = s (i);
}
uint32_t idBus = MaxV (graph, vsf, maxVlt);
DoubleValue t;
maxVlt->GetAttribute ("VCalc", t);
std::cout << "Max Vlt = " << maxVlt->GetBus ().m_nin << " = " << t.Get () << ", Max = " << vsf (idBus - 1) << ", IdBus = " << idBus << std::endl;
vec aux = zeros<vec> (vsf.n_elem);
aux (idBus - 1) = vsf (idBus - 1);
vec deltaVIjt = inv (jqv) * aux;
double m_alpha = 1;
double value = fabs (deltaVIjt (idBus - 1));
while (m_alpha * value < LIMIAR)
{
m_alpha++;
}
std::cout << "Variação de Tensão => " << value << ", alpha = " << m_alpha << "\n";
Ptr<Bus> bus = graph->GetBus (idBus);
value = deltaVIjt (idBus - 1);
if (maxVlt->GetStatus () == Bus::MIN_VOLTAGE_VIOLATION && value < 0)
{
value = fabs (value);
}
if (maxVlt->GetStatus () == Bus::MAX_VOLTAGE_VIOLATION && value > 0)
{
value *= -1;
}
DoubleValue v;
bus->GetAttribute("VCalc", v);
double newValue = v.Get () + (value * m_alpha);
if (newValue < Bus::MIN_VOLTAGE_GR)
{
newValue = Bus::MIN_VOLTAGE_GR;
}
if (newValue > Bus::MAX_VOLTAGE_ONS)
{
newValue = Bus::MAX_VOLTAGE_ONS;
}
std::cout << "Value = " << v.Get () << " Bus = " << bus->GetType () << ", Voltage + value = " << (newValue) << std::endl;
bus->SetAttribute ("VCalc", DoubleValue (newValue));
}
return control;
}
}
<file_sep>/jacobian.h
#ifndef JACOBIAN_H_
#define JACOBIAN_H_
#include "graph.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
#include <armadillo>
using namespace arma;
namespace ns3
{
class Jacobian : public Object
{
public:
Jacobian();
virtual ~Jacobian();
static TypeId GetTypeId();
mat GetMatrix () const;
void SetMatrix (uint64_t numLines, uint64_t numCols);
void SetJ1(uint64_t numRows, uint64_t numCols);
mat GetJ1 () const;
void SetJ2(uint64_t numRows, uint64_t numCols);
mat GetJ2 () const;
void SetJ3(uint64_t numRows, uint64_t numCols);
mat GetJ3 () const;
void SetJ4(uint64_t numRows, uint64_t numCols);
mat GetJ4 () const;
mat CalcJac(Ptr<Graph> graph);
vec SolveSys (vec b);
void Zeros (void);
void Zeros (uint32_t numRows, uint32_t numCols);
mat GetJqv(void);
private:
mat m_matrix;
mat m_j1;
mat m_j2;
mat m_j3;
mat m_j4;
mat m_jqv;
void CalcDPk(Ptr<Graph> graph);
void CalcDQk(Ptr<Graph> graph);
void CalcJDQ(Ptr<Graph> graph);
void CalcJqv (void);
};
}
#endif // JACOBIAN_H_
<file_sep>/mismatches.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2016 UFPI (Universidade Federal do Piauí)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: <NAME> <<EMAIL>>
* Author: <NAME> <<EMAIL>>
*/
#include "mismatches.h"
#include "graph.h"
#include <ns3/log.h>
#include <math.h>
#include <iostream>
namespace ns3
{
NS_LOG_COMPONENT_DEFINE ("Mismatch");
NS_OBJECT_ENSURE_REGISTERED (Mismatch);
Mismatch::Mismatch ()
{
}
Mismatch::~Mismatch ()
{
}
TypeId
Mismatch::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Mismatch")
.SetParent<Object> ()
.AddConstructor<Mismatch> ()
;
return tid;
}
void
Mismatch::CalcPkB (Ptr<Graph> graph)
{
// Balanço de potência ativa:
for (uint32_t i = 0; i < graph->GetNumBus (); i++)
{
Ptr<Bus> busK = graph->GetBus (i+1);
if (busK->GetType () == Bus::SLACK)
{
continue;
}
uint32_t k = busK->GetBus ().m_ord;
m_mis (k) = 0;
std::vector<Ptr<Branch> > branches = busK->GetBranches();
std::vector<Ptr<Bus> > neighbors = busK->GetNeighbors ();
for (uint32_t j = 0; j < branches.size (); j++)
{
DBranch_t dataBranch = branches.at (j)->GetBranch ();
Ptr<Bus> busM = neighbors.at (j);
DoubleValue vK, vM, aK, aM;
busK->GetAttribute ("VCalc", vK);
busM->GetAttribute ("VCalc", vM);
busK->GetAttribute ("ACalc", aK);
busM->GetAttribute ("ACalc", aM);
double theta_km = aK.Get () - aM.Get ();
//if (busK->GetBus ().m_nin == dataBranch.m_ni)
if (dataBranch.m_tipo == 1 && busK->GetTap () == Bus::TAP)
{
/*mis(k-1) =
(s.branch.g(km)*(1/s.branch.tap(km)^2)*s.bus.v(k)^2 -
(1/s.branch.tap(km))*s.bus.v(k)*s.bus.v(m)*
(s.branch.g(km)*cos(akm - s.branch.def(km))+s.branch.b(km)*
sin(akm - s.branch.def(km)))) + mis(k-1);
*/
m_mis(k) = (dataBranch.m_g * 1 / pow (dataBranch.m_tap, 2) * pow(vK.Get (), 2) -
(1 / dataBranch.m_tap) * vK.Get () * vM.Get () *
( dataBranch.m_g * cos(theta_km - dataBranch.m_def) +
dataBranch.m_b * sin(theta_km - dataBranch.m_def) ) ) + m_mis(k);
}
else
{
/*
* mis(k-1) = (s.branch.g(km)*s.bus.v(k)^2 - (1/s.branch.tap(km))*
* s.bus.v(k)*s.bus.v(m)*(s.branch.g(km)*cos(akm + s.branch.def(km))+
* s.branch.b(km)*sin(akm + s.branch.def(km)))) + mis(k-1);
*/
m_mis(k) = (dataBranch.m_g * pow(vK.Get (), 2) -
(1 / dataBranch.m_tap) * vK.Get () * vM.Get () *
( dataBranch.m_g * cos(theta_km + dataBranch.m_def) +
dataBranch.m_b * sin(theta_km + dataBranch.m_def) ) ) + m_mis(k);
}
}
DoubleValue vK, pgK;
busK->GetAttribute ("VCalc", vK);
busK->GetAttribute("PCalc", pgK);
/*
* s.bus.pg(k) + s.bus.gsh(k)*s.bus.v(k)^2 - s.bus.pc(k) - mis(k-1);
*/
m_mis(k) = pgK.Get () + busK->GetBus ().m_gsh *
pow(vK.Get (), 2) - busK->GetBus ().m_pc - m_mis(k);
}
}
void
Mismatch::CalcQkB (Ptr<Graph> graph)
{
// Balanço de potência reativa:
for (uint32_t i = 0; i < graph->GetNumBus (); i++)
{
Ptr<Bus> busK = graph->GetBus (i + 1);
if (busK->GetType() == Bus::LOSS_CONTROL_REACT ||
busK->GetType () == Bus::LOAD)
{
uint32_t index = graph->GetNumBus () - 1 + busK->GetBus ().m_ordPQ;
m_mis (index) = 0;
std::vector<Ptr<Branch> > branches = busK->GetBranches();
std::vector<Ptr<Bus> > neighbors = busK->GetNeighbors ();
for (uint32_t j = 0; j < branches.size (); j++)
{
DBranch_t dataBranch = branches.at (j)->GetBranch ();
Ptr<Bus> busM = neighbors.at (j);
DoubleValue vK, vM, aK, aM;
busK->GetAttribute ("VCalc", vK);
busM->GetAttribute ("VCalc", vM);
busK->GetAttribute ("ACalc", aK);
busM->GetAttribute ("ACalc", aM);
double theta_km = aK.Get () - aM.Get ();
//if (busK->GetBus ().m_nin == dataBranch.m_ni)
if (dataBranch.m_tipo == 1 && busK->GetTap () == Bus::TAP)
{
/*
* mis(s.nb-1+s.bus.ordPQ(k)) =
* (-(s.branch.b(km)*(1/(s.branch.tap(km)^2))+s.branch.bsh(km))*
* s.bus.v(k)^2 + (1/s.branch.tap(km))*s.bus.v(k)*s.bus.v(m)*
* (s.branch.b(km)*cos(akm - s.branch.def(km))-s.branch.g(km)*
* sin(akm - s.branch.def(km)))) + mis(s.nb-1+s.bus.ordPQ(k));
*/
m_mis(index) = (-(dataBranch.m_b * (1 / pow(dataBranch.m_tap, 2)) + dataBranch.m_bsh ) *
pow (vK.Get (), 2) + (1/dataBranch.m_tap) * vK.Get () * vM.Get () *
(dataBranch.m_b * cos(theta_km - dataBranch.m_def) - dataBranch.m_g *
sin(theta_km - dataBranch.m_def) ) ) + m_mis(index);
}
else
{
/*
* mis(s.nb-1+s.bus.ordPQ(k)) =
* (-s.branch.b(km)*s.bus.v(k)^2 + (1/s.branch.tap(km))*s.bus.v(k)*
* s.bus.v(m)*(s.branch.b(km)*cos(akm + s.branch.def(km))-s.branch.g(km)*
* sin(akm + s.branch.def(km)))) + mis(s.nb-1+s.bus.ordPQ(k));
*/
m_mis(index) = (-(dataBranch.m_b) * pow (vK.Get (), 2) +
(1/dataBranch.m_tap) * vK.Get () * vM.Get () *
(dataBranch.m_b * cos(theta_km + dataBranch.m_def) - dataBranch.m_g *
sin(theta_km + dataBranch.m_def) ) ) + m_mis(index);
}
}
DoubleValue vK, qgK;
busK->GetAttribute ("VCalc", vK);
busK->GetAttribute("QCalc", qgK);
/*
* mis(s.nb-1+s.bus.ordPQ(k)) =
* s.bus.qg(k) + s.bus.bsh(k)*s.bus.v(k)^2 - s.bus.qc(k) - mis(s.nb-1+s.bus.ordPQ(k));
*/
m_mis(index) = qgK.Get () + busK->GetBus ().m_bsh * pow (vK.Get (), 2) -
busK->GetBus ().m_qc - m_mis(index);
}
}
}
vec
Mismatch::CalcMismatches(Ptr<Graph> graph)
{
m_mis = zeros<vec>(graph->GetNumPQ () * 2 + graph->GetNumPV ());
CalcPkB (graph);
CalcQkB (graph);
return GetMis ();
}
vec
Mismatch::GetMis(void)
{
return m_mis;
}
}
<file_sep>/q-control.h
#ifndef QCONTROL_H_
#define QCONTROL_H_
#include "control.h"
#include "graph.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
namespace ns3
{
class QControl : public Control
{
private:
void UpdateOrd(Ptr<Graph> graph);
public:
QControl();
virtual ~QControl();
static TypeId GetTypeId(void);
virtual bool DoControl (Ptr<Graph> graph);
virtual bool DoRestore (Ptr<Graph> graph);
};
}
#endif /* QCONTROL_H_ */
<file_sep>/max-q.h
#ifndef MAX_Q_H_
#define MAX_Q_H_
#include "v-control.h"
#include "graph.h"
#include "jacobian.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
namespace ns3
{
class MaxQ : public VControl
{
public:
MaxQ();
virtual ~MaxQ();
static TypeId GetTypeId(void);
virtual bool DoControl (mat jqv, Ptr<Graph> graph);
//uint32_t MaxV (Ptr<Graph> graph, vec q, Ptr<Bus> modBus);
static const double LIMIAR = 0.01;
};
}
#endif /* MaxQ_H_ */
<file_sep>/mismatches.h
#ifndef MISMATCHES_H_
#define MISMATCHES_H_
#include "graph.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
#include <armadillo>
using namespace arma;
namespace ns3
{
class Mismatch : public Object
{
private:
vec m_mis;
void CalcPkB(Ptr<Graph> graph);
void CalcQkB(Ptr<Graph> graph);
public:
Mismatch();
virtual ~Mismatch();
static TypeId GetTypeId();
vec CalcMismatches(Ptr<Graph> graph);
vec GetMis(void);
};
}
#endif // MISMATCHES_H_
<file_sep>/bus.h
#ifndef BUS_H_
#define BUS_H_
#include "branch.h"
#include "ns3/ptr.h"
#include "ns3/object.h"
#include "ns3/type-id.h"
#include <string>
#include <vector>
namespace ns3
{
/*
* Struct to store buses variables
*/
struct bus
{
public:
uint32_t m_nex;
uint32_t m_nin;
std::string m_nome;
double m_area;
double m_zona;
uint32_t m_tipo;
double m_v;
double m_ang;
double m_pc;
double m_qc;
double m_pg;
double m_qg;
double m_base_kV;
double m_vg_o;
double m_qgmax;
double m_qgmin;
double m_vmax;
double m_vmin;
double m_gsh;
double m_bsh;
double m_crt;
uint32_t m_ctrl_rem;
uint32_t m_ordPV;
uint32_t m_posPV;
uint32_t m_ordPQ;
uint32_t m_posPQ;
uint32_t m_ord;
};
typedef bus DBus_t;
class Bus : public Object {
public:
enum Type
{
SLACK = 3,
GENERATION = 2,
LOAD = 0,
LOSS_CONTROL_REACT = 4
};
enum TapType
{
IMP = 0,
TAP = 1
};
enum Violation
{
NORMAL = 0,
MIN_VOLTAGE_VIOLATION = 1,
MAX_VOLTAGE_VIOLATION = 2
};
static const double MIN_VOLTAGE_GR = 0.95;
static const double MIN_VOLTAGE_IEEE = 1.10;
static const double MIN_VOLTAGE_ONS = 0.95;
static const double MAX_VOLTAGE_ONS = 1.05;
static const double MAX_VOLTAGE_IEEE = 0.90;
static const double INCREMENT_STEP = 0.01;
Bus();
virtual ~Bus();
static TypeId GetTypeId();
DBus_t GetBus(void) const;
void SetBus(DBus_t bus);
Type GetType(void);
void SetType(enum Type);
void AddBranch(Ptr<Branch> branch, Ptr<Bus> neighbor);
std::vector<Ptr<Branch> > GetBranches() const;
std::vector<Ptr<Bus> > GetNeighbors() const;
double CalcPg(void);
double CalcQg (void);
void SetTap(TapType tap);
TapType GetTap(void) const;
void Print(void);
void SetCrt(double crt);
double GetCrt(void) const;
double CalcDsv(void);
double GetDsv(void);
Bus::Violation GetStatus (void);
bool IsControlled (void);
private:
double m_aCalc;
double m_vCalc;
double m_qgCalc;
double m_pgCalc;
double m_dsv;
TapType m_tap;
DBus_t m_bus;
std::vector<Ptr<Branch> > m_branches;
std::vector<Ptr<Bus> > m_neighbors;
Type m_type;
double m_crt;
Violation m_status;
bool m_isControlled;
};
}
#endif /* BUS_H_ */
|
64443c653af8246bf56f7630da7645136363bfcd
|
[
"C++"
] | 18 |
C++
|
tallisson/fluxo_carga
|
b0adb0508bc3003a68dc3e7ac4c529d30b9a8283
|
4bb9e438973ee2dab2722f4710adb22897a9a33b
|
refs/heads/master
|
<repo_name>heping56/gobang-1<file_sep>/src/View/ChooseLevel.java
package View;
import com.sun.awt.AWTUtilities;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.RoundRectangle2D;
/**
* Created by Blossoming on 2016/12/11.
*/
public class ChooseLevel extends JFrame implements MouseListener{
public static final int PRIMARY_LEVEL=1;
public static final int MEDIUM_LEVEL=2;
public static final int SENIOR_LEVEL=3;
public ChooseLevel()
{
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
setUndecorated(true);
setVisible(true);
setLayout(new FlowLayout());
setBounds(580, 185, 290, 390);
setResizable(false);
paintBg();
addMouseListener(this);
AWTUtilities.setWindowShape(this,
new RoundRectangle2D.Double(0D, 0D, this.getWidth(),
this.getHeight(), 24.0D, 24.0D));
}
public void paintBg() {
ImageIcon image = new ImageIcon("level.jpg");
JLabel la3 = new JLabel(image);
la3.setBounds(0, 0, this.getWidth(), this.getHeight());//添加图片,设置图片大小为窗口的大小。
this.getLayeredPane().add(la3, new Integer(Integer.MIN_VALUE)); //将JLabel加入到面板容器的最高层
JPanel jp = (JPanel) this.getContentPane();
jp.setOpaque(false); //设置面板容器为透明
}
@Override
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println(x+" "+y);
if(x>=65&&x<=222&&y>=92&&y<=120)
{
//初级场
dispose();
new PCMainBoard(PRIMARY_LEVEL);
}
else if(x>=65&&x<=222&&y>=170&&y<=206)
{
//中级场
dispose();
new PCMainBoard(MEDIUM_LEVEL);
}
else if(x>=65&&x<=222&&y>=257&&y<=291)
{
//高级场
dispose();
new PCMainBoard(SENIOR_LEVEL);
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
<file_sep>/src/View/PCChessBoard.java
package View;
import Control.JudgeWinner;
import Model.Chess;
import Model.Computer;
import Model.Coord;
import Net.NetTool;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* Created by Blossoming on 2016/12/6.
*/
public class PCChessBoard extends ChessBoard{
public static final int BACK_MESSAGE=1;
private int role;
private int comPos[]=new int[2];
private int result=1;
private PCMainBoard mb;
private WinDialog dialog;
private Computer com;
private int msg_back=0;
private int step[][]=new int[30*30][2];
private int stepCount=0;
private Coord coord=new Coord();
public void setMsg_back(){this.msg_back=msg_back;}
public int getMsg_back(){return msg_back;}
public void setResult(int result){this.result=result;}
public PCChessBoard(PCMainBoard mb)
{
this.mb=mb;
role=Chess.WHITE;
com=new Computer();
dialog=new WinDialog(mb,"恭喜",true);
setBorder(new LineBorder(new Color(0, 0, 0)));
}
/**
* 保存黑白棋子的坐标于二维数组中
* @param posX
* @param posY
*/
private void saveStep(int posX,int posY)
{
stepCount++;
step[stepCount][0]=posX;
step[stepCount][1]=posY;
}
public void backStep()
{
if(stepCount>=2)
{
chess[step[stepCount][0]][step[stepCount][1]]=0;
chess[step[stepCount-1][0]][step[stepCount-1][1]]=0;
stepCount=stepCount-2;
}
}
public void WinEvent(int winner)
{
//白棋赢
if(winner == Chess.WHITE) {
result=GAME_OVER;
try {
mb.getTimer().interrupt();
} catch (Exception e1) {
e1.printStackTrace();
}
mb.getBtn_startGame().setText("开始游戏");
mb.getBtn_startGame().setEnabled(true);
dialog.setWinnerInfo("白棋获胜!");
setClickable(MainBoard.CAN_NOT_CLICK_INFO);
dialog.setVisible(true);
if(dialog.getMsg()==WinDialog.BACK)
{
//System.exit(0);
mb.dispose();
new SelectMenu();
}
else
{
initArray();
//setClickable(MainBoard.CAN_CLICK_INFO);
}
}
//黑棋赢
else if(winner==Chess.BLACK){
result=GAME_OVER;
try {
mb.getTimer().interrupt();
} catch (Exception e1) {
e1.printStackTrace();
}
mb.getBtn_startGame().setText("开始游戏");
mb.getBtn_startGame().setEnabled(true);
setClickable(MainBoard.CAN_NOT_CLICK_INFO);
dialog.setWinnerInfo("黑棋获胜!");
dialog.setVisible(true);
if(dialog.getMsg()==WinDialog.BACK)
{
//System.exit(0);
mb.dispose();
new SelectMenu();
}
else
{
initArray();
//setClickable(MainBoard.CAN_CLICK_INFO);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
int winner;
if(clickable==MainBoard.CAN_CLICK_INFO) {
chessX = e.getX();
chessY = e.getY();
if (chessX < 524 && chessX > 50 && chessY < 523 && chessY > 50) {
float x = (chessX - 49) / 25;
float y = (chessY - 50) / 25;
int x1 = (int) x;
int y1 = (int) y;
//如果这个地方没有棋子
if (chess[x1][y1] == Chess.NO_CHESS) {
chess[x1][y1] = role;
saveStep(x1,y1);
setClickable(MainBoard.CAN_NOT_CLICK_INFO);
winner= JudgeWinner.PPJudge(x1, y1, chess, role);
WinEvent(winner);
if(result!=GAME_OVER) {
coord = com.computePos(Chess.BLACK, chess,mb.getLevel());
chess[coord.getX()][coord.getY()] = Chess.BLACK;
saveStep(coord.getX(),coord.getY());
winner = JudgeWinner.PPJudge(coord.getX(), coord.getY(), chess, Chess.BLACK);
WinEvent(winner);
if(result!=GAME_OVER) {
setClickable(MainBoard.CAN_CLICK_INFO);
}
}
}
}
}
}
}
<file_sep>/src/View/MainBoard.java
package View;
import Model.timerThread;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* Created by Blossoming on 2016/12/6.
*/
public class MainBoard extends JFrame implements MouseListener,ActionListener{
public static final int CAN_CLICK_INFO=1;
public static final int CAN_NOT_CLICK_INFO=0;
public JLabel label_timeCount;
public timerThread timer;
public int result=1;
private ChessLine cl;
public timerThread getTimer() {return timer;}
public JLabel getLabel() {return label_timeCount;}
public MainBoard()
{
setLayout(null);
setBounds(300,70,800,620);
init1();
//paintBg();
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setResizable(false);
setTitle("五子棋游戏");
}
public void paintBg() {
ImageIcon image = new ImageIcon("7.jpg");
JLabel la3 = new JLabel(image);
la3.setBounds(0, 0, this.getWidth(), this.getHeight());//添加图片,设置图片大小为窗口的大小。
this.getLayeredPane().add(la3, new Integer(Integer.MIN_VALUE)); //将JLabel加入到面板容器的最高层
JPanel jp = (JPanel) this.getContentPane();
jp.setOpaque(false); //设置面板容器为透明
}
public void paint(Graphics g)
{
super.paint(g);
repaint();
}
public void init1()
{
label_timeCount=new JLabel();
label_timeCount.setFont(new Font("Microsoft Yahei",Font.BOLD,30));
label_timeCount.setBounds(602, 50, 230, 40);
add(label_timeCount);
}
@Override
public void actionPerformed(ActionEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
<file_sep>/src/View/PPMainBoard.java
package View;
import Model.Chess;
import Model.timerThread;
import Net.NetTool;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
/**
* Created by Blossoming on 2016/11/30.
*/
public class PPMainBoard extends MainBoard {
private PPChessBoard cb;
private JButton btn_startGame;
private JButton btn_back;
private JTextArea ta_chess_info;
private JTextField tf_ip;
private String ip;
private DatagramSocket socket;
private String gameState;
private String enemyGameState;
//接收到发送端的信息
private ArrayList<String> enemyMsg;
private WinDialog dialog;
public JButton getBtn_startGame(){return btn_startGame;}
public String getIp() {return ip;}
public JTextField getTf() {return tf_ip;}
public DatagramSocket getSocket() {return socket;}
public PPMainBoard()
{
label_timeCount.setBounds(602, 330, 230, 40);
init();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public void init()
{
gameState="NOT_START";
enemyGameState="NOT_START";
enemyMsg=new ArrayList<String>();
tf_ip=new JTextField("请输入IP地址");
tf_ip.setBounds(582, 379, 200, 30);
tf_ip.addMouseListener(this);
btn_startGame=new JButton("准备游戏");
btn_startGame.setFocusPainted(false);
btn_startGame.setBackground(Color.CYAN);
btn_startGame.setFont(new Font(Font.DIALOG, Font.BOLD, 22));
btn_startGame.addActionListener(this);
btn_startGame.setBounds(582, 429, 200, 50);
btn_back=new JButton("退 出");
btn_back.setFocusPainted(false);
btn_back.setBackground(Color.CYAN);
btn_back.setFont(new Font(Font.DIALOG, Font.BOLD, 22));
btn_back.addActionListener(this);
btn_back.setBounds(582, 499, 200, 50);
ta_chess_info=new JTextArea();
//ta_chess_info.setFont(new Font(Font.DIALOG_INPUT,Font.BOLD,20));
ta_chess_info.setEnabled(false);
ta_chess_info.setBackground(Color.BLUE);
ta_chess_info.setForeground(Color.black);
//ta_chess_info.setBounds(550, 55, 230, 300);
JScrollPane p = new JScrollPane(ta_chess_info);
p.setBounds(582, 20, 200, 300);
dialog=new WinDialog(this,"恭喜",true);
cb=new PPChessBoard(this,dialog);
cb.setClickable(PPMainBoard.CAN_NOT_CLICK_INFO);
cb.setBounds(0, 20, 570, 585);
cb.setVisible(true);
cb.setInfoBoard(ta_chess_info);
add(tf_ip);
add(cb);
add(btn_startGame);
add(p);
add(btn_back);
// add(label_timeCount);
ReicThread();
repaint();
}
/**
* 接收信息放在线程中
*/
public void ReicThread()
{
new Thread(new Runnable()
{
public void run()
{
try
{
byte buf[]=new byte[1024];
socket=new DatagramSocket(2222);
DatagramPacket dp=new DatagramPacket(buf, buf.length);
while(true)
{
socket.receive(dp);
//0.接收到的发送端的主机名
InetAddress ia=dp.getAddress();
//enemyMsg.add(new String(ia.getHostName()));
//1.接收到的内容
String data=new String(dp.getData(),0,dp.getLength());
if(data.isEmpty())
{
cb.setClickable(CAN_NOT_CLICK_INFO);
}
else {
//enemyMsg.add(data);
String[] msg = data.split(",");
System.out.println(msg[0]);
//接收到对面准备信息并且自己点击了准备
if(msg[0].equals("ready"))
{
enemyGameState="ready";
System.out.println("对方已准备");
if(gameState.equals("ready"))
{
gameState="FIGHTING";
cb.setClickable(CAN_CLICK_INFO);
btn_startGame.setText("正在游戏");
timer=new timerThread(label_timeCount);
timer.start();
}
}
else if(msg[0].equals("POS")){
System.out.println("发送坐标");
//接受坐标以及角色
cb.setCoord(Integer.parseInt(msg[1]), Integer.parseInt(msg[2]), Integer.parseInt(msg[3]));
}
}
//2.接受到的IP地址
//enemyMsg.add(new String(ia.getAddress()));
//3.接收到的发送端的端口
//enemyMsg.add(dp.getPort()+"");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}).start();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn_startGame)
{
if(!tf_ip.getText().isEmpty()&&
!tf_ip.getText().equals("不能为空")&&
!tf_ip.getText().equals("请输入IP地址")&&
!tf_ip.getText().equals("不能连接到此IP")) {
ip=tf_ip.getText();
btn_startGame.setEnabled(false);
btn_startGame.setText("等待对方准备");
tf_ip.setEditable(false);
NetTool.sendUdpBroadCast(ip,"ready");
gameState="ready";
if(enemyGameState=="ready")
{
gameState="FIGHTING";
cb.setClickable(CAN_CLICK_INFO);
btn_startGame.setText("正在游戏");
timer=new timerThread(label_timeCount);
timer.start();
}
}
else
{
tf_ip.setText("不能为空");
}
}
else if(e.getSource()==btn_back)
{
System.exit(0);
}
}
}
<file_sep>/src/View/ChessBoard.java
package View;
import Model.Chess;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* Created by Blossoming on 2016/12/6.
*/
public class ChessBoard extends JPanel implements MouseListener{
public static final int GAME_OVER=0;
public static final int COLS=19;
public static final int RAWS=19;
public int result=1;
public Image whiteChess;
//黑白棋子
public Image chessBoardImage;
public Image laceImage;
public Image blackChess;
//棋子的横坐标
public int chessX;
//棋子的纵坐标
public int chessY;
//棋盘上隐形的坐标,每一个小区域代表一个数组元素
public int chess[][]=new int[COLS][RAWS];
public int clickable;
/**
* 构造函数,初始化棋盘的图片,初始化数组
* @param
*/
ChessBoard() {
chessBoardImage = Toolkit.getDefaultToolkit().getImage("gobang1.jpg");
whiteChess = Toolkit.getDefaultToolkit().getImage("white.png");
blackChess=Toolkit.getDefaultToolkit().getImage("black.png");
laceImage=Toolkit.getDefaultToolkit().getImage("lace.jpg");
initArray();
addMouseListener(this);
}
public void setClickable(int clickable)
{
this.clickable=clickable;
}
/**
* 初始化数组为全零
*/
public void initArray()
{
for(int i=0;i<19;i++)
{
for(int j=0;j<19;j++)
{
chess[i][j]= Chess.NO_CHESS;
}
}
}
/**
* 从父类继承的方法,自动调用,绘画图形
* @param g 该参数是绘制图形的句柄
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(laceImage,0,0,null);
g.drawImage(chessBoardImage, 35, 35,null);
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
if (chess[i][j] == Chess.BLACK) {
g.drawImage(blackChess, 60 + i * 25 - 11, 62 + j * 25 - 12, null);
} else if (chess[i][j] == Chess.WHITE) {
g.drawImage(whiteChess, 60 + i * 25 - 11, 62 + j * 25 - 12, null);
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
/**
* 按下鼠标时,记录鼠标的位置,并改写数组的数值,重新绘制图形
* @param e
*/
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
<file_sep>/src/View/WinDialog.java
package View;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Blossoming on 2016/12/5.
*/
public class WinDialog extends JDialog implements ActionListener{
public static final int RESTART=1;
public static final int BACK=0;
private JButton btn_restart,btn_back;
private JLabel label;
private int msg;
public WinDialog(JFrame f,String title,boolean b)
{
super(f,title,b);
setLayout(null);
setResizable(false);
setBounds(500,300,300,200);
init();
}
public int getMsg()
{
return msg;
}
public void setWinnerInfo(String winnerInfo)
{
label.setText(winnerInfo);
}
private void init()
{
btn_restart=new JButton("重新开始");
btn_restart.setFocusPainted(false);
btn_restart.setBackground(Color.CYAN);
btn_restart.addActionListener(this);
btn_restart.setBounds(20, 110, 115, 40);
btn_back=new JButton("返回主页面");
btn_back.setBounds(155,110,115,40);
btn_back.setBackground(Color.CYAN);
btn_back.addActionListener(this);
label=new JLabel();
label.setFont(new Font(Font.DIALOG_INPUT,Font.BOLD,20));
label.setBounds(100,10,100,100);
add(btn_restart);
add(btn_back);
add(label);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn_restart)
{
msg=RESTART;
setVisible(false);
}
else if(e.getSource()==btn_back)
{
msg=BACK;
setVisible(false);
}
}
}
<file_sep>/src/View/HeadLine.java
package View;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.net.URL;
/**
* Created by Blossoming on 2016/12/20.
*/
public class HeadLine extends JPanel implements MouseListener,MouseMotionListener{
private Btns btn_close;
private Btns btn_small;
private static String[]closeIcons = {
"close_icon.png","close_pressed.png","close_pressed.png"
};
private static String[] smallIcons= {
"small_icon.png","small_pressed.png","small_pressed.png"
};
public HeadLine()
{
init();
setLayout(new FlowLayout());
setVisible(true);
}
private void init() {
btn_close=new Btns(closeIcons,null);
btn_small=new Btns(smallIcons,null);
btn_close.setSize(60,60);
btn_small.setSize(60,60);
// btn_close=new Btns("haha");
// btn_small=new Btns("hehe");
add(btn_close);
add(btn_small);
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
<file_sep>/src/View/Btns.java
package View;
import javax.swing.*;
import java.awt.*;
/**
* Created by Blossoming on 2016/12/20.
*/
public class Btns extends JButton{
private String[] image_url;
private boolean hasImage;
public Btns()
{
super();
hasImage=false;
}
public Btns(String text)
{
super(text);
hasImage=false;
}
public Btns(String[] image_url,String text)
{
super(text);
hasImage=true;
this.image_url=image_url;
setCursor(new Cursor(Cursor.HAND_CURSOR));
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
ButtonModel model = getModel();
Image image;
//当按钮被按下
if (hasImage == true) {
if (model.isPressed()) {
Color c = new Color(0, 0, 0);
g.setColor(c);
image = Toolkit.getDefaultToolkit().getImage(image_url[1]);
g.drawImage(image, 0, 0, null);
}
else if (model.isRollover()) {
Color c = new Color(0, 0, 0);
g.setColor(c);
image =Toolkit.getDefaultToolkit().getImage(image_url[2]);
g.drawImage(image, 0, 0 , null);
}
else {
Color c = new Color(120, 120, 120);
g.setColor(c);
image = Toolkit.getDefaultToolkit().getImage(image_url[0]);
g.drawImage(image , 0, 0 , null);
}
}
}
}
<file_sep>/src/View/ImgPanel.java
package View;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImgPanel extends JPanel {
private static BufferedImage image;
private static BufferedImage default_image;
public ImgPanel() {
try {
URL url = ImgPanel.class.getResource("images/main-theme.png");
default_image = ImageIO.read(url);
image=default_image;
} catch (IOException ex) {
// do nothing
System.out.println(ex);
}
}
@Override
protected void paintComponent(Graphics g) {
Image tmp = image.getScaledInstance(435, 435, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(435, 435, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, new Color(255,255,255),null);
g2d.dispose();
g.drawImage(dimg, 0, 0, null);
}
// paint img by Graphics
public void setImage(BufferedImage Image) {
if (Image != null){
image = Image;
} else {
image = default_image;
}
this.paintComponent(getGraphics());
this.paintAll(getGraphics());
}
}
<file_sep>/src/View/PCMainBoard.java
package View;
import Model.Chess;
import Model.timerThread;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Blossoming on 2016/12/6.
*/
public class PCMainBoard extends MainBoard{
private PCChessBoard cb;
private JButton btn_startGame;
private JButton btn_back;
private JButton btn_exit;
private int level;
private ChessLine cl1;
private ChessLine cl2;
private ChessLine cl3;
private ChessLine cl4;
private ChessLine cl5;
public int getLevel(){return level;}
public JButton getBtn_startGame(){return btn_startGame;}
public JButton getBtn_back(){return btn_back;}
public PCMainBoard(int level)
{
init();
this.level=level;
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public void init()
{
cb=new PCChessBoard(this);
cb.setClickable(PPMainBoard.CAN_NOT_CLICK_INFO);
cb.setBounds(0, 20, 570, 585);
cb.setVisible(true);
btn_startGame=new JButton("开始游戏");
btn_startGame.setBounds(582,205, 200, 50);
btn_startGame.setBackground(new Color(227, 164, 113));
btn_startGame.setFocusable(false);
btn_startGame.setFont(new Font(Font.DIALOG, Font.BOLD, 20));
btn_startGame.addActionListener(this);
btn_back=new JButton("悔 棋");
btn_back.setBounds(582, 270, 200, 50);
btn_back.setBackground(new Color(144, 142, 153));
btn_back.setFocusable(false);
btn_back.setFont(new Font(Font.DIALOG, Font.BOLD, 22));
btn_back.addActionListener(this);
btn_exit=new JButton("返 回");
btn_exit.setBackground(new Color(82,109,165));
btn_exit.setBounds(582,335,200,50);
btn_exit.setFocusable(false);
btn_exit.setFont(new Font(Font.DIALOG, Font.BOLD, 22));
btn_exit.addActionListener(this);
cl1=new ChessLine(Chess.BLACK);
cl1.setBounds(570, 20, 230, 22);
cl2=new ChessLine(Chess.BLACK);
cl2.setBounds(570,100,230,22);
cl3=new ChessLine(Chess.WHITE);
cl3.setBounds(570,180,230,22);
add(cb);
add(cl1);
add(cl2);
add(cl3);
add(btn_back);
add(btn_startGame);
add(btn_exit);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn_startGame)
{
btn_startGame.setEnabled(false);
btn_startGame.setText("正在游戏");
cb.setClickable(CAN_CLICK_INFO);
timer=new timerThread(label_timeCount);
timer.start();
cb.setResult(1);
}
else if(e.getSource()==btn_back)
{
cb.backStep();
}
else if(e.getSource()==btn_exit)
{
dispose();
new SelectMenu();
}
}
}
<file_sep>/src/Net/NetTool.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Net;
import View.PPMainBoard;
import java.awt.List;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
/**
*
* @author Blossoming
*/
public class NetTool {
public static void sendUdpBroadCast(String ip,String msg){
try {
MulticastSocket ms = new MulticastSocket();
InetAddress ia = InetAddress.getByName(ip);
DatagramPacket dp = new DatagramPacket(msg.getBytes(), 0, msg.length(), ia, 1111);
ms.send(dp);
ms.close();
}catch (Exception e)
{
e.printStackTrace();
}
finally {
}
}
}
<file_sep>/README.md
# gobang
Gobang implemented by Java
## 环境及开发工具
Java + IDEA(Windows)
## 运行
运行入口src/View/SelectMenu.java
## 运行截图
界面一:

界面二(难度选择):

界面三(人机界面):

界面四(人人界面):

<file_sep>/src/View/SelectMenu.java
package View;
import com.sun.awt.AWTUtilities;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
/**
* Created by Blossoming on 2016/11/30.
*/
public class SelectMenu extends JFrame implements MouseListener,ActionListener,MouseMotionListener {
private Btns close_btn;
private Btns small_btn;
private JButton btn;
private JLabel headLabel;
private Point pos;
private Point newPos;
private static String[] closeIcons = {
"close_icon.png","close_pressed.png","close_pressed.png"
};
private static String[] smallIcons= {
"small_icon.png","small_pressed.png","small_pressed.png"
};
public SelectMenu() {
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
init();
setUndecorated(true);
setVisible(true);
setLayout(null);
setBounds(580,185,290,420);
setResizable(false);
paintBg();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//setDefaultLookAndFeelDecorated(true);
addMouseListener(this);
AWTUtilities.setWindowShape(this,
new RoundRectangle2D.Double(0D, 0D, this.getWidth(),
this.getHeight(), 24.0D, 24.0D));
}
private void init() {
close_btn=new Btns(closeIcons,null);
close_btn.setBounds(260,0,30,30);
close_btn.addActionListener(this);
close_btn.setBorderPainted(false);
btn=new JButton("哈哈哈");
headLabel=new JLabel();
headLabel.setBounds(30,0,230,30);
headLabel.setOpaque(true);
headLabel.setBackground(new Color(72,72,72));
headLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
pos=new Point(e.getX(),e.getY());
setCursor(new Cursor(Cursor.MOVE_CURSOR));
}
public void mouseReleased(MouseEvent e) {
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
}
});
headLabel.addMouseMotionListener(this);
small_btn=new Btns(smallIcons,null);
small_btn.setBounds(0,0,30,30);
small_btn.addActionListener(this);
small_btn.setBorderPainted(false);
add(headLabel);
add(close_btn);
add(small_btn);
add(btn);
}
public void paintBg() {
ImageIcon image = new ImageIcon("5.jpg");
JLabel la3 = new JLabel(image);
la3.setBounds(0, 0, this.getWidth(), this.getHeight());//添加图片,设置图片大小为窗口的大小。
this.getLayeredPane().add(la3, new Integer(Integer.MIN_VALUE)); //将JLabel加入到面板容器的最高层
JPanel jp = (JPanel) this.getContentPane();
jp.setOpaque(false); //设置面板容器为透明
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
int x=e.getX();
int y=e.getY();
if(x>=65&&x<=231&&y>=120&&y<=150)
{
//人机
dispose();
new ChooseLevel();
//new PCMainBoard();
}
else if(x>=65&&x<=231&&y>=210&&y<=250)
{
//人人
dispose();
new PPMainBoard();
}
else if(x>=65&&x<=231&&y>=325&&y<=355)
{
//退出
System.exit(0);
}
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public static void main(String args[])
{
new SelectMenu();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==small_btn)
{
setExtendedState(ICONIFIED);
}
else if(e.getSource()==close_btn)
{
dispose();
}
}
@Override
public void mouseDragged(MouseEvent e) {
newPos=new Point(getLocation().x + e.getX() - pos.x,getLocation().y + e.getY() - pos.y);
setLocation(newPos.x,newPos.y);
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
|
85219e0b02967f31d08c1875e94507871cc1a918
|
[
"Markdown",
"Java"
] | 13 |
Java
|
heping56/gobang-1
|
11d54187b12180f40b4675cc56daf5e93156bed3
|
3eb9aa62217aa32b7da29cb0ca70c1d91a103f12
|
refs/heads/master
|
<repo_name>Kouzukii/bdx-worker<file_sep>/game/explorer.go
package game
import (
"github.com/pkg/errors"
"strings"
)
type NoSuchEntry struct{}
type Explorer struct {
location string
root *folderEntry
}
type folderEntry struct {
directories map[string]*folderEntry
files map[string]*FileEntry
}
type FileEntry struct {
name string
size uint
folderName string
}
func (e *Explorer) traverse(path string, create bool) (*FileEntry, error) {
var ok bool
folder := e.root
split := strings.Split(path, "/")
for i, seg := range split {
seg = strings.ToLower(seg)
if i+1 == len(split) {
return folder.files[seg], nil
}
if folder, ok = folder.directories[seg]; !ok {
if create {
folder.directories[seg] = &folderEntry{make(map[string]*folderEntry), make(map[string]*FileEntry)}
} else {
return nil, NoSuchEntry{}
}
}
}
}
func (NoSuchEntry) Error() string {
return "No such entry in the file tree"
}
<file_sep>/util/utf16.go
package util
import (
"syscall"
"unsafe"
)
type UTF16 struct {
buf []uint16
}
func (b *UTF16) Ptr() *uint16 {
return &b.buf[0]
}
func (b *UTF16) BytePtr() *byte {
return (*byte)(unsafe.Pointer(&b.buf[0]))
}
func (b *UTF16) String() string {
return syscall.UTF16ToString(b.buf)
}
func (b *UTF16) Sizeof() uint32 {
return uint32(len(b.buf) * 2)
}
func NewUTF16(size uint32) *UTF16 {
return &UTF16{make([]uint16, size)}
}
<file_sep>/util/registry.go
package util
import (
"github.com/lxn/win"
"github.com/pkg/errors"
"syscall"
)
func ReadRegistryValue(key string) (string, error) {
regkey, err := syscall.UTF16PtrFromString(key)
if err == nil {
buf := NewUTF16(512)
size := buf.Sizeof()
if result := win.HRESULT(win.RegQueryValueEx(win.HKEY_LOCAL_MACHINE, regkey, nil, nil, buf.BytePtr(), &size)); win.SUCCEEDED(result) {
return buf.String(), nil
} else {
return "", errors.Errorf("Win32 error %x", result)
}
}
return "", err
}
<file_sep>/game/file-handler.go
package game
import (
"path"
"strings"
)
type FileType int
const (
DDS FileType = 1
PAC FileType = 2
Text FileType = 3
Other FileType = 4
)
func (e *Explorer) ExportFile(entry *FileEntry, exportTextures bool) (FileType, string) {
ft := Other
ext := path.Ext(entry.name)
switch ext {
case ".pac":
ft = PAC
case ".dds":
ft = DDS
case ".txt":
case ".xml":
ft = Text
}
filepath := path.Join(ExportDir(), entry.folderName, entry.name)
upscaledPath := filepath[:-len(ext)] + ".upscaled" + ext
return ft, filepath
}
<file_sep>/util/readlink.go
package util
// #include "shortcut.h"
import "C"
import (
"github.com/lxn/win"
"github.com/pkg/errors"
"syscall"
)
func ResolveShortcutTarget(lnk string) (string, error) {
buf := NewUTF16(512)
if result := C.ResolveIt(0, syscall.BytePtrFromString(lnk), buf.Ptr(), 512); win.SUCCEEDED(result) {
return buf.String(), nil
} else {
return "", errors.Errorf("Win32 Error %x", result)
}
}
<file_sep>/game/discovery.go
package game
import (
"github.com/Kouzukii/bdx-worker/util"
"github.com/lxn/win"
"os"
"path"
)
type BlackDesertInstallationNotFound struct{}
type ExportDirectoryNotFound struct{}
var (
location string
exportDir string
)
func Location() string {
if location != "" {
return location
}
if loc, err := util.ReadRegistryValue("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{C1F96C92-7B8C-485F-A9CD-37A0708A2A60}\\InstallLocation"); err == nil {
if f, err := os.Stat(loc); err == nil && f.IsDir() {
location = loc
return location
}
}
buf := util.NewUTF16(512)
win.SHGetSpecialFolderPath(0, buf.Ptr(), win.CSIDL_COMMON_STARTMENU, false)
if loc, err := util.ResolveShortcutTarget(path.Join(buf.String(), "Black Desert Online.lnk")); err == nil {
if _, err := os.Stat(loc); err == nil {
location = path.Dir(loc)
return location
}
}
buf = util.NewUTF16(512)
win.SHGetSpecialFolderPath(0, buf.Ptr(), win.CSIDL_COMMON_DESKTOPDIRECTORY, false)
if loc, err := util.ResolveShortcutTarget(path.Join(buf.String(), "Black Desert Online.lnk")); err == nil {
if _, err := os.Stat(loc); err == nil {
location = path.Dir(loc)
return location
}
}
buf = util.NewUTF16(512)
win.SHGetSpecialFolderPath(0, buf.Ptr(), win.CSIDL_PROGRAM_FILESX86, false)
loc := path.Join(buf.String(), "Black Desert Online")
if f, err := os.Stat(loc); err == nil && f.IsDir() {
location = loc
return location
}
panic(BlackDesertInstallationNotFound{})
}
func PazLocation() string {
return path.Join(Location(), "Paz")
}
func ExportDir() string {
if exportDir != "" {
return exportDir
}
dir, err := os.Getwd()
if err != nil {
panic(ExportDirectoryNotFound{})
}
exportDir = path.Join(dir, "export")
return exportDir
}
<file_sep>/util/shortcut.h
// source https://stackoverflow.com/a/22988327/9187529
#include "stdafx.h"
#include "windows.h"
#include "shobjidl.h"
#include "shlguid.h"
#include "strsafe.h"
HRESULT ResolveIt(HWND hwnd, LPCSTR lpszLinkFile, LPWSTR lpszPath, int iPathBufferSize)
{
HRESULT hres;
IShellLink* psl;
WCHAR szGotPath[MAX_PATH];
WCHAR szDescription[MAX_PATH];
WIN32_FIND_DATA wfd;
*lpszPath = 0; // Assume failure
// Get a pointer to the IShellLink interface. It is assumed that CoInitialize
// has already been called.
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
if (SUCCEEDED(hres))
{
IPersistFile* ppf;
// Get a pointer to the IPersistFile interface.
hres = psl->QueryInterface(IID_IPersistFile, (void**)&ppf);
if (SUCCEEDED(hres))
{
WCHAR wsz[MAX_PATH];
// Ensure that the string is Unicode.
MultiByteToWideChar(CP_ACP, 0, lpszLinkFile, -1, wsz, MAX_PATH);
// Add code here to check return value from MultiByteWideChar
// for success.
// Load the shortcut.
hres = ppf->Load(wsz, STGM_READ);
if (SUCCEEDED(hres))
{
// Resolve the link.
hres = psl->Resolve(hwnd, 0);
if (SUCCEEDED(hres))
{
// Get the path to the link target.
hres = psl->GetPath(szGotPath, MAX_PATH, (WIN32_FIND_DATA*)&wfd, SLGP_SHORTPATH);
if (SUCCEEDED(hres))
{
// Get the description of the target.
hres = psl->GetDescription(szDescription, MAX_PATH);
if (SUCCEEDED(hres))
{
hres = StringCbCopy(lpszPath, iPathBufferSize, szGotPath);
if (SUCCEEDED(hres))
{
// Handle success
}
else
{
// Handle the error
}
}
}
}
}
// Release the pointer to the IPersistFile interface.
ppf->Release();
}
// Release the pointer to the IShellLink interface.
psl->Release();
}
return hres;
}
|
ca90e9d1cd3a6904caa43f6e536696e1abd187f2
|
[
"C",
"Go"
] | 7 |
Go
|
Kouzukii/bdx-worker
|
c8736139bbea9019f7caac7d48088cdf54862b1b
|
4fa9afb7a3a31792d3fa44a87ca8a5f3a51db9a7
|
refs/heads/master
|
<repo_name>naxadeve/vso<file_sep>/application/models/Publication_model.php
<?php
class Publication_model extends CI_Model {
public function get_all_data(){
$this->db->select('*');
$this->db->order_by('id','DESC');
$q=$this->db->get('publication');
return $q->result_array();
}
public function add_publication($table,$data){
$this->db->insert($table,$data);
if ($this->db->affected_rows() > 0)
{
return $this->db->insert_id();
}
else
{
$error = $this->db->error();
return $error;
}
}
public function update_path($id,$data){
$this->db->where('id',$id);
$this->db->update('publication',$data);
}
public function do_upload($filename,$name)
{
$field_name ='proj_pic';
$config['upload_path'] = './uploads/publication/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function file_do_upload($filename,$name)
{
$field_name ='uploadedfile';
$config['upload_path'] = './uploads/publication/file/';
$config['allowed_types'] = 'pdf';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
return 1;
}
}
public function delete_data($id){
$this->db->where('id',$id);
$this->db->delete('publication');
}
public function get_edit_Data($id,$table){
$this->db->select('*');
$this->db->where('id',$id);
$query=$this->db->get($table);
return $query->row_array();
}
public function update_data($id,$data){
$this->db->where('id',$id);
$q=$this->db->update('publication',$data);
if($q){
return 1;
}else{
return 0;
}
}
}
<file_sep>/application/controllers/Admin/DashController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class DashController extends CI_Controller
{
function __construct()
{
parent::__construct();
if(($this->session->userdata('logged_in'))!=TRUE)
{
redirect('admin');
}else{
}
$this->load->model('Admin_dash_model');
}
public function dashboard()
{
$this->body['user']=$this->Admin_dash_model->count_data('users');
$this->body['map_data']=$this->Admin_dash_model->count_data('categories_tbl');
$this->body['report']=$this->Admin_dash_model->count_data('report_tbl');
$this->body['max']=$this->Admin_dash_model->max_views();
//var_dump($this->body['max']);
$home=$this->Admin_dash_model->count_views('home');
$map=$this->Admin_dash_model->count_views('map');
$reports=$this->Admin_dash_model->count_views('reports');
$about=$this->Admin_dash_model->count_views('about');
$this->body['home']=$home['views_count'];
$this->body['map']=$map['views_count'];
$this->body['reports']=$reports['views_count'];
$this->body['about']=$about['views_count'];
//var_dump($this->body['user']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/dash.php',$this->body);
$this->load->view('admin/footer');
}
public function logout(){
$newdata = array(
'logged_in' => TRUE,
);
$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
redirect('login', 'refresh');
}
}
<file_sep>/application/views/admin/manage_style.php
<!--main content start-->
<!-- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/10.0.2/css/bootstrap-slider.min.css" /> -->
<!--
<link href="<?php echo base_url()?>assets/admin/css/ion.rangeSlider.css" rel="stylesheet" />
<link href="<?php echo base_url()?>assets/admin/css/ion.rangeSlider.skinFlat.css" rel="stylesheet"/>
<script type="text/javascript" src="<?php echo base_url()?>assets/admin/js/spinner.min.js"></script>
<script type="text/javascript" src="<?php echo base_url()?>assets/admin/js/bootstrap-colorpicker.js"></script>
<script src="<?php echo base_url()?>assets/admin/js/ion.rangeSlider.min.js" type="text/javascript"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section id="main-content" class="">
<section class="wrapper">
<!-- page start-->
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
<b>Manage Marker Style</b>
<span class="tools pull-right">
<a href="<?php echo base_url()?>category?tbl=<?php echo $table ?>"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1fb5ad;border-color: #1fb5ad;margin-top: -7px;"><i class="fa fa-map-marker"></i> View In Map</button></a>
</span>
</header>
<div class="panel-body">
<?php
$error= $this->session->flashdata('msg');
if($error){ ?>
<div class="alert alert-info alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message!!!!</strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<form class="form-horizontal bucket-form" method="post" action="">
<!-- start -->
<!-- <input id="range_5" type="text" name="range_5" value="" /> -->
<!-- end -->
<div class="form-group">
<label class="control-label col-md-3">Opacity</label>
<div class="col-md-9">
<div class="input-group" style="width: 150px">
<span class="input-group-btn "><button type="button" class="btn btn-default value-control opac" data-target="font-size" data-action="minus"><span class="glyphicon glyphicon-minus"></span></button></span>
<input type="text" name="opacity" value="<?php echo $style_array['opacity'] ?>" min="0" max="1" class="form-control" id="font-size" >
<span class="input-group-btn "><button type="button" class="btn btn-default value-control opac" data-action="plus" data-target="font-size"><span class="glyphicon glyphicon-plus"></span></button></span>
</div>
<span class="help-block">
with max value: 1
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Fill Opacity</label>
<div class="col-md-9">
<div class="input-group" style="width: 150px">
<span class="input-group-btn"><button type="button" class="btn btn-default value-control fillopac" data-action="minus" data-target="fillopac"><span class="glyphicon glyphicon-minus"></span></button></span>
<input type="text" name="fillOpacity" value="<?php echo $style_array['fillOpacity'] ?>" class="form-control" id="fillopac">
<span class="input-group-btn"><button type="button" class="btn btn-default value-control fillopac" data-action="plus" data-target="fillopac"><span class="glyphicon glyphicon-plus"></span></button></span>
</div>
<span class="help-block">
with max value: 1
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Weight</label>
<div class="col-md-9">
<div id="spinner3">
<div class="input-group" style="width: 150px">
<span class="input-group-btn"><button type="button" class="btn btn-default value-control weight" data-action="minus" data-target="weight"><span class="glyphicon glyphicon-minus"></span></button></span>
<input type="text" name="weight" min="1" max="10" value="<?php echo $style_array['weight'] ?>" class="form-control" id="weight">
<span class="input-group-btn"><button type="button" class="btn btn-default value-control weight" data-action="plus" data-target="weight"><span class="glyphicon glyphicon-plus"></span></button></span>
</div>
<span class="help-block">
with max value: 10
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Dash Array</label>
<div class="col-md-9">
<div id="spinner3">
<div class="input-group" style="width: 150px">
<span class="input-group-btn"><button type="button" class="btn btn-default value-control dashArray" data-action="minus" data-target="dashArray"><span class="glyphicon glyphicon-minus"></span></button></span>
<input type="text" name="dashArray" min="1" max="10" value="2" class="form-control" id="dashArray">
<span class="input-group-btn"><button type="button" class="btn btn-default value-control dashArray" data-action="plus" data-target="dashArray"><span class="glyphicon glyphicon-plus"></span></button></span>
</div>
<span class="help-block">
with max value: 10
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Dash Offset</label>
<div class="col-md-9">
<div id="spinner3">
<div class="input-group" style="width: 150px">
<span class="input-group-btn"><button type="button" class="btn btn-default value-control dashOffset" data-action="minus" data-target="dashOffset"><span class="glyphicon glyphicon-minus"></span></button></span>
<input type="text" name="dashOffset" min="1" max="10" value="2" class="form-control" id="dashOffset">
<span class="input-group-btn"><button type="button" class="btn btn-default value-control dashOffset" data-action="plus" data-target="dashOffset"><span class="glyphicon glyphicon-plus"></span></button></span>
</div>
<span class="help-block">
with max value: 10
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Color</label>
<div class="col-md-4 col-xs-11">
<div data-color-format="rgb" data-color="rgb(255, 146, 180)" class="input-append colorpicker-default color">
<input type="color" name="color" value="<?php echo $style_array['color'] ?>">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Fill Color</label>
<div class="col-md-4 col-xs-11">
<div data-color-format="rgb" data-color="rgb(255, 146, 180)" class="input-append colorpicker-default color">
<input type="color" name="fillColor" value="<?php echo $style_array['fillColor'] ?>">
</div>
</div>
</div>
<!-- <div class="form-group ">
<div class="col-md-9">
<br>
<div class="col-md-6">
Upload Image
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="" />
</div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>
<div>
<span class="btn btn-white btn-file">
<span class="fileupload-new"><i class="fa fa-paper-clip"></i> Select image</span>
<span class="fileupload-exists"><i class="fa fa-undo"></i> Change</span>
<input type="file" name="cat_pic" class="default" />
</span>
</div>
</div>
</div>
<div class="col-md-6">
Select Icon
<div class="panel panel-default icon-select" style="border: 1px solid #ddd;max-height: 150px; width: 425px;overflow-x: auto;" >
<div class="panel-body" style="overflow: hidden;">
<div class="form-group">
<div class="row">
<div class="col-md-3">
<form>
<label>
<input id="fb3" type="radio" name="fb" value="med" />
<img class="map-marker" src="<?php echo base_url();?>assets/img/mark.png" alt="Logo" >
</label>
</div>
<div class="col-md-3">
<label>
<input id="fb3" type="radio" name="fb" value="med" />
<img class="map-marker" src="<?php echo base_url();?>assets/img/mark.png" alt="Logo" >
</label>
</div>
<div class="col-md-3">
<label>
<input id="fb3" type="radio" name="fb" value="med" />
<img class="map-marker" src="<?php echo base_url();?>assets/img/mark.png" alt="Logo" >
</label>
</div>
<div class="col-md-3">
<label>
<input id="fb3" type="radio" name="fb" value="med" />
<img class="map-marker" src="<?php echo base_url();?>assets/img/mark.png" alt="Logo">
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div> -->
<div class="col-md-6">
<button type="submit" name="submit" class="btn btn-success" style="background-color: #1fb5ad;border-color: #1fb5ad;">Update</button>
</div>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
<!-- page end-->
</section>
<!--main content end-->
<script>
$(document).ready(function(){
$(".opac").on('click',function(){
var action = $(this).attr('data-action')
var target = $(this).attr('data-target')
var value = parseFloat($('[id="'+target+'"]').val());
// console.log('action');
// console.log(action);
// //console.log(target);
// console.log(value);
if ( action == "plus" ) {
value=value+0.1;
var val=Math.round(value*100)/100;
}else{
value=value-0.1;
var val=Math.round(value*100)/100;
}
// $('[id="'+target+'"]').val(value);
if( ( val >= 0 ) && ( val <= 1) ){
$("#font-size").val(val);
}
});
$(".fillopac").on('click',function(){
var action = $(this).attr('data-action')
var target = $(this).attr('data-target')
var value = parseFloat($('[id="'+target+'"]').val());
// console.log('action');
// console.log(action);
// //console.log(target);
// console.log(value);
if ( action == "plus" ) {
value=value+0.1;
var val=Math.round(value*100)/100;
}else{
value=value-0.1;
var val=Math.round(value*100)/100;
}
// $('[id="'+target+'"]').val(value);
if( ( val >= 0 ) && ( val <= 1) ){
$("#fillopac").val(val);
}
});
$(".weight").on('click',function(){
var action = $(this).attr('data-action')
var target = $(this).attr('data-target')
var value = parseFloat($('[id="'+target+'"]').val());
// console.log('action');
// console.log(action);
// //console.log(target);
// console.log(value);
if ( action == "plus" ) {
value=value+1;
var val=Math.round(value*100)/100;
}else{
value=value-1;
var val=Math.round(value*100)/100;
}
// $('[id="'+target+'"]').val(value);
if( ( val >= 0 ) && ( val <= 10) ){
$("#weight").val(val);
}
});
$(".dashArray").on('click',function(){
var action = $(this).attr('data-action')
var target = $(this).attr('data-target')
var value = parseFloat($('[id="'+target+'"]').val());
// console.log('action');
// console.log(action);
// //console.log(target);
// console.log(value);
if ( action == "plus" ) {
value=value+1;
var val=Math.round(value*100)/100;
}else{
value=value-1;
var val=Math.round(value*100)/100;
}
// $('[id="'+target+'"]').val(value);
if( ( val >= 0 ) && ( val <= 10) ){
$("#dashArray").val(val);
}
});
$(".dashOffset").on('click',function(){
var action = $(this).attr('data-action')
var target = $(this).attr('data-target')
var value = parseFloat($('[id="'+target+'"]').val());
// console.log('action');
// console.log(action);
// //console.log(target);
// console.log(value);
if ( action == "plus" ) {
value=value+1;
var val=Math.round(value*100)/100;
}else{
value=value-1;
var val=Math.round(value*100)/100;
}
// $('[id="'+target+'"]').val(value);
if( ( val >= 0 ) && ( val <= 10) ){
$("#dashOffset").val(val);
}
});
});
// $(document).on('click','.value-control1',function(){
// var action1 = $(this).attr('data-action')
// var target1 = $(this).attr('data-target')
// var value1 = parseFloat($('[id="'+target1+'"]').val());
// if ( action1 == "plus" ) {
// value=value+0.1;
// }
// if ( action1 == "minus" ) {
// value=value-0.1;
// }
// $('[id="'+target1+'"]').val(value)
// })
// $(document).on('click','.value-control',function(){
// var action = $(this).attr('data-action')
// var target = $(this).attr('data-target')
// var value = parseFloat($('[id="'+target+'"]').val());
// if ( action == "plus" ) {
// value++;
// }
// if ( action == "minus" ) {
// value--;
// }
// $('[id="'+target+'"]').val(value)
// })
</script>
<file_sep>/application/models/Dash_model.php
<?php
class Dash_model extends CI_Model {
public function delete_lang($tbl){
$this->db->where('tbl_name',$tbl);
$this->db->delete('tbl_lang');
}
public function get_sub_cat_style($tbl){
$this->db->where('category_table',$tbl);
$q=$this->db->get('categories_tbl');
return $q->row_array();
}
public function create_geom($long,$lat,$tbl){
$query= "UPDATE $tbl SET the_geom = ST_PointFromText('POINT(' || $long || ' ' || $lat || ')', 27700)";
$this->db->query($query);
}
public function get($tbl){
$this->db->select('*');
$this->db->select('ST_AsGeoJSON(the_geom)');
$query=$this->db->get($tbl);
return $query->result_array();
}
public function get_tbl_type($tbl){
$this->db->select('*');
$this->db->select('ST_AsGeoJSON(the_geom)');
$this->db->limit(1);
$query=$this->db->get($tbl);
return $query->row_array();
}
// create categories
public function get_sub_cat_data($tbl,$data,$col){
$this->db->select('*');
$this->db->select('ST_AsGeoJSON(the_geom)');
$this->db->where($col,$data);
$res=$this->db->get($tbl);
return $res->result_array();
}
public function get_sub_cat_data_count($tbl,$data,$col){
$this->db->select('*');
$this->db->where($col,$data);
$res=$this->db->get($tbl);
return $res->num_rows();
}
public function filter_map_data($tbl,$query){
$this->db->select('*');
$this->db->select('ST_AsGeoJSON(the_geom)');
$this->db->where($query);
$res=$this->db->get($tbl);
return $res->result_array();
}
public function do_upload($filename,$name)
{
$field_name ='cat_pic';
$config['upload_path'] = './uploads/categories/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function do_upload_marker($filename,$name)
{
$field_name ='cat_pic';
$config['upload_path'] = './uploads/icons/map/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
return 1;
}
}
public function insert_cat($table, $udata)
{
$this->db->insert($table, $udata);
if ($this->db->affected_rows() > 0)
{
return $this->db->insert_id();
}
else
{
$error = $this->db->error();
return $error;
}
}
// end categories
// table operations
public function get_tables_data($tbl){ //get data of table
$this->db->select('*');
$this->db->order_by('id','ASC');
$q=$this->db->get($tbl);
return $q->result_array();
}
public function get_tables_data_cat($tbl,$lang){ //get data of table
$this->db->select('*');
$this->db->where('language',$lang);
$this->db->order_by('id','ASC');
$q=$this->db->get($tbl);
return $q->result_array();
}
public function get_default_cat_data($tbl){ //get data of table
$this->db->select('*');
$this->db->order_by('id','ASC');
$this->db->where('default_load',1);
$this->db->limit(1);
$q=$this->db->get($tbl);
return $q->row_array();
}
public function get_count_views_datasets($tbl){ //get data of table
$this->db->select('*');
$this->db->where('category_table',$tbl);
$q=$this->db->get('categories_tbl');
return $q->row_array();
}
public function get_tables_data_lang($tbl,$tble_field){ //get data of table
$this->db->select('*');
$this->db->where('tbl_name',$tble_field);
$this->db->order_by('id','ASC');
$q=$this->db->get($tbl);
return $q->result_array();
}
public function edit_get_data($id,$tbl){ // edit data of table
$this->db->where('id',$id);
$q=$this->db->get($tbl);
return $q->row_array();
}
public function update($id,$data,$tbl){ // update the edited table
$this->db->where('id',$id);
$q=$this->db->update($tbl,$data);
if($q){
return 1;
}else{
return 0;
}
}
public function cat_update($id,$data){ // update the edited table
$this->db->where('id',$id);
$q=$this->db->update('categories_tbl',$data);
if($q){
return 1;
}else{
return 0;
}
}
// end table operation
// view all cat table
public function view_cat_tables(){ //get list of cat table from db
$tables = $this->db->list_tables();
return $tables;
}
//storing column name in nepali and english
public function insert_lang($table,$data){
$this->db->insert($table, $data);
if ($this->db->affected_rows() > 0)
{
return $this->db->insert_id();
}
else
{
$error = $this->db->error();
return $error;
}
}
public function delete_data($id,$table_name){
$this->db->where('id', $id);
$this->db->delete($table_name);
}
public function get_sub_cat($col,$tbl){
$this->db->select($col);
$this->db->distinct();
$res=$this->db->get($tbl);
return $res->result_array();
}
// end cat tables
public function update_sub_cat($data,$tbl){ // update the edited table
$this->db->where('category_table',$tbl);
$q=$this->db->update('categories_tbl',$data);
if($q){
return 1;
}else{
return 0;
}
}
}//main
<file_sep>/application/config/routes.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'MainController/default_page';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
// user routes
$route['en'] ='Lang/eng';
$route['nep'] ='Lang/nep';
$route['main'] ='MainController/default_page';
$route['datasets'] ='MainController/dataset_page';
$route['about'] ='MainController/about_page';
$route['publication'] ='MainController/publication';
$route['inventory'] ='MainController/inventory';
$route['contact'] ='MainController/contact';
$route['get_csv_emergency'] ='MainController/get_csv_emergency';
$route['map'] ='MapController/map_page';
$route['category'] ='MapController/category_map';
$route['admin_category'] ='MapController/admin_category_map';
$route['manage_popup'] ='MapController/manage_popup';
$route['manage_style'] ='MapController/manage_style';
$route['update_summary'] ='MapController/update_summary';
$route['map_download'] ='MapController/map_download';
$route['circle_marker'] ='MapController/circle_marker';
$route['location_marker'] ='MapController/location_marker';
$route['data_map'] ='MapController/data_map';
$route['news_register'] ='NewsletterController/register';
$route['site_setting'] ='Admin/SiteController/site_setting';
$route['site_setting_nep'] ='Admin/SiteController/site_setting_nep';
$route['report_page'] ='ReportController/report_page';
$route['report_manage'] ='ReportController/report_manage';
$route['report/delete'] = 'ReportController/delete_data';
$route['map_reports_table'] ='ReportController/map_reports_table';
$route['map_reports'] ='ReportController/map_reports';
$route['filter'] ='ReportController/date_test';
$route['ghatana'] ='Admin/GhatanaController/view_ghatana';
$route['add_ghatana'] ='Admin/GhatanaController/add_ghatana';
$route['ghatana_edit'] ='Admin/GhatanaController/ghatana_edit';
$route['ghatana_delete'] ='Admin/GhatanaController/ghatana_delete';
// Admin routes
$route['admin'] = 'Admin/LoginController';
$route['logout'] = 'Admin/LoginController/logout';
$route['feature'] = 'Admin/FeatureDataset/feature';
$route['add_feature'] = 'Admin/FeatureDataset/add_feature';
$route['add_feature_nep'] = 'Admin/FeatureDataset/add_feature_nep';
$route['delete_feature'] = 'Admin/FeatureDataset/delete_feature';
$route['edit_feature'] = 'Admin/FeatureDataset/edit_feature';
$route['edit_feature_nep'] = 'Admin/FeatureDataset/edit_feature_nep';
$route['feature_nep'] = 'Admin/FeatureDataset/feature_nep';
$route['table_create'] = 'Admin/TableController/create_table';
$route['dashboard'] = 'Admin/CategoriesController';
$route['data_tables'] = 'Admin/CategoriesController/data_tables';
//$route['csv_upload'] = 'Admin/CategoriesController/csv_upload';
$route['edit'] = 'Admin/CategoriesController/edit';
$route['create_col'] = 'Admin/CategoriesController/create_col';
$route['create_categories_tbl'] = 'Admin/CategoriesController/create_categories_tbl';
$route['create_categories'] = 'Admin/CategoriesController/create_categories';
$route['create_categories_nep'] = 'Admin/CategoriesController/create_categories_nep';
$route['view_cat_tables'] = 'Admin/CategoriesController/view_cat_tables';
$route['categories_tbl'] = 'Admin/CategoriesController/categories_tbl';
$route['categories_tbl_nep'] = 'Admin/CategoriesController/categories_tbl_nep';
$route['edit_categories'] = 'Admin/CategoriesController/edit_categories';
$route['drop_cat_table'] = 'Admin/CategoriesController/drop_cat_table';
$route['delete_data'] = 'Admin/CategoriesController/delete_data';
$route['csv_data_tbl'] = 'Admin/CategoriesController/csv_data_tbl';
$route['sub_categories'] = 'Admin/CategoriesController/sub_categories';
$route['sub_cat_insert'] = 'Admin/CategoriesController/sub_cat_insert';
$route['proj/delete_data'] = 'Admin/ProjectController/delete_data';
$route['proj/edit_proj'] = 'Admin/ProjectController/edit_proj';
$route['add_proj'] = 'Admin/ProjectController/add_proj';
$route['view_proj'] = 'Admin/ProjectController/view_proj';
$route['csv_upload'] = 'Admin/TableController/copy_table';
$route['csv_tbl'] = 'Admin/TableController/csv_tbl';
$route['get_csv_dataset'] = 'Admin/TableController/get_csv_dataset';
$route['get_geojson_dataset'] = 'Admin/TableController/get_geojson_dataset';
$route['add_layers'] = 'Admin/LayersController/add_layers';
$route['layers_view'] = 'Admin/LayersController/layers_view';
$route['layers_detail'] = 'Admin/LayersController/layers_detail';
$route['layers_edit'] = 'Admin/LayersController/layers_edit';
$route['background'] = 'Admin/UploadController/bck_img';
$route['emergency_contact'] = 'Admin/UploadController/emergency_contact';
$route['emergency_contact_nep'] = 'Admin/UploadController/emergency_contact_nep';
$route['emergency_personnel'] = 'Admin/UploadController/emergency_personnel';
$route['emergency_personnel_nep'] = 'Admin/UploadController/emergency_personnel_nep';
$route['delete_emergency'] = 'Admin/UploadController/delete_emerg';
$route['edit_emergency'] = 'Admin/UploadController/edit_emerg';
$route['edit_emergency_personnel'] = 'Admin/UploadController/edit_emerg_personnel';
$route['add_emergency'] = 'Admin/UploadController/add_emergency';
$route['add_emergency_personnel'] = 'Admin/UploadController/add_emergency_personnel';
$route['add_icon'] = 'Admin/UploadController/add_icon';
$route['upload_csv_emerg'] = 'Admin/UploadController/upload_csv_emerg';
$route['view_publication'] = 'Admin/PublicationController/view_publication';
$route['add_publication'] = 'Admin/PublicationController/add_publication';
$route['delete_publication'] = 'Admin/PublicationController/delete_publication';
$route['edit_publication'] = 'Admin/PublicationController/edit_publication';
$route['download'] = 'Admin/PublicationController/download';
$route['view_about'] = 'Admin/AboutController/view_about';
$route['edit_about'] = 'Admin/AboutController/edit_about';
$route['map_show'] ='Admin/MapDownload/map_show';
$route['add_maps'] ='Admin/MapDownload/add_maps';
$route['edit_map'] ='Admin/MapDownload/edit_map';
$route['delete_map'] ='Admin/MapDownload/delete_map';
$route['dashboard'] ='Admin/DashController/dashboard';
<file_sep>/application/models/Layers_model.php
<?php
class Layers_model extends CI_Model {
public function insert_layer($id,$data){
$this->db->where('id',$id);
$this->db->update('categories_tbl',$data);
}
public function get_layers($tbl){
$this->db->select('*');
$query=$this->db->get($tbl);
return $query->result_array();
}
public function get_edit_layers($tbl,$id){
$this->db->select('*');
$this->db->where('gid',$id);
$query=$this->db->get($tbl);
return $query->result_array();
}
}
<file_sep>/application/views/about.php
<style>
#section1{margin-top: 0}
#section1 {height:520px;color: #fff; background-color: #1f5cb2;}
#section2 {padding-top:50px;padding-bottom: 30px; background-color: #f5f6f7; color: #101010;}
#section3 {padding-top:50px;color: #101010; background-color:white; padding-bottom: 10px;}
#section4 {padding-top:50px;padding-bottom: 30px; color: #101010; background-color:#f5f6f7}
#section5 {padding-top:50px;color: #101010; background-color:white; padding-bottom: 10px;}
.section-1-content{
font-size: 14px;
padding-left: 75px;
padding-top: 50px;
}
.section1-p{
font-size: 15px;
}
.section1-img{
position: relative;
-webkit-animation-name: example;
-webkit-animation-duration: 4s;
animation-name: example;
float: right;
width: 100%;
height: 100%;
}
.section2-img{
position: relative;
-webkit-animation-name: example;
-webkit-animation-duration: 4s;
animation-name: example;
width: 100%;
height: 100%;
}
@keyframes example {
0% {opacity: 0}
100% {opacity: 1;}
}
div#clients{
padding: 20px;
}
/** client logos **/
#clients {
display: block;
margin-bottom: 15px;
}
#clients .clients-wrap {
display: block;
width: 100%;
margin: 0 auto;
overflow: hidden;
margin-left: 250px;
}
#clients .clients-wrap ul {
display: block;
list-style: none;
position: relative;
}
#clients .clients-wrap ul li {
display: block;
float: left;
position: relative;
width: 140px;
height: 100px;
line-height: 55px;
text-align: center;
}
#clients .clients-wrap ul li img {
vertical-align: middle;
height: 80px;
-webkit-transition: all 0.3s linear;
-moz-transition: all 0.3s linear;
transition: all 0.3s linear;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=65)";
filter: alpha(opacity=65);
opacity: 0.65;
}
#clients .clients-wrap ul li img:hover {
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
filter: alpha(opacity=100);
opacity: 1.0;
}
</style>
<!--about-content -->
<div class="section">
<div id="section1" class="container-fluid">
<div class="row">
<div class="col-xs-7 col-sm-7 col-md-7">
<div class="section-1-content">
<h2><?php echo $disaster['title'] ?></h2>
<p class="section1-p"><?php echo $disaster['summary'] ?></p>
</div>
</div>
<div class="col-xs-5 col-sm-5 col-md-5" style="padding-top:0; padding-right: 0; padding-left: 0">
<img class="section1-img" src="<?php echo $disaster['photo'] ?>">
</div>
</div>
</div>
<div id="section2" class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-3">
<img class="section2-img" src="<?php echo $risk['photo'] ?>">
</div>
<div class="col-md-6">
<h4><?php echo $risk['title'] ?></h4>
<p><?php echo $risk['summary'] ?></p>
</div>
</div>
</div>
</div>
<div id="section3" class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-9">
<h4><?php echo $utility['title'] ?></h4>
<p><?php echo $utility['summary'] ?></p>
</div>
<div class="col-md-3">
<img class="section2-img" src="<?php echo $utility['photo'] ?>"></div>
</div>
</div>
</div>
<div id="section4" class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-3">
<img class="section2-img" src="<?php echo $house['photo'] ?>">
</div>
<div class="col-md-6">
<h4><?php echo $house['title'] ?></h4>
<p><?php echo $house['summary'] ?></p>
</div>
</div>
</div>
</div>
<div id="section5" class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-9">
<h4><?php echo $query['title'] ?></h4>
<p><?php echo $query['summary'] ?></p>
</div>
<div class="col-md-3">
<img class="section2-img" src="<?php echo $query['photo'] ?>"></div>
</div>
</div>
</div>
</div>
<!--about-content-->
<!-- Project Partnes -->
<!-- Testimonials -->
<div id="clients">
<h3 class="proj text-center">Project Partners</h3>
<br>
<div class="clients-wrap text-center">
<ul id="clients-list" class="clearfix">
<?php foreach($proj_data as $data){ ?>
<li class="logos"><img src="<?php echo $data['project_pic'] ?>" alt="euro"></li>
<?php } ?>
</ul>
</div><!-- @end .clients-wrap -->
</div><!-- @end #clients -->
<file_sep>/application/models/Ghatana_model.php
<?php
class Ghatana_model extends CI_Model {
public function get_data(){
$this->db->select('*');
$res=$this->db->get('map_reports_table');
return $res->result_array();
}
public function add_ghatana($table,$data)
{
$this->db->insert($table, $data);
if ($this->db->affected_rows() > 0)
{
return $this->db->insert_id();
}
else
{
$error = $this->db->error();
return $error;
}
}
public function edit_data($id){
$this->db->select('*');
$this->db->where('id',$id);
$res=$this->db->get('map_reports_table');
return $res->row_array();
}
public function update_data($id,$data){ // update the edited table
$this->db->where('id',$id);
$q=$this->db->update('map_reports_table',$data);
if($q){
return 1;
}else{
return 0;
}
}
public function delete_data($id){
$this->db->where('id',$id);
return $this->db->delete('map_reports_table');
}
} //end
<file_sep>/application/views/data_map.php
<style>
.nav-tabs,
.nav-pills {
position: relative;
}
.tabdrop{
width: 120px;
margin-top: .5rem;
}
.nav-tabs li li i{
visibility: hidden;
}
.hide {
display: none;
}
.input-group-addon {
position: absolute;
right: 10px;
bottom: 13px;
z-index: 2;
}
.contact-search-1 {
padding: 50px;
border-bottom: 1px solid #eee;
padding-left: 0px;
}
.responstable th {
display: none;
border: 1px solid transparent;
background-color: lightslategray;
color: #FFF;
padding: 1em;
}
#reportable{
overflow: auto;
margin: 0em auto 3em;
}
.responstable {
margin: 1em 0em;
width: 100%;
overflow:auto;
background: #FFF;
color: #000;
border-radius: 0px;
border: 1px solid #1f5cb2;
font-size: 16px;
}
.responstable tr {
border: 1px solid #D9E4E6;
}
.responstable tr:nth-child(odd) {
background-color: #EAF3F3;
}
.responstable th:first-child {
display: table-cell;
text-align: center;
}
.responstable th:nth-child(2) {
display: table-cell;
}
.responstable th:nth-child(2) span {
display: none;
}
.responstable th:nth-child(2):after {
content: attr(data-th);
}
@media (min-width: 480px) {
.responstable th:nth-child(2) span {
display: block;
}
.responstable th:nth-child(2):after {
display: none;
}
}
.responstable td {
display: block;
word-wrap: break-word;
max-width: 7em;
}
.responstable td:first-child {
display: table-cell;
text-align: center;
border-right: 1px solid #D9E4E6;
}
@media (min-width: 480px) {
.responstable td {
border: 1px solid #D9E4E6;
}
}
.responstable th, .responstable td {
text-align: left;
margin: .5em 1em;
}
@media (min-width: 480px) {
.responstable th, .responstable td {
display: table-cell;
padding: 0.3em;
}
}
.tabdrop .dropdown-menu a{
padding: 20px;
}
#map-table-jana{
margin: 20px 0px 60px;
background: #fff;
overflow: hidden;
}
#reportable{
overflow: auto;
margin: 0.5em;
/* margin-left: 253px; */
}
#map-table-jana .text-center h3{
}
#map-table-jana .report-down{
padding: 25px;
border-bottom: 1px solid #e7e7e7;
}
#map-table-jana .repo_filter{
margin: 30px auto 15px;
}
table.dataTable.no-footer{
border-bottom: 0;
}
.dataTables_filter label > input{
visibility: visible;
position: relative;
padding: .1rem .75rem;
font-size: 1rem;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .1rem;
-webkit-transition: border-color 0.15s ease-in-out,-webkit-box-shadow 0.15s ease-in-out;
transition: border-color 0.15s ease-in-out,-webkit-box-shadow 0.15s ease-in-out;
transition: border-color 0.15s ease-in-out,box-shadow 0.15s ease-in-out;
transition: border-color 0.15s ease-in-out,box-shadow 0.15s ease-in-out,-webkit-box-shadow 0.15s ease-in-out;
}
</style>
<!-- table List -->
<div class="container">
<div id="map-table-jana">
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="health" role="tabpanel" aria-labelledby="health-tab">
<div class="row">
<div class="col-md-12">
<div class="p-4">
<div class="row">
<div class="col-md-9"><h4 class="text-uppercase m-0"><strong><?php echo $name ?> Data Table </strong></h4></div>
<div class="col-md-3 clearfix">
<!-- <a href="get_csv_emergency?type=health&&name=Health_Institutions&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px; float: right;"><i class="fa fa-download"></i> Download</button></a> -->
</div>
</div>
</div>
</div>
</div>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="table table-striped table-bordered table-hover" id="hydropower">
<thead class='thead-light' >
<tr>
<?php foreach ($data[0] as $key => $value){
if($key == "the geom"){
}else{
?>
<th><strong><?php echo $key ?></strong></th>
<?php }}?>
</tr>
</thead>
<?php foreach ($data as $v) {
?>
<tr class="tr_tbl">
<?php foreach ($v as $key => $value ) {
if($key == 'the geom'){
}else{
?>
<td><?php echo $value ?></td>
<?php } }?>
</tr>
<?php } ?>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="<?php echo base_url()?>assets/js/bootstrap-tabdrop.js"></script>
<script type="text/javascript">
$(".nav-tabs").tabdrop();
function myFunction() {
// Declare variables
var input, filter, div, tr, i ,j;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
//
div = document.getElementsByClassName("tab-pane");
//
// td = document.getElementsByTagName('td');
tr = document.getElementsByClassName('tr_tbl');
// console.log(td);
// console.log(h5);
// console.log(div);
// console.log(filter);
// console.log(input);
//
// // Loop through all list items, and hide those who don't match the search query
// var ab='<NAME>'
// console.log(ab.toUpperCase().indexOf(filter));
console.log(tr);
for(j = 0; j < tr.length; j++){
//console.log(tr);
var closeit = 0;
for (i = 0; i < tr[j].children.length; i++) {
var td = tr[j].children[i];
//console.log(td);
// a = h5[i].getElementsByTagName("a")[0];
//console.log(td[i].innerHTML.toUpperCase().indexOf(filter));
if(closeit == 0){
$("#"+td.id).parent().css('display','none');
//console.log("not found on"+td[i].id);
}
if ((td.innerText.toUpperCase().indexOf(filter) > -1) && closeit == 0) {
// console.log("found on"+td.id);
// console.log(closeit);
$("#"+td.id).parent().css('display','');
closeit = 1;
}
}
//console.log("row");
}
}
</script>
<file_sep>/application/views/admin/choose_icon.php
<style type="text/css">
label > input{ /* HIDE RADIO */
visibility: hidden; /* Makes input not-clickable */
position: absolute; /* Remove input from document flow */
}
label > input + img{ /* IMAGE STYLES */
cursor:pointer;
border:2px solid transparent;
}
label > input:checked + img{ /* (RADIO CHECKED) IMAGE STYLES */
border:2px solid #f00;
}
div#exampleModal {
overflow: hidden;
}
.map-marker{
width: 60px;
height: 80px;
margin: auto;
display: block;
margin-left: 12px;
}
</style>
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!-- page start-->
<div class="row">
<div class="col-sm-12">
<section class="panel">
<section class="panel">
<header class="panel-heading">
<b>Choose Map Icon Style</b>
<span class="tools pull-right">
<a href="<?php echo base_url()?>category?tbl=<?php echo $tbl ?>"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1fb5ad;border-color: #1fb5ad;margin-top: -7px;"><i class="fa fa-map-marker"></i> View In Map</button></a>
</span>
</header>
<div class="panel-body">
<?php
$error= $this->session->flashdata('msg');
if($error){ ?>
<div class="alert alert-info alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message!!!!</strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<form role="form" method="POST" action="" enctype="multipart/form-data">
<div class="form-group ">
<div class="col-md-9">
<br>
<div class="col-md-6">
Upload Image
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="" />
</div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>
<div>
<span class="btn btn-white btn-file">
<span class="fileupload-new"><i class="fa fa-paper-clip"></i> Select image</span>
<span class="fileupload-exists"><i class="fa fa-undo"></i> Change</span>
<input type="file" name="cat_pic" class="default" />
</span>
</div>
</div>
</div>
<div class="col-md-6">
Select Icon
<div class="panel panel-default icon-select" style="border: 1px solid #ddd;max-height: 150px; width: 425px;overflow-x: auto;" >
<div class="panel-body" style="overflow: hidden;">
<div class="form-group">
<div class="row">
<?php foreach($icons as $v){ ?>
<div class="col-md-3">
<label>
<input id="fb3" type="radio" value="<?php echo $v['marker_path']?>" name="icon" value="med" />
<img class="map-marker" src="<?php echo $v['marker_path']?>" alt="Logo" >
</label>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<a href="#"> <button type="submit" name="submit" class="btn btn-success" style="background-color: #1fb5ad;border-color: #1fb5ad;">Update</button></a>
</div>
</div>
</form>
</div>
</section>
</section>
</div>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/controllers/Admin/SiteController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class SiteController extends CI_Controller
{
function __construct()
{
parent::__construct();
// if(($this->session->userdata('logged_in'))!=TRUE)
// {
//
// redirect('admin');
// }else{
//
// }
$this->load->helper('url');
$this->load->library('form_validation');
$this->load->model('Site_model');
}
//english start
public function site_setting(){
$this->body['site_info']=$this->Site_model->site_setting(1);
//var_dump($this->body['site_info']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/site_setting',$this->body);
$this->load->view('admin/footer');
}
public function update_site_text(){
if( $_FILES['site_logo']['name']==''){
var_dump($_POST);
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,1);
echo $update;
if($update){
$this->session->set_flashdata('msg','Site Logo and Site Text successfully Updated');
redirect('site_setting');
}else{
//error
}
}else{
$file_name = $_FILES['site_logo']['name'];
$img_upload=$this->Site_model->do_upload($file_name,'site_logo');
if($img_upload['status']==1){
$ext=$img_upload['upload_data']['file_ext'];
unset($_POST['submit']);
$image_path=base_url().'uploads/site_setting/site_logo'.$ext ;
$_POST['site_logo']=$image_path;
$update=$this->Site_model->update_data($_POST,1);
if($update){
$this->session->set_flashdata('msg','Site Logo and Site Text successfully Updated');
redirect('site_setting');
}else{
echo 'errp';
}
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('site_setting');
}
}
}
public function update_cover(){
if( $_FILES['cover_photo']['name']==''){
// var_dump($_POST);
// exit();
var_dump($_POST);
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,1);
echo $update;
if($update){
$this->session->set_flashdata('msg','Cover Photo and Cover Text successfully Updated');
redirect('site_setting');
}else{
//error
}
}else{
$file_name = $_FILES['cover_photo']['name'];
$img_upload=$this->Site_model->do_upload_cover($file_name,'cover_photo');
if($img_upload['status']==1){
$ext=$img_upload['upload_data']['file_ext'];
unset($_POST['submit']);
$image_path=base_url().'uploads/site_setting/cover_photo'.$ext ;
$_POST['cover_photo']=$image_path;
$update=$this->Site_model->update_data($_POST,1);
if($update){
$this->session->set_flashdata('msg','Cover Photo and Cover Text successfully Updated');
redirect('site_setting');
}else{
echo 'errp';
}
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('site_setting');
}
}
}
public function footer_text(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,1);
echo $update;
if($update){
$this->session->set_flashdata('msg','Footer Right Text successfully Updated');
redirect('site_setting');
}else{
//error
}
}
public function important_link(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,1);
echo $update;
if($update){
$this->session->set_flashdata('msg','Importnat Links successfully Updated');
redirect('site_setting');
}else{
//error
}
}
public function find_us_links(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,1);
echo $update;
if($update){
$this->session->set_flashdata('msg','Find us Links successfully Updated');
redirect('site_setting');
}else{
//error
}
}
public function copyright(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,1);
echo $update;
if($update){
$this->session->set_flashdata('msg','Copy Right Text successfully Updated');
redirect('site_setting');
}else{
//error
}
}
public function map_zoom(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,1);
$update=$this->Site_model->update_data($_POST,2);
echo $update;
if($update){
$this->session->set_flashdata('msg','Map zoom and center successfully Updated');
redirect('site_setting');
}else{
//error
}
}
//english end
//nepali start
public function site_setting_nep(){
$this->body['site_info']=$this->Site_model->site_setting(2);
//var_dump($this->body['site_info']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/site_setting_nep',$this->body);
$this->load->view('admin/footer');
}
public function update_site_text_nep(){
if( $_FILES['site_logo']['name']==''){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,2);
// echo $update;
if($update){
$this->session->set_flashdata('msg','Site Logo and Site Text successfully Updated');
redirect('site_setting_nep');
}else{
//error
}
}else{
$file_name = $_FILES['site_logo']['name'];
$img_upload=$this->Site_model->do_upload($file_name,'site_logo');
if($img_upload['status']==1){
$ext=$img_upload['upload_data']['file_ext'];
unset($_POST['submit']);
$image_path=base_url().'uploads/site_setting/site_logo'.$ext ;
$_POST['site_logo']=$image_path;
$update=$this->Site_model->update_data($_POST,2);
if($update){
$this->session->set_flashdata('msg','Site Logo and Site Text successfully Updated');
redirect('site_setting_nep');
}else{
echo 'errp';
}
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('site_setting_nep');
}
}
}
public function update_cover_nep(){
if( $_FILES['cover_photo']['name']==''){
// var_dump($_POST);
// exit();
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,2);
echo $update;
if($update){
$this->session->set_flashdata('msg','Cover Photo and Cover Text successfully Updated');
redirect('site_setting_nep');
}else{
//error
}
}else{
$file_name = $_FILES['cover_photo']['name'];
$img_upload=$this->Site_model->do_upload_cover($file_name,'cover_photo');
if($img_upload['status']==1){
$ext=$img_upload['upload_data']['file_ext'];
unset($_POST['submit']);
$image_path=base_url().'uploads/site_setting/cover_photo'.$ext ;
$_POST['cover_photo']=$image_path;
$update=$this->Site_model->update_data($_POST,2);
if($update){
$this->session->set_flashdata('msg','Cover Photo and Cover Text successfully Updated');
redirect('site_setting_nep');
}else{
echo 'errp';
}
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('site_setting_nep');
}
}
}
public function footer_text_nep(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,2);
echo $update;
if($update){
$this->session->set_flashdata('msg','Footer Right Text successfully Updated');
redirect('site_setting_nep');
}else{
//error
}
}
public function important_link_nep(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,2);
if($update){
$this->session->set_flashdata('msg','Importnat Links successfully Updated');
redirect('site_setting_nep');
}else{
//error
}
}
public function find_us_links_nep(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,2);
//echo $update;
if($update){
$this->session->set_flashdata('msg','Find us Links successfully Updated');
redirect('site_setting_nep');
}else{
//error
}
}
public function copyright_nep(){
unset($_POST['submit']);
$update=$this->Site_model->update_data($_POST,2);
//echo $update;
if($update){
$this->session->set_flashdata('msg','Copy Right Text successfully Updated');
redirect('site_setting_nep');
}else{
//error
}
}
//nepali end
}//end
<file_sep>/application/views/header.php
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="<?php echo base_url();?>assets/img/ng.png">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<title>Municipal GIS</title>
<!-- Bootstrap core CSS -->
<link href="<?php echo base_url();?>assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script>window.jQuery || document.write('<script src="<?php echo base_url();?>assets/js/vendor/jquery-1.11.2.min.js"><\/script>')</script>
<script src="<?php echo base_url();?>assets/js/vendor/popper.min.js"></script>
<script src="<?php echo base_url();?>assets/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="<?php echo base_url();?>assets/js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
<script src="<?php echo base_url();?>assets/js/vendor/jquery.nicescroll.min.js"></script>
<!-- map -->
<link href="<?php echo base_url();?>assets/css/sitemapstyler.css" rel="stylesheet" type="text/css" media="screen" />
<!-- Custom fonts for this template -->
<link href="<?php echo base_url();?>assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="<?php echo base_url();?>assets/vendor/simple-line-icons/css/simple-line-icons.css" rel="stylesheet" type="text/css">
<!-- Custom styles for this template -->
<link href="<?php echo base_url();?>assets/css/landing-page.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/css/styles.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/style.css">
<link rel="stylesheet" href="assets/css/jquery.dropdown.css">
<!-- <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/css/new.css"> -->
<!-- datatable -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
<!-- datatable end -->
<!-- end data -->
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"/>
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/leaflet.label.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/leaflet.label.js"></script>
<script src="<?php echo base_url();?>assets/js/carousels.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/sitemapstyler.js"></script>
<script src="<?php echo base_url();?>assets/js/vendor/jquery.matchHeight.js"></script>
<script src="<?php echo base_url();?>assets/js/plugins.js"></script>
<link href="https://fonts.googleapis.com/css?family=Mukta:200,300,400,500,600,700,800" rel="stylesheet">
<script>
$(document).ready(function(){
var imgSrc = $('.banner-item>img').attr('src');
$('.banner-item').css({"background" : "url("+imgSrc+")", "background-position": "center", "background-size": "cover"});
$(".banner-item>img").remove();
});
</script>
<!-- div is created to keep the map in its certain area whichever amount of area is located to display the map -->
<style type="text/css">
.scrolling-wrap{
overflow-x: hidden !important;
}
.leaflet-popup-content {
overflow: auto;
}
div#map {
margin-top: 44px ;
}
#load{
width:100%;
height:100%;
position:fixed;
z-index:9999;
background:url("img/loader.gif") no-repeat center center rgba(0,0,0,0.25)
}
}
#over_map {
position: absolute;
top: 117px;
left: 12px;
z-index: 999;
}
.subscribe-wrap .fbox .list-group a, .subscribe-wrap .fbox .list-group a:hover{
color: #fff;
}
body {
overflow-x: hidden;
}
/**/
</style>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div id="load" style="background-color: white;"></div>
<header id="website-header">
<nav class="navbar navbar-expand-lg navbar-light bg-white">
<div class="container">
<a class="navbar-brand" href="<?php echo base_url();?>">
<div class="logo-gov clearfix">
<img src="<?php echo $site_info['site_logo'] ?>" alt="Logo">
<h6>
<strong><?php echo $site_info['site_name'] ?></strong>
<div class="sub-head"> <small><?php echo $site_info['site_text'] ?></small> </div>
</h6>
</div>
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="index.php"><?php echo $site_info['nav_7'] ?> <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url()?>category?tbl=0 && name=0"><?php echo $site_info['nav_1'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url()?>report_page"><?php echo $site_info['nav_2'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url()?>contact"><?php echo $site_info['nav_3'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url()?>inventory"><?php echo $site_info['nav_4'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url()?>datasets"><?php echo $site_info['nav_5'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo base_url()?>publication"><?php echo $site_info['nav_6'] ?></a>
</li>
<!-- <li class="nav-item">
<a class="nav-link" href="<?php echo base_url()?>about">About</a>
</li> -->
<!-- <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="la la-language"></i> : ने
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">अङ्रेजी</a>
</div>
</li> -->
<!-- <li class="nav-item" > -->
<!-- <ul class="lang-switcher">
<a href="#" class="is-active">En</a> | <a href="#">Fr</a>
</ul> -->
<?php
if($this->session->userdata('Language')==NULL){
$this->session->set_userdata('Language','nep');
}
$lang=$this->session->get_userdata('Language');
if($lang['Language']=='en'){
?>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="<?php echo base_url();?>nep?urll=<?php echo $urll ?>" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="la la-language"></i> : En
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="<?php echo base_url();?>nep?urll=<?php echo $urll ?>">Nepali</a>
</div>
</li>
<?php }else{ ?>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="<?php echo base_url();?>nep?urll=<?php echo $urll ?>" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="la la-language"></i> : ने
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="<?php echo base_url();?>en?urll=<?php echo $urll ?>">अङ्रेजी</a>
</div>
</li>
<?php } ?>
<!-- </li> -->
</ul>
</div>
</div>
</nav>
</header>
<script>
// console.log('header');
// $('.lang-nav').click(function(){
// var lang_name=$(this).attr('name');
// console.log(lang_name);
// if(lang_name =='en'){
// $(this).attr("id","nep");
// $('.lang-name').html('nep').trigger('change');
// }else{
// $(this).attr("id","en");
// $('.lang-name').html('en').trigger('change');
// }
//
// });
</script>
<file_sep>/application/views/admin/cat_tables.php
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!-- page start-->
<div class="row">
<div class="col-sm-12">
<section class="panel">
<section class="panel">
<header class="panel-heading">
Hover Table
<span class="tools pull-right">
<a href="javascript:;" class="fa fa-chevron-down"></a>
<a href="javascript:;" class="fa fa-cog"></a>
<a href="javascript:;" class="fa fa-times"></a>
</span>
</header>
<div class="panel-body">
<?php
$error= $this->session->flashdata('msg');
if($error){ ?>
<div class="alert alert-info alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message!!!!</strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<table class="table table-hover">
<thead>
<tr>
<td>
Table Name
</td>
<td>
Operations
</td>
</tr>
</thead>
<tbody>
<?php foreach($data as $v ){
if($v == "users"||$v == "spatial_ref_sys"||$v == "project_tbl"||$v == "geography_columns"||$v == "geometry_columns"||$v == "raster_overviews"||$v == "raster_overviews"||$v == "raster_columns"){}else{
?>
<tr>
<td><?php echo $v;?></td>
<td><a href="<?php echo base_url()?>data_tables?tbl_name=<?php echo base64_encode($v);?>">view</a>/<a href="<?php echo base_url()?>drop_cat_table?tbl_name=<?php echo base64_encode($v);?>">Delete</a></td>
</tr>
<?php }} ?>
</tbody>
</table>
</div>
</section>
</section>
</div>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/views/admin/edit_map_download.php
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
Edit Map
</header>
<div class="panel-body">
<div class="position-center">
<h5><i class="fa fa-info-circle"></i> Note: Edit Map Download Part</h5><br>
<form role="form" method="POST" action="" enctype="multipart/form-data">
<?php
$error= $this->session->flashdata('msg');
if($error){ ?>
<div class="alert alert-info alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message!!!!</strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<div class="form-group" >
<label for="exampleInputFile">Map Category</label>
<select name="category">
<option value="<?php echo $e_data['category'] ?>"><?php echo $e_data['category'] ?></option>
<option value="admin" >Administrative Maps</option>
<option value="risk" >Risk and Hazard Maps</option>
<option value="socio" >Socio Economic Maps</option>
<option value="tourist" >Tourist Maps</option>
<option value="land" >Land use and Land Cover</option>
<option value="other" >Others</option>
</select>
</div>
<div class="form-group">
<input type="hidden" value="<?php echo $e_data['id'];?>" name="id">
<label for="exampleInputEmail1">Title</label>
<input type="text" value="<?php echo $e_data['title'] ?>" name="title" class="form-control" id="exampleInputEmail1" required>
</div>
<div class="form-group">
<label class="col-sm-3 control-label col-sm-2">Summary</label>
<div class="col-sm-10">
<textarea class="form-control" name="summary" rows="5" required><?php echo $e_data['summary'] ?></textarea>
</div>
</div>
<button type="submit" name="submit" class="btn btn-info">Upload</button>
</form>
</div>
</div>
</section>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/views/admin/edit_project.php
<!--main content start-->
<section id="main-content" class="">
<section class="wrapper">
<!-- page start-->
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
Form Elements
</header>
<div class="panel-body">
<form class="form-horizontal bucket-form" method="post" action="">
<input type="hidden" value="<?php echo $edit_data[$fields[$i]];?>" name="id">
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-6">
<input type="text" value="" name="" class="form-control round-input">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Project Partner Brief</label>
<div class="col-sm-6">
<input type="text" value="" name="" class="form-control round-input">
</div>
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/views/admin/add_ghatana.php
<!--main content start-->
<section id="main-content" class="">
<section class="wrapper">
<!-- page start-->
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
Ghatana
</header>
<div class="panel-body">
<form class="form-horizontal bucket-form" method="post" action="">
<?php
for($i=0;$i<sizeof($fields);$i++){
if($fields[$i]=='id'){
?>
<?php }elseif($fields[$i]=='district'){
?>
<div class="form-group">
<label class="col-sm-3 control-label"><?php echo ucwords(str_replace("_"," ",$fields[$i]));?></label>
<div class="col-sm-6">
<select class="form-control input-sm m-bot15" name="<?php echo $fields[$i];?>">
<option value="0" selected disabled>Select a district</option>
<option value="Taplejung">Taplejung</option>
<option value="Panchthar">Panchthar</option>
<option value="Ilaam">Ilaam</option>
<option value="Jhapa">Jhapa</option>
<option value="Morang">Morang</option>
<option value="Sunsari">Sunsari</option>
<option value="Dhankuta">Dhankuta</option>
<option value="Terhathum">Terhathum</option>
<option value="Bhojpur">Bhojpur</option>
<option value="Shankhuwasabha">Shankhuwasabha</option>
<option value="Solukhumbu">Solukhumbu</option>
<option value="Khotang">Khotang</option>
<option value="Okhaldhunga">Okhaldhunga</option>
<option value="Udayapur">Udayapur</option>
<option value="Siraha">Siraha</option>
<option value="Saptari">Saptari</option>
<option value="Dhanusha">Dhanusha</option>
<option value="Mahottari">Mahottari</option>
<option value="Sarlahi">Sarlahi</option>
<option value="Sindhuli">Sindhuli</option>
<option value="Ramechhap">Ramechhap</option>
<option value="Dolakha">Dolakha</option>
<option value="RASUWA">RASUWA</option>
<option value="Sindhupalchowk">Sindhupalchowk</option>
<option value="Nuwakot">Nuwakot</option>
<option value="Dhading">Dhading</option>
<option value="Kathmandu">Kathmandu</option>
<option value="Lalitpur">Lalitpur</option>
<option value="Bhaktapur">Bhaktapur</option>
<option value="Kavrepalanchowk">Kavrepalanchowk</option>
<option value="Makawanpur">Makawanpur</option>
<option value="Rautahat">Rautahat</option>
<option value="Bara">Bara</option>
<option value="Parsa">Parsa</option>
<option value="Chitawan">Chitawan</option>
<option value="Nawalparasi">Nawalparasi</option>
<option value="Rupandehi">Rupandehi</option>
<option value="Kapilbastu">Kapilbastu</option>
<option value="Palpa">Palpa</option>
<option value="Arghakhanchi">Arghakhanchi</option>
<option value="Gulmi">Gulmi</option>
<option value="Tanahu">Shyanja</option>
<option value="43">Tanahu</option>
<option value="Gorkha">Gorkha</option>
<option value="Lamjung">Lamjung</option>
<option value="Kaski">Kaski</option>
<option value="Manang">Manang</option>
<option value="Mustang">Mustang</option>
<option value="Myagdi">Myagdi</option>
<option value="Baglung">Baglung</option>
<option value="Parbat">Parbat</option>
<option value="Dang">Dang</option>
<option value="Pyuthan">Pyuthan</option>
<option value="Rolpa">Rolpa</option>
<option value="Salyan">Salyan</option>
<option value="Rukum">Rukum</option>
<option value="Dolpa">Dolpa</option>
<option value="Mugu">Mugu</option>
<option value="Humla">Humla</option>
<option value="Jumla">Jumla</option>
<option value="Kalikot">Kalikot</option>
<option value="Jajarkot">Jajarkot</option>
<option value="Dailekh">Dailekh</option>
<option value="Surkhet">Surkhet</option>
<option value="Bardiya">Bardiya</option>
<option value="Banke">Banke</option>
<option value="Kailali">Kailali</option>
<option value="Doti">Doti</option>
<option value="Achhaam">Achhaam</option>
<option value="Bajura">Bajura</option>
<option value="Bajhang">Bajhang</option>
<option value="Darchula">Darchula</option>
<option value="Baitadi">Baitadi</option>
<option value="Dadeldhura">Dadeldhura</option>
<option value="Kanchanpur">Kanchanpur</option>
</select>
</div>
</div>
<?php }elseif($fields[$i]=='ward'){
?>
<div class="form-group">
<label class="col-sm-3 control-label"><?php echo ucwords(str_replace("_"," ",$fields[$i]));?></label>
<div class="col-sm-6">
<select class="form-control input-sm m-bot15" name="<?php echo $fields[$i];?>">
<option value="0" selected disabled>Select ward</option>
<option value="10" >ward no 10 </option>
<option value="9" >ward no 9 </option>
<option value="8" >ward no 8 </option>
<option value="7" >ward no 7 </option>
<option value="6" >ward no 6 </option>
<option value="5" >ward no 5 </option>
<option value="4" >ward no 4 </option>
<option value="3" >ward no 3 </option>
<option value="2" >ward no 2 </option>
<option value="1" >ward no 1 </option>
</select>
</div>
</div>
<?php }elseif($fields[$i]=='incident'){
?>
<div class="form-group">
<label class="col-sm-3 control-label"><?php echo ucwords(str_replace("_"," ",$fields[$i]));?></label>
<div class="col-sm-6">
<select class="form-control input-sm m-bot15" name="<?php echo $fields[$i];?>">
<option value="0" selected disabled>Select an incident</option>
<option value="Flash Flood">Flash Flood</option>
<option value="Leak">Leak</option>
<option value="Sedimentation">Sedimentation</option>
<option value="Accident">Accident</option>
<option value="Biological">Biological</option>
<option value="Frost">Frost</option>
<option value="Pollution">Pollution</option>
<option value="Famine">Famine</option>
<option value="Panic">Panic</option>
<option value="Explosion">Explosion</option>
<option value="Drought">Drought</option>
<option value="Strong_Wind">Strong Wind</option>
<option value="Forest Fire">Forest Fire</option>
<option value="Snow Storm">Snow Storm</option>
<option value="Heat Wave">Heat Wave</option>
<option value="Plague">Plague</option>
<option value="Hail Storm">Hail Storm</option>
<option value="Structure Collapse">Structure Collapse</option>
<option value="Tuin Chudera">Tuin Chudera</option>
<option value="Bridge Collapse">Bridge Collapse</option>
<option value="Air Crash">Air Crash</option>
<option value="Avalanche">Avalanche</option>
<option value="Cold Wave">Cold Wave</option>
<option value="Boat Capsize">Boat Capsize</option>
<option value="High Altitude">High Altitude</option>
<option value="Heavy Rainfall">Heavy Rainfall</option>
<option value="Drowning">Drowning</option>
<option value="Wind storm">Wind storm</option>
<option value="Hailstone">Hailstone</option>
<option value="Epidemic">Epidemic</option>
<option value="Other">Other</option>
<option value="storm">storm</option>
<option value="Bus accident">Bus accident</option>
<option value="Lightning">Lightning</option>
<option value="Thunderbolt">Thunderbolt</option>
<option value="Fire">Fire</option>
<option value="Landslide">Landslide</option>
<option value="Flood">Flood</option>
<option value="Earthquake">Earthquake</option>
</select>
</div>
</div>
<?php }else{ ?>
<div class="form-group">
<label class="col-sm-3 control-label"><?php echo ucwords(str_replace("_"," ",$fields[$i]));?></label>
<div class="col-sm-6">
<input type="text" name="<?php echo $fields[$i];?>" class="form-control round-input">
</div>
</div>
<?php }} ?>
<div class="col-md-6">
<button type="submit" name="submit" class="btn btn-info">Submit</button>
</div>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/models/Newsletter.php
<?php
class Newsletter extends CI_Model {
public function send_mail($message,$mail_subject)
{
$this->load->library('email');
$this->db->select('*');
$q=$this->db->get('newsletter');
$mail=$q->result_array();
foreach($mail as $m){
$u_email=$m['email'];
$m='test';
$config['protocol']='smtp';
$config['smtp_host']='ssl://smtp.googlemail.com';
$config['smtp_port']='465';
$config['smtp_timeout']='30';
$config['smtp_user']='<EMAIL>';
$config['smtp_pass']='<PASSWORD>...';
$config['charset']='utf-8';
$config['newline']="\r\n";
$config['wordwrap'] = TRUE;
$config['mailtype'] = 'html';
$this->email->initialize($config);
//$this->load->library('email', $config);
//$this->email->set_mailtype("html");
$this->email->from('VSO Website', 'VSO');
$this->email->to($u_email);
$this->email->subject($mail_subject);
$this->email->message($message);
if($this->email->send())
{
return 1;
}else{
return 0;
}
}
}
public function register($data)
{
$this->db->insert('newsletter',$data);
if ($this->db->affected_rows() > 0)
{
return $this->db->insert_id();
}
else
{
$error = $this->db->error();
return $error;
}
}
//publication part
public function get_pub_all($tbl) {
$this->db->select('*');
$res=$this->db->get($tbl);
return $res->result_array();
}
public function get_pub_filter($cat,$tbl){
$this->db->select('*');
$this->db->where('category',$cat);
$res=$this->db->get($tbl);
return $res->result_array();
}
//end
}
<file_sep>/application/controllers/Admin/MapDownload.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MapDownload extends CI_Controller
{
function __construct()
{
parent::__construct();
if(($this->session->userdata('logged_in'))!=TRUE)
{
redirect('admin');
}else{
}
$this->load->model('Map_model');
}
public function map_show()
{
if(isset($_POST['submit']))
{
$id=$this->input->post('id');
$file_name = $_FILES['map_pic']['name'];
// $ext = pathinfo($file_name, PATHINFO_EXTENSION);
$img_upload=$this->Map_model->do_upload($file_name,$id);
if($img_upload['status']== 1){
$ext=$img_upload['upload_data']['file_ext'];
$image_path=base_url() . 'uploads/map_download/'.$id.$ext ;
$data=array(
'photo'=>$image_path,
'photo_thumb'=>base_url() . 'uploads/map_download/'.$id.'_thumb'.$ext
);
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/map_download/'.$id.$ext;
$config['new_image'] = './uploads/map_download/'.$id.$ext;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 800;
$config['height'] = 800;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
//var_dump($this->image_lib->resize());
//var_dump($this->image_lib->display_errors());
// exit();
if(!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$update=$this->Map_model->update_map_download($id,$data,'maps_download');
$this->session->set_flashdata('msg','successfully Photo Changed');
redirect('map_show');
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('map_show');
}
}else{
$this->body['data']= $this->Map_model->get_map_download_data();
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/map_download',$this->body);
$this->load->view('admin/footer');
}
}
public function add_maps(){
if(isset($_POST['submit'])){
unset($_POST['submit']);
unset($_POST['map_pic']);
//var_dump($_POST);
$insert=$this->Map_model->insert_map_download($_POST);
if($insert!=""){
$file_name = $_FILES['map_pic']['name'];
//$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$img_upload=$this->Map_model->do_upload($file_name,$insert);
if($img_upload['status'] == 1){
$ext=$img_upload['upload_data']['file_ext'];
$image_path=base_url() . 'uploads/map_download/'.$insert.$ext ;
$data=array(
'photo'=>$image_path,
'photo_thumb'=>base_url() . 'uploads/map_download/'.$insert.'_thumb'.$ext
);
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/map_download/'.$insert.$ext;
$config['new_image'] = './uploads/map_download/'.$insert.$ext;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 800;
$config['height'] = 800;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
//var_dump($this->image_lib->resize());
//var_dump($this->image_lib->display_errors());
// exit();
if(!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$update=$this->Map_model->update_map_download($insert,$data,'maps_download');
$this->session->set_flashdata('msg','Map Added successfully');
redirect('map_show');
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('map_show');
}
}else{
//db error
}
}else{
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/add_map_download');
$this->load->view('admin/footer');
}
}
public function edit_map()
{
if(isset($_POST['submit'])){
unset($_POST['submit']);
var_dump($_POST);
$tbl='maps_download';
$update=$this->Map_model->update_map_download($this->input->post('id'),$_POST,$tbl);
if($update){
$this->session->set_flashdata('msg','Updated successfully');
redirect('map_show');
}else{
//db error
}
}else{
$this->body['e_data']=$this->Map_model->e_data_map(base64_decode($this->input->get('id')));
//echo base64_decode($this->input->get('id'));
//var_dump($this->body['e_data']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/edit_map_download',$this->body);
$this->load->view('admin/footer');
}
}
public function delete_map(){
$id = $this->input->get('id');
$delete=$this->Map_model->delete_map($id);
$this->session->set_flashdata('msg','Id number '.$id.' row data was deleted successfully');
redirect('map_show');
}
}
<file_sep>/application/views/publication.php
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<style type="text/css">
.input-group-addon {
position: absolute;
right: 10px;
bottom: 13px;
z-index: 2;
}
.publish-srch {
padding: 35px;
border-bottom: 1px solid #eee;
}
.publish{
padding: 35px;
}
.publish img{
width: 100%;
height: auto;
object-fit: cover;
}
.publish h5{
font-weight: bold;
border-bottom: 1px solid #ccc;
}
.publish .publish-des{
text-align: justify;
}
#myUL {
/* Remove default list styling */
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd; /* Add a border to all links */
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6; /* Grey background color */
padding: 12px; /* Add some padding */
text-decoration: none; /* Remove default text underline */
font-size: 18px; /* Increase the font-size */
color: black; /* Add a black text color */
display: block; /* Make it into a block element to fill the whole list */
}
#myUL li a:hover:not(.header) {
background-color: #eee; /* Add a hover effect to all links, except for headers */
}
.publication-item .thumb{
height: 120px;
}
.publication-item .thumb img{
}
</style>
<div class="container" >
<!-- search bar -->
<div class="mt-2 pt-4 pb-4">
<div class="row">
<div class="col-md-6">
<label for="pub_cat"><strong><?php echo $site_info['publ_type'] ?></strong></label>
</div>
<div class="col-md-6">
<label for="myInput"><strong><?php echo $site_info['search'] ?></strong></label>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<select class="form-control" id="pub_cat">
<option value=0>ALL</option>
<option value="muni_pub">Municipal Publications</option>
<option value="law_act">Laws and Acts</option>
<option value="plan_politics">Plans and Policies</option>
<option value="others">Others</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="myInput" onkeyup="myFunction()">
</div>
</div>
</div>
</div>
<!-- data Column -->
<div class="row justify-content-center mb-4 pb-3" id="filter_pub">
<?php foreach($data as $d ){ ?>
<div class="col-md-4 col-xl-3">
<div class="publication-item padding bg-white" data-mh="publication">
<div class="thumb"><img src="<?php echo $d['photo']?>" ></div>
<h6 class="name" id="<?php echo $d['id'] ?>"><?php echo $d['title']?></h6>
<p><?php echo $d['summary']?></p>
<a href="<?php echo base_url()?>download?file=<?php echo $d['file']?> && title="<?php echo $d['title']?>" class="btn btn-primary btn-block"><?php echo $site_info['download'] ?> <i class="la la-download"></i></a>
</div>
</div>
<?php } ?>
</div>
<!-- data Column -->
</div>
<script type="text/javascript">
function myFunction() {
// Declare variables
var input, filter, div, h5, a, i;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
div = document.getElementsByClassName("myUL");
h5 = document.getElementsByTagName('h5');
//console.log(h5);
// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < h5.length; i++) {
// a = h5[i].getElementsByTagName("a")[0];
//console.log(h5[i].innerHTML.toUpperCase().indexOf(filter));
if (h5[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
// console.log('if');
$("#"+h5[i].id).parent().parent().parent().parent().css('display','');
} else {
//console.log('else');
$("#"+h5[i].id).parent().parent().parent().parent().css('display','none');
}
}
}
$('#pub_cat').change(function(){
var category = $(this).val();
$.ajax({
type: "GET",
// data: name,
url: "NewsletterController/get_category_pub?cat="+category,
beforeSend: function() {
$('#filter_pub').empty();
$('#filter_pub').html('<h2>Loading</h2>');
},
complete: function() {
// $('#filter_pub').empty();
// $('#filter_pub').append('<h2>Loading</h2>');
},
success: function (result) {
$('#filter_pub').html('');
var data = JSON.parse(result);
console.log(data.length);
//console.log (data[0].summary);
var i;
for(i=0; i<data.length; i++){
var div_pub = "";
console.log(data.length);
div_pub +='<div class="col-md-4 col-xl-3">';
div_pub +='<div class="publication-item" data-mh="publication">';
div_pub +='<div class="thumb"><img src="'+data[i].photo+'"></div>';
div_pub +='<h6 class="name" id="'+data[i].id+'">'+data[i].title+'</h6>';
div_pub +='<p>'+data[i].summary+'</p>';
div_pub +='<a href="<?php echo base_url()?>download?file=<?php echo $d['file']?> && title="'+data[i].title+'" class="btn btn-primary btn-block">डाउनलोड <i class="la la-download"></i></a>';
div_pub +='</div>';
div_pub +='</div>';
$('#filter_pub').append(div_pub);
console.log(div_pub);
}
}
})
});
</script>
<file_sep>/application/controllers/Admin/AboutController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class AboutController extends CI_Controller
{
function __construct()
{
parent::__construct();
if(($this->session->userdata('logged_in'))!=TRUE)
{
redirect('admin');
}else{
}
$this->load->dbforge();
$this->load->helper('url');
$this->load->model('About_model');
}
public function view_about()
{
$this->body['data']=$this->About_model->get_about();
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/about',$this->body);
$this->load->view('admin/footer');
}
public function edit_about()
{
$id=base64_decode($this->input->get('id'));
if(isset($_POST['submit'])){
if( $_FILES['proj_pic']['name']==''){
$data= array(
'title'=>$this->input->post('title'),
'summary'=>$this->input->post('summary'),
);
$update=$this->About_model->update_data($id,$data);
if($update==1){
$this->session->set_flashdata('msg','Data successfully Updated');
redirect('view_about');
}else{
//error
}
}else{
$file_name = $_FILES['proj_pic']['name'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$data=array(
'title'=>$this->input->post('title'),
'summary'=>$this->input->post('summary'),
);
$insert=$this->About_model->update_data($id,$data);
if($insert==1){
$img_upload=$this->About_model->do_upload($file_name,$id);
if($img_upload==1){
$image_path=base_url() . 'uploads/about/'.$id.'.'.$ext ;
$img=array(
'photo'=>$image_path,
);
$update_path=$this->About_model->update_data($id,$img);
$this->session->set_flashdata('msg','Publication successfully Updated');
redirect('view_about');
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('edit_about');
}
}else{
//db error
}
}
}else{
$this->body['edit_data']=$this->About_model->get_edit_data(base64_decode($this->input->get('id')),'about');
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/edit_publication',$this->body);
$this->load->view('admin/footer');
}
}
}
<file_sep>/application/views/admin/login-page.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<meta name="keyword" content="vso">
<link rel="shortcut icon" href="img/favicon.png">
<title>Admin Login </title>
<!-- Bootstrap core CSS -->
<link href="<?php echo base_url();?>assets/admin/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/admin/css/bootstrap-reset.css" rel="stylesheet">
<!--external css-->
<link href="<?php echo base_url();?>assets/admin/css/font-awesome.css" rel="stylesheet" />
<!-- Custom styles for this template -->
<link href="<?php echo base_url();?>assets/admin/css/style.css?1" rel="stylesheet">
<link href="<?php echo base_url();?>assets/admin/css/style-responsive.css" rel="stylesheet" />
<!-- HTML5 shim and Respond.js IE8 support of HTML5 tooltipss and media queries -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<![endif]-->
</head>
<body class="lock-screen" onload="startTime()">
<div class="lock-wrapper" style="overflow:hidden; position:relative;">
<div id="time" style="color:rgba(0,0,0,0.5); font-weight:300; position:relative; top:50px; object-fit:center; " ></div>
<div class="lock-box text-center">
<form class="form-signin" method="post" action="">
<!-- <h2 class="form-signin-heading no-padding">sign in now</h2> -->
<?php
$error= $this->session->flashdata('Login');
if($error){
echo $error;
}
?>
<div class="login-wrap">
<div class="user-login-info">
<input type="text" class="form-control" name="username" placeholder="User ID" autofocus>
<input type="password" class="form-control" name="password" placeholder="<PASSWORD>">
</div>
<!-- <label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
<span class="pull-right">
<a data-toggle="modal" href="#myModal"> Forgot Password?</a>
</span>
</label> -->
<button class="btn btn-lg btn-login btn-block" name="submit" type="submit">Sign iin</button>
<!-- <div class="registration">
Don't have an account yet?
<a class="" href="registration.html">
Create an account
</a>
</div> -->
</div>
<!-- Modal -->
<!-- <div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Forgot Password ?</h4>
</div>
<div class="modal-body">
<p>Enter your e-mail address below to reset your password.</p>
<input type="text" name="email" placeholder="Email" autocomplete="off" class="form-control placeholder-no-fix">
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
<button class="btn btn-success" type="button">Submit</button>
</div>
</div>
</div>
</div> -->
<!-- modal -->
</form>
</div>
</div>
<script>
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('time').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</body>
</html>
<file_sep>/application/views/main.php
<script>
$(document).ready(function(){
bannerHeight();
window.onresize = function(event) {
bannerHeight();
}
function bannerHeight() {
vph = $(window).height();
headerHeight = $("#website-header").height();
vph = vph - headerHeight;
$("#banner").height(vph);
vph = (vph - $(".banner-item").height())/2;
$(".banner-item").css('padding-top', vph);
$(".banner-item").css('padding-bottom', vph);
}
});
</script>
<div id="banner">
<div class="banner-item">
<img src="<?php echo $site_info['cover_photo'] ?>" class="banner-img">
<div class="container clearfix">
<div class="banner-caption text-center mb-4">
<h2><strong><?php echo $site_info['cover_big'] ?></strong></h2>
<p>
<?php echo $site_info['cover_small'] ?>
</p>
</div>
<div class="row justify-content-center">
<div class="col-md-2">
<div class="disaster-summary-item" data-mh="summary-item">
<i class="la la-fire"></i>
<h6>बाडी</h6>
<h4>२०</h4>
</div>
</div>
<div class="col-md-2">
<div class="disaster-summary-item" data-mh="summary-item">
<i class="la la-fire"></i>
<h6>आगलागी</h6>
<h4>२५</h4>
</div>
</div>
<div class="col-md-2">
<div class="disaster-summary-item" data-mh="summary-item">
<i class="la la-fire"></i>
<h6>पहिरो</h6>
<h4>१०</h4>
</div>
</div>
<div class="col-md-2">
<div class="disaster-summary-item" data-mh="summary-item">
<i class="la la-fire"></i>
<h6>चट्याङ</h6>
<h4>४०</h4>
</div>
</div>
<div class="col-md-2">
<a href="<?php echo base_url() ?>report_page" class="disaster-summary-item" data-mh="summary-item">
<p>थप +</p>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="bg-dark" id="nextDiv">
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-6">
<div class="search-wrap text-center">
<h3 class="mb-3"><?php echo $site_info['search_dataset'] ?><strong></strong></h3>
<form method="POST" action="<?php echo base_url()?>datasets">
<div class="input-group input-group-lg">
<input type="text" class="form-control" name="search" placeholder="<?php echo $site_info['search']?>" aria-label="Keywords" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-secondary" name="submit_search" type="submit"><?php echo $site_info['search']?></button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="dataset-wrap">
<div class="container">
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="hazard-tab" data-toggle="tab" href="#hazard" role="tab" aria-controls="hazard" aria-selected="true"><?php echo $site_info['cat_1'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" id="exposure-tab" data-toggle="tab" href="#exposure" role="tab" aria-controls="exposure" aria-selected="false"><?php echo $site_info['cat_2'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" id="baseline-tab" data-toggle="tab" href="#baseline" role="tab" aria-controls="baseline" aria-selected="false"><?php echo $site_info['cat_3'] ?></a>
</li>
</ul>
<div class="tab-content scrolling-wrap" style="height: 280px;" id="myTabContent">
<div class="tab-pane fade show active" id="hazard" role="tabpanel" aria-labelledby="hazard-tab">
<div class="container-fluid">
<ul class="row">
<?php foreach($exposure_data as $data){ ?>
<li class="col-md-3 col-lg-2">
<a href="<?php echo base_url()?>category?tbl=<?php echo $data['category_table'] ?> && name=<?php echo $data['category_name'] ?> " class="dataset-item-wrap margin-top-large" data-mh="eq-item">
<img src="<?php echo $data['category_photo'] ?>">
<h6><?php echo $data['category_name'] ?></h6>
<span class="count"><?php
if(!$this->db->table_exists($data['category_table'])){
echo 0;
}else{
echo $data_count_cat[$data['category_table']];
}
?></span>
</a>
</li>
<?php } ?>
</ul>
</div>
</div>
<div class="tab-pane fade" id="exposure" role="tabpanel" aria-labelledby="exposure-tab">
<ul class="row">
<?php foreach($hazard_data as $data){ ?>
<li class="col-md-3 col-lg-2">
<a href="<?php echo base_url()?>category?tbl=<?php echo $data['category_table'] ?> && name=<?php echo $data['category_name'] ?> " class="dataset-item-wrap margin-top-large" data-mh="eq-item">
<img src="<?php echo $data['category_photo'] ?>">
<h6><?php echo $data['category_name'] ?></h6>
<span class="count"><?php
if(!$this->db->table_exists($data['category_table'])){
echo 0;
}else{
echo $data_count_cat[$data['category_table']];
}
?></span>
</a>
</li>
<?php }?>
</ul>
</div>
<div class="tab-pane fade" id="baseline" role="tabpanel" aria-labelledby="baseline-tab">
<ul class="row">
<?php foreach($baseline_data as $data){ ?>
<li class="col-md-3 col-lg-2">
<a href="<?php echo base_url()?>category?tbl=<?php echo $data['category_table']?>&&name=<?php echo $data['category_name'] ?>" class="dataset-item-wrap margin-top-large" data-mh="eq-item">
<img src="<?php echo $data['category_photo'] ?>">
<h6><?php echo $data['category_name'] ?></h6>
<span class="count"><?php
if(!$this->db->table_exists($data['category_table'])){
echo 0;
}else{
echo $data_count_cat[$data['category_table']];
}
?></span>
</a>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
<?php if($feat_lang=='en'){ ?>
<a href="category?tbl=<?php echo $feature['table'] ?>">
<div class="bg-white feature-section">
<div class="container">
<div class="featured-post clearfix">
<h5 class="post-ribbon">Featured Dataset</h5>
<img src="<?php echo $feature['photo'] ?>" alt="">
<h3><?php echo $feature['title'] ?></h3>
<p>
<?php echo $feature['summary'] ?>
</p>
</div>
</div>
</div>
</a>
<?php }else{ ?>
<a href="category?tbl=<?php echo $feature['table'] ?>">
<div class="bg-white feature-section">
<div class="container">
<div class="featured-post clearfix">
<h5 class="post-ribbon">विशेष डाटासेट</h5>
<img src="<?php echo $feature['photo'] ?>" alt="">
<h3><a href="#" title=""><?php echo $feature['nepali_title'] ?></a></h3>
<p>
<?php echo $feature['nepali_summary'] ?>
</p>
<!-- <a href="#" title="" class="btn btn-primary">पुरा पढ्नुहोस्</a> -->
</div>
</div>
</div>
</a>
<?php } ?>
<script type="text/javascript">
$("#started").click(function() {
$('html, body').animate({
scrollTop: $("#nextDiv").offset().top
}, 1000);
});
$(document).ready(function(){
if ($.fn.niceScroll) {
$(".scrolling-wrap").niceScroll({
cursorcolor: "#2057af",
cursorborder: "0px solid #fff",
cursorborderradius: "0px",
cursorwidth: "8px"
});
$(".scrolling-wrap").getNiceScroll().resize();
$(".scrolling-wrap").getNiceScroll().show();
}
});
</script>
<file_sep>/application/views/footer.php
<style type="text/css">
label > input{ /* HIDE RADIO */
visibility: hidden; /* Makes input not-clickable */
position: absolute; /* Remove input from document flow */
}
label > input + img{ /* IMAGE STYLES */
cursor:pointer;
border:2px solid transparent;
}
label > input:checked + img{ /* (RADIO CHECKED) IMAGE STYLES */
border:2px solid #f00;
}
div#exampleModal {
overflow: hidden;
}
button.btn.btn-secondary {
z-index: 0;
}
</style>
<footer id="website-footer" class="bg-dark">
<div class="subscribe-wrap">
<div class="container">
<div class="row clearfix">
<div class="col-md-4">
<div class="fbox">
<h4><?php echo $site_info['footer_big'] ?></h4>
<p>
<?php echo $site_info['footer_small'] ?> <!-- <a href="<?php echo base_url()?>about" title="" class="btn btn-outline-light btn-sm">थप</a> -->
</p>
</div>
</div>
<div class="col-md-4">
<div class="fbox">
<h4><?php echo $site_info['subscribe'] ?></h4>
<form action="" method="">
<div class="input-group">
<input type="email" class="form-control" name="email" placeholder="<?php echo $site_info['email'] ?>" aria-label="Email Address" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-secondary" name="submit" type="submit" data-toggle="modal" data-target="#exampleModal"><?php echo $site_info['subscribe_btn'] ?></button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel" style="color: #111">Subscribe</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="margin-left: 25px;">
<div class="row">
<div class="col-md-6">
<form>
<label>
<input id="fb3" type="radio" name="fb" value="med" />
<img src="<?php echo base_url();?>assets/img/dataset.png" alt="Logo" height="90" >
<p class="text-center" style="color: #111"> Datasets</p>
</label>
</div>
<div class="col-md-6">
<label>
<input id="fb3" type="radio" name="fb" value="med" />
<img src="<?php echo base_url();?>assets/img/dataset.png" alt="Logo" height="90">
<p class="text-center" style="color: #111"> Maps</p>
</label>
</div>
<div class="col-md-6">
<label>
<input id="fb3" type="radio" name="fb" value="med" />
<img src="<?php echo base_url();?>assets/img/dataset.png" alt="Logo" height="90">
<p class="text-center" style="color: #111"> Publications</p>
</label>
</div>
<div class="col-md-6">
<label>
<input id="fb3" type="radio" name="fb" value="med" />
<img src="<?php echo base_url();?>assets/img/dataset.png" alt="Logo" height="90">
<p class="text-center" style="color: #111">Contact</p>
</label>
</div>
<div class="all-select" style="color: #111">
<input type="radio" name="allselect"> Subscribe All
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Subscribe</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-4">
<div class="fbox">
<h4><?php echo $site_info['imp_link'] ?></h4>
<ul class="list-group">
<li><i class="la la-caret-right"></i><a href="<?php echo $site_info['1_link'] ?>" target="_blank"><?php echo $site_info['1_name'] ?></a></li>
<li><i class="la la-caret-right"></i><a href="<?php echo $site_info['2_link'] ?>" target="_blank"><?php echo $site_info['2_name'] ?></a></li>
<!-- <li><i class="la la-caret-right"></i><a href="<?php echo $site_info['3_link'] ?>" target="_blank"><?php echo $site_info['3_name'] ?></a></li>
<li><i class="la la-caret-right"></i><a href="<?php echo $site_info['4_link'] ?>" target="_blank"><?php echo $site_info['4_name'] ?></a></li>
<li><i class="la la-caret-right"></i><a href="<?php echo $site_info['5_link'] ?>" target="_blank"><?php echo $site_info['5_name'] ?></a></li> -->
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="footer-bottom">
<div class="container">
<div class="row">
<div class="col-md-6 sec-left">
<p class="margin-top">
© <?php echo $site_info['copy_date'] ?> <a href="#" title=""></a><?php echo $site_info['copy_text'] ?>
<!-- <a href="#" title="">हाम्रो बारेमा</a>
<a href="#" title="">संपर्क</a>
<a href="#" title="">प्रयोगका शर्तहरू</a>
<a href="#" title="">गोपनीयता नीति</a> -->
</p>
</div>
<div class="col-md-6 sec-right">
<p class="margin-top social-icons">
<a href="<?php echo $site_info['facebook'] ?>" title=""><i class="fa fa-facebook"></i></a>
<a href="<?php echo $site_info['twitter'] ?>" title=""><i class="fa fa-twitter"></i></a>
<a href="<?php echo $site_info['google'] ?>" title=""><i class="fa fa-google-plus"></i></a>
</p>
</div>
</div>
</div>
</div>
</footer>
<!-- <script src="https://code.jquery.com/jquery-3.3.1.js"></script> -->
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
document.getElementById('contents').style.visibility="hidden";
} else if (state == 'complete') {
setTimeout(function(){
document.getElementById('interactive');
document.getElementById('load').style.visibility="hidden";
document.getElementById('website-header').style.visibility="visible";
},1000);
}
}
</script>
<!--counter-->
<script type="text/javascript">
$(document).ready(function() {
$('#hydropower').DataTable({
dom: 'Bfrtip',
});
} );
// $('.count').each(function () {
// $(this).prop('Counter',0).animate({
// Counter: $(this).text()
// }, {
// duration: 4000,
// easing: 'swing',
// step: function (now) {
// $(this).text(Math.ceil(now));
// }
// });
// });
</script>
</body>
</html>
<file_sep>/application/controllers/Admin/FeatureDataset.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class FeatureDataset extends CI_Controller
{
function __construct()
{
parent::__construct();
if(($this->session->userdata('logged_in'))!=TRUE)
{
redirect('admin');
}else{
}
$this->load->dbforge();
$this->load->helper('url');
$this->load->model('Feature_model');
}
//english feature dataset start
public function feature()
{
if(isset($_POST['submit_feature']))
{
$d=array(
"default"=>0,
);
$this->Feature_model->update_default($d);
$id=$this->input->post('default');
$data=array(
"default"=>1,
);
$update=$this->Feature_model->update_map_download($id,$data,'featured_dataset');
$this->session->set_flashdata('msg','Featured Dataset Changed');
redirect('feature');
//var_dump($_POST);
}elseif(isset($_POST['submit']))
{
$id=$this->input->post('id');
$file_name = $_FILES['map_pic']['name'];
//$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$img_upload=$this->Feature_model->do_upload($file_name,$id);
if($img_upload != " "){
$ext=$img_upload['upload_data']['file_ext'];
$image_path=base_url() . 'uploads/datasets/'.$id.$ext ;
$data=array(
'photo'=>$image_path
);
$update=$this->Feature_model->update_map_download($id,$data,'featured_dataset');
$this->session->set_flashdata('msgg','successfully Photo Changed');
redirect('feature');
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msgg', $code);
redirect('feature');
}
}else{
$this->body['data']=$this->Feature_model->get_feature();
//var_dump($this->body['data']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/feature_dataset',$this->body);
$this->load->view('admin/footer');
}
}
public function add_feature()
{
if(isset($_POST['submit'])){
unset($_POST['submit']);
unset($_POST['map_pic']);
//var_dump($_POST);
$d=array(
"default"=>0,
);
$_POST['lang']= 'en';
$this->Feature_model->update_default($d);
$insert=$this->Feature_model->insert_feature_download($_POST);
if($insert!=""){
$file_name = $_FILES['map_pic']['name'];
// $ext = pathinfo($file_name, PATHINFO_EXTENSION);
$img_upload=$this->Feature_model->do_upload($file_name,$insert);
if($img_upload != ""){
$ext=$img_upload['upload_data']['file_ext'];
$image_path=base_url() . 'uploads/datasets/'.$insert.$ext ;
$data=array(
'photo'=>$image_path
);
$update=$this->Feature_model->update_map_download($insert,$data,'featured_dataset');
$this->session->set_flashdata('msgg','Dataset Added successfully');
redirect('feature');
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msgg', $code);
redirect('feature');
}
}else{
//db error
}
}else{
$this->body['cat']=$this->Feature_model->get_tables_data('categories_tbl');
// var_dump($this->body['cat']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/add_feature',$this->body);
$this->load->view('admin/footer');
}
}
public function delete_feature(){
$id = $this->input->get('id');
$delete=$this->Feature_model->delete_map($id);
$this->session->set_flashdata('msgg','Id number '.$id.' row data was deleted successfully');
redirect('feature');
}
public function edit_feature()
{
if(isset($_POST['submit'])){
unset($_POST['submit']);
var_dump($_POST);
$tbl='featured_dataset';
$update=$this->Feature_model->update_map_download($this->input->post('id'),$_POST,$tbl);
if($update){
$this->session->set_flashdata('msgg','Updated successfully');
redirect('feature');
}else{
//db error
}
}else{
$this->body['e_data']=$this->Feature_model->e_data_map(base64_decode($this->input->get('id')));
$this->body['cat']=$this->Feature_model->get_tables_data('categories_tbl');
//echo base64_decode($this->input->get('id'));
var_dump($this->body['e_data']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/edit_feature',$this->body);
$this->load->view('admin/footer');
}
}
public function select_feature()
{
$this->body['data']=$this->Feature_model->get_feature();
}
//end feature dataset
//nepali featuredataset start
public function feature_nep()
{
if(isset($_POST['submit_feature']))
{
$d=array(
"default_nep"=>0,
);
$this->Feature_model->update_default($d);
$id=$this->input->post('default_nep');
$data=array(
"default_nep"=>1,
);
$update=$this->Feature_model->update_map_download($id,$data,'featured_dataset');
$this->session->set_flashdata('msg','Featured Dataset Changed');
redirect('feature_nep');
//var_dump($_POST);
}elseif(isset($_POST['submit']))
{
$id=$this->input->post('id');
$file_name = $_FILES['map_pic']['name'];
//$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$img_upload=$this->Feature_model->do_upload($file_name,$id);
if($img_upload != " "){
$ext=$img_upload['upload_data']['file_ext'];
$image_path=base_url() . 'uploads/datasets/'.$id.$ext ;
$data=array(
'photo'=>$image_path
);
$update=$this->Feature_model->update_map_download($id,$data,'featured_dataset');
$this->session->set_flashdata('msgg','successfully Photo Changed');
redirect('feature_nep');
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msgg', $code);
redirect('feature_nep');
}
}else{
$this->body['data']=$this->Feature_model->get_feature_nep();
//var_dump($this->body['data']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/feature_dataset_nep',$this->body);
$this->load->view('admin/footer');
}
}
public function add_feature_nep()
{
if(isset($_POST['submit'])){
unset($_POST['submit']);
unset($_POST['map_pic']);
//var_dump($_POST);
$d=array(
"default_nep"=>0,
);
$_POST['lang']= 'nep';
$this->Feature_model->update_default($d);
$insert=$this->Feature_model->insert_feature_download($_POST);
if($insert!=""){
$file_name = $_FILES['map_pic']['name'];
// $ext = pathinfo($file_name, PATHINFO_EXTENSION);
$img_upload=$this->Feature_model->do_upload($file_name,$insert);
if($img_upload != ""){
$ext=$img_upload['upload_data']['file_ext'];
$image_path=base_url() . 'uploads/datasets/'.$insert.$ext ;
$data=array(
'photo'=>$image_path
);
$update=$this->Feature_model->update_map_download($insert,$data,'featured_dataset');
$this->session->set_flashdata('msgg','Dataset Added successfully');
redirect('feature_nep');
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msgg', $code);
redirect('feature_nep');
}
}else{
//db error
}
}else{
$this->body['cat']=$this->Feature_model->get_tables_data('categories_tbl');
// var_dump($this->body['cat']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/add_feature_nep',$this->body);
$this->load->view('admin/footer');
}
}
public function edit_feature_nep()
{
if(isset($_POST['submit'])){
unset($_POST['submit']);
// var_dump($_POST);
$tbl='featured_dataset';
$update=$this->Feature_model->update_map_download($this->input->post('id'),$_POST,$tbl);
if($update){
$this->session->set_flashdata('msgg','Updated successfully');
redirect('feature_nep');
}else{
//db error
}
}else{
$this->body['e_data']=$this->Feature_model->e_data_map(base64_decode($this->input->get('id')));
$this->body['cat']=$this->Feature_model->get_tables_data('categories_tbl');
//echo base64_decode($this->input->get('id'));
// var_dump($this->body['e_data']);
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/edit_feature_nep',$this->body);
$this->load->view('admin/footer');
}
}
//end nepali feature dataset
}//end
<file_sep>/application/models/About_model.php
<?php
class About_model extends CI_Model {
public function get_about()
{
$this->db->select('*');
$q=$this->db->get('about');
return $q->result_array();
}
public function get_edit_Data($id,$table){
$this->db->select('*');
$this->db->where('id',$id);
$query=$this->db->get($table);
return $query->row_array();
}
public function update_data($id,$data){
$this->db->where('id',$id);
$q=$this->db->update('about',$data);
if($q){
return 1;
}else{
return 0;
}
}
public function do_upload($filename,$name)
{
$field_name ='proj_pic';
$config['upload_path'] = './uploads/about/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
return 1;
}
}
}
<file_sep>/application/views/admin/login.php
<!DOCTYPE html>
<html>
<body>
<?php
$error= $this->session->flashdata('Login');
if($error){
echo $error;
}
?>
<form action="" method="POST">
First name:<br>
<input type="text" name="username" required>
<br>
Last name:<br>
<input type="<PASSWORD>" name="password" required>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<file_sep>/application/views/admin/categories_edit.php
<!--main content start-->
<section id="main-content" class="">
<section class="wrapper">
<!-- page start-->
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
Change Category
</header>
<div class="panel-body">
<form class="form-horizontal bucket-form" method="post" action="" enctype="multipart/form-data">
<?php
for($i=0;$i<sizeof($fields);$i++){
if($fields[$i]=='id'){
?>
<input type="hidden" value="<?php echo $edit_data[$fields[$i]];?>" name="id">
<?php }else{
?>
<?php if($fields[$i]=='category_name' || $fields[$i]=='category_type' || $fields[$i]=='category_photo'){ ?>
<?php if($fields[$i]=='category_type'){ ?>
<div class="form-group">
<label class="col-sm-3 control-label"><?php echo ucwords(str_replace("_"," ",$fields[$i]));?></label>
<div class="col-sm-6">
<select name="<?php echo $fields[$i];?>" >
<option value="<?php echo $edit_data[$fields[$i]]; ?>"><?php echo str_replace("_"," ",$edit_data[$fields[$i]])?></option>
<option value="Hazard_Data">Hazard Data</option>
<option value="Exposure_Data">Resource Data</option>
<option value="Baseline_Data">Baseline Data</option>
</select>
</div>
</div>
<?php }elseif($fields[$i]=='category_photo'){?>
<div class="form-group ">
<label class="control-label col-md-3"><?php echo ucwords(str_replace("_"," ",$fields[$i]));?></label>
<div class="col-md-9">
<br>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;">
<img src="<?php echo $edit_data[$fields[$i]]; ?>" alt="" />
</div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>
<div>
<span class="btn btn-white btn-file">
<span class="fileupload-new"><i class="fa fa-paper-clip"></i> Select image</span>
<span class="fileupload-exists"><i class="fa fa-undo"></i> Change</span>
<input type="file" name="cat_pic" class="default" />
</span>
</div>
</div>
</div>
</div>
</div>
<?php }else{ ?>
<div class="form-group">
<label class="col-sm-3 control-label"><?php echo ucwords(str_replace("_"," ",$fields[$i]));?></label>
<div class="col-sm-6">
<input type="text" value="<?php echo $edit_data[$fields[$i]]; ?>" name="<?php echo $fields[$i];?>" class="form-control round-input">
</div>
</div>
<?php }}}}?>
<div class="col-md-6">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/views/report_pages.php
<link href="sitemapstyler/sitemapstyler.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="sitemapstyler/sitemapstyler.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<!--<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-ajax/2.1.0/leaflet.ajax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/randomcolor/0.5.2/randomColor.js"></script>
<!-- date -->
<style>
.leaflet-left .leaflet-control {
margin-left: 1300;
margin-bottom: 10;
}
.leaflet-top .leaflet-control {
margin-top: 26px;
}
button.layer-toggle {
margin-top: 250px;
background: #668bb1;
border-color: transparent;
border-radius: 0px;
outline: none;
position: relative;
z-index: 999;
}
body {
font-size: 0.8em !important;
font-weight: 400;
line-height: 1.5;
text-align: left;
background-color: #fff;}
label{margin-left: 20px;}
#datepicker{width:180px; margin: 0 20px 20px 20px;}
#datepicker > span:hover{cursor: pointer;}
</style>
<div id="wrapper">
<!--sub-menu-->
<div class="icon-bar icon">
<a class="active" href="mapt.php"><i class="fa fa-map"></i> Maps</a>
<a href="#"><i class="fa fa-database"></i> Data</a>
</div>
<!--ends sub-menu-->
<div id="map" style="width:100%; height:550px; z-index: 4; margin-top:0px;">
</div>
<div id="over_map" style ="margin-top: 36px;">
<div class="panel panel-danger">
<!-- search -->
<form action="" method="POST">
<label><b> Date : </b></label>
<div class="row">
<!-- Include Bootstrap Datepicker -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.min.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker3.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.min.js"></script>
<div class="col-md-6 date">
<div class="input-group input-append date" id="datePicker1">
<input type="text" class="form-control" name="from_date" placeholder="From" />
<span class="input-group-addon add-on"><span class="fa fa-calendar repo" style="font-size: 14px;"> </span></span>
</div>
</div>
<div class="col-md-6 date">
<div class="input-group input-append date" id="datePicker2">
<input type="text" class="form-control" name="to_date" placeholder="To" />
<span class="input-group-addon add-on"><span class="fa fa-calendar repo" style="font-size: 14px;"> </span></span>
</div>
</div>
</div>
<!-- search -->
<div class="form-group" style="margin-top: 8px;">
<select name="category" class="form-control" id="exampleSelect1">
<option value="0">Select Categories</option>
<option value="fire">1</option>
<option value="water">2</option>
<option value="earth">3</option>
</select>
</div>
<div class="text-center">
<button class="btn btn-success btn-sm text-center" type="submit" name="submit" style="margin-top: 0px;">Apply</button>
</div>
</form>
</div>
<!-- left report Data -->
<div class="panel panel-default report">
<div class="panel-body problem">
<?php foreach($report_data as $data){ ?>
<div class="row problem report_div" value="<?php echo $data['latitude'] ;?>" name="<?php echo $data['longitude'] ;?>" >
<div class="col-sm-4"><img src="./assets/img/help.png" class="problems"></div>
<div class="col-sm-8"><span class="ttl"><?php echo $data['incident_type'] ;?></span>
<p><?php echo $data['message'] ;?></p>
</div>
<hr style="width: 100%; margin-top: 0px;">
<p class="men text-center">Category: <?php echo $data['incident_type'] ;?> | Status: problem | 2 hours ago | Sender: <?php echo $data['name'] ?></p>
</div>
<?php } ?>
<br>
<br>
<br>
<br>
</div>
</div></div></div>
<!-- report data -->
</div>
<script>
var report = '<?php echo $report_map_layer ;?>';
report_layer = JSON.parse(report);
//console.log(report_layer);
/*-- LayerJS--*/
$(document).ready(function(){
$(".layer-toggle").click(function(){
$(".panel.panel-success").toggle(800);
$(".layer-toggle i").toggleClass("fa-chevron-right");
});
//map part
var map = L.map('map');//.setView([27.7005033, 85.4328162], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);
$(".layer-toggle").click(function(){
$(".panel.panel-success").toggle(1000);
$(".layer-toggle i").toggleClass("fa-chevron-right");
});
var sankhu = new L.geoJson.ajax("http://localhost/vos/geojson/Shankharapur.geojson", {
onEachFeature: function(feature,layer){
layer.on('click', function() {
map.fitBounds(layer.getBounds());
});
layer.setStyle({
fillColor:"Green",
fillOpacity:0,
weight: 1,
opacity: 1,
color: 'black',
//dashArray: '3'
});
}
}).addTo(map);
sankhu.on('data:loaded', function (data) {
map.fitBounds(sankhu.getBounds());
});
var report_map = new L.GeoJSON(report_layer, {
pointToLayer: function(feature, latlng) {
icons = L.icon({
//iconSize: [27, 27],
iconAnchor: [13, 27],
popupAnchor: [2, -24],
iconUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon.png'
});
//console.log(icon.options);
var marker = L.marker(latlng, {icon: icons});
return marker;
},
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.name);
//feature.properties.layer_name = "transit_stops";
}
});
report_map.on('data:loaded', function (data) {
});
report_map.addTo(map);
//filter start
$('.report_div').click(function(){
var long =$(this).attr("name");
var lat =$(this).attr("value");
console.log(typeof lat);
console.log(long);
map.setView([parseFloat(lat),parseFloat(long)], 18);
//$.ajax({
// url: 'ReportController/search?data='+srch,
// success: function(response) {
//alert(response);
//var srchd= JSON.parse(response);
// alert(response);
// map.removeLayer(report_map);s
// single_report=JSON.parse(response);
//
// console.log(parseFloat(single_report.features.geometry.coordinates[0]));
// var single_map = new L.GeoJSON(single_report, {
// pointToLayer: function(feature, latlng) {
// icons = L.icon({
// //iconSize: [27, 27],
// iconAnchor: [13, 27],
// popupAnchor: [2, -24],
// iconUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon.png'
// });
// //console.log(icon.options);
// var marker = L.marker(latlng, {icon: icons});
// return marker;
//
// },
// onEachFeature: function(feature, layer) {
// layer.bindPopup(feature.properties.name);
// //feature.properties.layer_name = "transit_stops";
//
// }
// });
// single_map.on('data:loaded', function (data) {
//
// map.addLayer(single_map);
//
//
// });
//map.setView(parseFloat(single_report.features.geometry.coordinates[1]),parseFloat(single_report.features.geometry.coordinates[0]), 18);
//}
//});
});
//filter end
}); //document --ends
</script>
<script type="text/javascript">
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
document.getElementById('contents').style.visibility="hidden";
} else if (state == 'complete') {
setTimeout(function(){
document.getElementById('interactive');
document.getElementById('load').style.visibility="hidden";
document.getElementById('contents').style.visibility="visible";
},1000);
}
}
</script>
<script>
$(document).ready(function() {
$('#datePicker1')
.datepicker({
format: 'mm/dd/yyyy'
})
$('#datePicker2')
.datepicker({
format: 'mm/dd/yyyy'
});
});
</script>
<file_sep>/application/views/map/map.php
<div id="wrapper">
<div id="map" style="width:100%; height:600px; margin-top:0px;"> </div></div>
<script>
var layer_array = '<?php echo $layer_name; ?>';
var geo_array = '<?php echo $geo; ?>';
//
var cat_layer = '<?php echo $cat_map_layer; ?>';
var cat_tbl_array = '<?php echo $category_tbl; ?>';
//
layer_name = JSON.parse(layer_array);
geojson = JSON.parse(geo_array);
cat_layer_data = JSON.parse(cat_layer);
cat_tbl_array_name = JSON.parse(cat_tbl_array);
//console.log(nep);
// console.log(layer_name);
//console.log(cat_layer);
$(document).ready(function(){
var map = L.map('map').setView([27.693547,85.440240], 13);
// map.scrollWheelZoom.disable();
map.options.maxBounds; // remove the maxBounds object from the map options
//map.options.minZoom = 9;
//map.options.minZoom = 14;
//console.log("adfasfsadfasfasdfasfdasdfsafasdfsafasfasfsafsa");
var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
});
googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
googleHybrid = L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
googleTerrain = L.tileLayer('http://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
//var none = "";
var baseLayers = {
"OpenStreetMap": osm,
"Google Streets": googleStreets,
"Google Hybrid": googleHybrid,
"Google Satellite": googleSat,
"Google Terrain": googleTerrain//,
//"None": none
};
map.addLayer(googleStreets);
layerswitcher = L.control.layers(baseLayers, {}, {collapsed: true}).addTo(map);
function underscoreToSpace(naaaaame) {
var underscored = naaaaame;
var spaced = underscored.replace(/_/g, " ");
return spaced;
}
for(i=0; i<layer_name.length; i++){
window[''+layer_name[i]] = new L.GeoJSON(geojson[i],
{
// pointToLayer: function(feature,Latlng)
// {
// icons=L.icon({
// iconUrl: "https://unpkg.com/[email protected]/dist/images/marker-icon.png"
// });
// var marker = L.marker(Latlng,{icon: icons});
//
// },
// with onEachFeature the task is carried out on Each of the point of coordinates or other properties Like( Creating table in each point of cordinates and etc)
onEachFeature: function(feature,layer){
layer.on('click',function() {
map.fitBounds(layer.getBounds());
});
var popUpContent = "";
popUpContent += '<table style="width:100%;" id="District-popup" class="popuptable">';
for (data in layer.feature.properties) {
// console.log('feature ', feature);
dataspaced = underscoreToSpace(data);
popUpContent += "<tr>" + "<td></td>" + "<td>" + " " + layer.feature.properties[data] + "</td>" + "</tr>";
}
popUpContent += '</table>';
layer.bindPopup(L.popup({
closeOnClick: true,
closeButton: true,
keepInView: true,
autoPan: true,
maxHeight: 200,
minWidth: 250
}).setContent(popUpContent));
layer.setStyle({
fillColor: randomColor(),
fillOpacity:0,
weight: 0.5,
opacity: 1,
color: 'black'//,
//dashArray: '3'
});
// table is created to put all the data of the database into the marker on one click
//slayer.bindLabel('sdfsaas');
// console.log(feature);
}
}).addTo(map);
}
//cat map load
for(i=0; i<cat_tbl_array_name.length; i++){
console.log(cat_tbl_array_name[i]);
window[''+cat_tbl_array_name[i]]= new L.GeoJSON(cat_layer_data[i],
{
pointToLayer: function(feature,Latlng)
{
icons=L.icon({
iconUrl: "https://unpkg.com/[email protected]/dist/images/marker-icon.png"
});
var marker = L.marker(Latlng,{icon: icons});
return marker;
},
onEachFeature: function(feature,layer){
var popUpContent = "";
popUpContent += '<table style="width:100%;" id="District-popup" class="popuptable">';
for (data in layer.feature.properties) {
console.log(feature);
// console.log('feature ', feature);
dataspaced = underscoreToSpace(data);
popUpContent += "<tr>" + "<td></td>" + "<td>" + " " + layer.feature.properties[data] + "</td>" + "</tr>";
}
popUpContent += '</table>';
layer.bindPopup(L.popup({
closeOnClick: true,
closeButton: true,
keepInView: true,
autoPan: true,
maxHeight: 200,
minWidth: 250
}).setContent(popUpContent));
},
}).addTo(map);
}
//cat map end
$( ".CheckBox" ).click(function( event ) {
layerClicked = window[event.target.value];
//console.log(layerClicked);
if (map.hasLayer(layerClicked)) {
map.removeLayer(layerClicked);
}
else{
map.addLayer(layerClicked);
} ;
});
$( ".CheckBoxStart" ).click(function( event ) {
layerClicked1 = window[event.target.value];
map.addLayer(layerClicked1);
map.removeLayer(layerClicked1)
});
L.Mask = L.Polygon.extend({
options: {
stroke: false,
color: '#333',
fillOpacity: 0.5,
clickable: true,
outerBounds: new L.LatLngBounds([-90, -360], [90, 360])
},
initialize: function (latLngs, options) {
var outerBoundsLatLngs = [
this.options.outerBounds.getSouthWest(),
this.options.outerBounds.getNorthWest(),
this.options.outerBounds.getNorthEast(),
this.options.outerBounds.getSouthEast()
];
L.Polygon.prototype.initialize.call(this, [outerBoundsLatLngs, latLngs], options);
},
});
L.mask = function (latLngs, options) {
return new L.Mask(latLngs, options);
};
var coordinates = changu1[0].features[0].geometry.coordinates[0];
var latLngs = [];
for (i=0; i<coordinates.length; i++) {
for(j=0; j<coordinates[i].length;j++){
// console.log(coordinates[i][j]);
latLngs.push(new L.LatLng(coordinates[i][j][1], coordinates[i][j][0]));
}
}
L.mask(latLngs).addTo(map);
});//document
</script>
<file_sep>/application/models/Main_model.php
<?php
class Main_model extends CI_Model {
public function get_feature()
{
$this->db->select('*');
$this->db->where('lang','en');
$this->db->where('default','1');
$q=$this->db->get('featured_dataset');
return $q->row_array();
}
public function get_feature_nep()
{
$this->db->select('*');
$this->db->where('lang','nep');
$this->db->where('default_nep','1');
$q=$this->db->get('featured_dataset');
return $q->row_array();
}
public function get_checked_dataset($data)
{
$this->db->select('*');
$this->db->or_where_in('category_table',$data);
$q=$this->db->get('categories_tbl');
return $q->result_array();
}
public function site_setting_en(){
$this->db->select('*');
$this->db->where('id',1);
$q=$this->db->get('site_setting');
return $q->row_array();
}
public function site_setting_nep(){
$this->db->select('*');
$this->db->where('id',2);
$q=$this->db->get('site_setting');
return $q->row_array();
}
public function get_post(){
$this->db->select('*');
$this->db->select('St_asText(geom)');
$query=$this->db->get('crops_2015');
return $query->result();
}
public function get_contact($cat,$tbl,$lang)
{
$this->db->select('*');
$this->db->where('language',$lang);
$this->db->where('category',$cat);
$q=$this->db->get($tbl);
return $q->result_array();
}
public function get_contact_csv($cat,$tbl)
{
$this->db->select('*');
$this->db->where('category',$cat);
$q=$this->db->get($tbl);
return $q ;
}
public function get_about_where($id)
{
$this->db->select('*');
$this->db->where('id',$id);
$q=$this->db->get('about');
return $q->row_array();
}
public function get_category(){
$this->db->select('*');
$this->db->where('language','en');
$q=$this->db->get('categories_tbl');
return $q->result_array();
}
public function count_dat_tbl($tbl){
$this->db->select('COUNT(*) as '.$tbl);
$this->db->distinct();
$result_set=$this->db->get($tbl);
return $result_set->row_array();
}
public function get_category_nep(){
$this->db->select('*');
$this->db->where('language','nep');
$q=$this->db->get('categories_tbl');
return $q->result_array();
}
public function insert($udata,$table){
$this->db->insert($table, $udata);
}
public function get($tbl){
$this->db->select('*');
$query=$this->db->get($tbl);
return $query->result_array();
}
public function get_proj_data(){
$this->db->select('*');
$query=$this->db->get('project_tbl');
return $query->result_array();
}
public function get_cat($tbl){
$this->db->select('*');
$this->db->order_by('id','ASC');
$query=$this->db->get($tbl);
return $query->result_array();
}
public function get_cat_exposure($tbl,$lang){
$this->db->select('*');
$this->db->where('language',$lang);
$this->db->where('category_type','Exposure_Data');
$this->db->order_by('id','ASC');
$query=$this->db->get($tbl);
return $query->result_array();
}
public function get_cat_baseline($tbl,$lang){
$this->db->select('*');
$this->db->where('language',$lang);
$this->db->where('category_type','Baseline_Data');
$this->db->order_by('id','ASC');
$query=$this->db->get($tbl);
return $query->result_array();
}
public function get_cat_hazard($tbl,$lang){
$this->db->select('*');
$this->db->where('language',$lang);
$this->db->where('category_type','Hazard_Data');
$this->db->order_by('id','ASC');
$query=$this->db->get($tbl);
return $query->result_array();
}
}
<file_sep>/application/models/Admin_dash_model.php
<?php
class Admin_dash_model extends CI_Model {
public function count_data($tbl){
return $this->db->count_all_results($tbl);
}
public function count_views($field){
$this->db->select('*');
$this->db->where('page',$field);
$q=$this->db->get('views');
return $q->row_array();
}
public function max_views(){
$this->db->select('*');
$this->db->order_by('views_count','DESC');
$this->db->limit(1);
$query=$this->db->get('views');
return $query->row_array();
}
}
<file_sep>/application/models/Project_model.php
<?php
class Project_model extends CI_Model {
public function add_proj($table,$data){
$this->db->insert($table,$data);
if ($this->db->affected_rows() > 0)
{
return $this->db->insert_id();
}
else
{
$error = $this->db->error();
return $error;
}
}
public function get_proj($tbl){
$this->db->select('*');
$this->db->order_by('id','ASC');
$query=$this->db->get($tbl);
return $query->result_array();
}
public function do_upload($filename,$name)
{
$field_name ='proj_pic';
$config['upload_path'] = './uploads/project_partner/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function get_edit_Data($id,$table){
$this->db->select('*');
$this->db->where('id',$id);
$query=$this->db->get($table);
return $query->row_array();
}
public function update_data($id,$data){
$this->db->where('id',$id);
$q=$this->db->update('project_tbl',$data);
if($q){
return 1;
}else{
return 0;
}
}
}
<file_sep>/application/controllers/NewsletterController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class NewsletterController extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('Newsletter');
}
public function register(){
var_dump($this->input->post('email'));
$data=array(
'email'=>$this->input->post('email'),
);
$insert=$this->Newsletter->register($data);
if($insert!=""){
redirect('main');
}
}
public function mail()
{
$this->Newsletter->send_mail('Newsletter');
}
//mapdownload code
public function download(){
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$id=$this->input->get('id');
$n=$this->input->get('name');
$name=$n.'.jpg';
$data=file_get_contents('uploads/map_download/'.$id.'.jpg');
force_download($name,$data);
//echo $id;
}
//end
public function get_category_pub(){
$cat=$this->input->get('cat');
$tbl='publication';
//$cat='muni_pub';
if ($cat=='0') {
$pub_fil=$this->Newsletter->get_pub_all($tbl);
} else {
$pub_fil=$this->Newsletter->get_pub_filter($cat,$tbl);
}
echo json_encode($pub_fil);
}
public function get_category_mapdownload(){
$cat=$this->input->get('cat');
$tbl='maps_download';
//$cat='muni_pub';
if ($cat=='0') {
$pub_fil=$this->Newsletter->get_pub_all($tbl);
} else {
$pub_fil=$this->Newsletter->get_pub_filter($cat,$tbl);
}
echo json_encode($pub_fil);
}
}//end
<file_sep>/application/models/Feature_model.php
<?php
class Feature_model extends CI_Model {
public function get_feature()
{
$this->db->select('id,title,summary,photo,default');
$this->db->where('lang','en');
$q=$this->db->get('featured_dataset');
return $q->result_array();
}
public function get_feature_nep()
{
$this->db->select('id,nepali_title,nepali_summary,photo,default_nep');
$this->db->where('lang','nep');
$q=$this->db->get('featured_dataset');
return $q->result_array();
}
public function update_default($value)
{
$this->db->update('featured_dataset',$value);
}
public function do_upload($filename,$name)
{
$field_name ='map_pic';
$config['upload_path'] = './uploads/datasets';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function insert_feature_download($data){
$this->db->insert('featured_dataset',$data);
if ($this->db->affected_rows() > 0)
{
return $this->db->insert_id();
}
else
{
$error = $this->db->error();
return $error;
}
}
public function update_map_download($id,$data,$tbl){
$this->db->where('id',$id);
return $this->db->update($tbl,$data);
}
public function delete_map($id)
{
$this->db->where('id',$id);
$this->db->delete('featured_dataset');
}
public function get_tables_data($tbl){ //get data of table
$this->db->select('*');
$this->db->order_by('id','ASC');
$q=$this->db->get($tbl);
return $q->result_array();
}
public function e_data_map($id){
$this->db->select('*');
$this->db->where('id',$id);
$query=$this->db->get('featured_dataset');
return $query->row_array();
}
}//end
<file_sep>/application/views/test_contact.php
<style>
.nav-tabs,
.nav-pills {
position: relative;
}
.tabdrop{
width: 120px;
margin-top: .5rem;
}
.nav-tabs li li i{
visibility: hidden;
}
.hide {
display: none;
}
.input-group-addon {
position: absolute;
right: 10px;
bottom: 13px;
z-index: 2;
}
.contact-search-1 {
padding: 50px;
border-bottom: 1px solid #eee;
padding-left: 0px;
}
.responstable th {
display: none;
border: 1px solid transparent;
background-color: lightslategray;
color: #FFF;
padding: 1em;
}
#reportable{
overflow: auto;
margin: 0em auto 3em;
}
.responstable {
margin: 1em 0em;
width: 100%;
overflow: hidden;
background: #FFF;
color: #000;
border-radius: 0px;
border: 1px solid #1f5cb2;
font-size: 16px;
}
.responstable tr {
border: 1px solid #D9E4E6;
}
.responstable tr:nth-child(odd) {
background-color: #EAF3F3;
}
.responstable th:first-child {
display: table-cell;
text-align: center;
}
.responstable th:nth-child(2) {
display: table-cell;
}
.responstable th:nth-child(2) span {
display: none;
}
.responstable th:nth-child(2):after {
content: attr(data-th);
}
@media (min-width: 480px) {
.responstable th:nth-child(2) span {
display: block;
}
.responstable th:nth-child(2):after {
display: none;
}
}
.responstable td {
display: block;
word-wrap: break-word;
max-width: 7em;
}
.responstable td:first-child {
display: table-cell;
text-align: center;
border-right: 1px solid #D9E4E6;
}
@media (min-width: 480px) {
.responstable td {
border: 1px solid #D9E4E6;
}
}
.responstable th, .responstable td {
text-align: left;
margin: .5em 1em;
}
@media (min-width: 480px) {
.responstable th, .responstable td {
display: table-cell;
padding: 0.3em;
}
}
.tabdrop .dropdown-menu a{
padding: 20px;
}
</style>
<!--advance Search starts-->
<div class="container ">
<div class="contact-search-1">
<div class="row">
<div class="col-sm-12 text-center">
<div class="row no-gutters">
<div class="col">
<input class="form-control border-secondary border-right-0 rounded-0" type="search" placeholder="Search For.." id="myInput" onkeyup="myFunction()">
</div>
<div class="col-auto">
<button class="btn btn-secondary border-left-0 rounded-0 rounded-right" type="button">
<i class="fa fa-search"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!--advance Search ends-->
<!-- table List -->
<div class="container" id="emergency_no">
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="health-tab" data-toggle="tab" href="#health" role="tab" aria-controls="health" aria-selected="true">Health Institutions</a>
</li>
<li class="nav-item">
<a class="nav-link" id="emergency-tab" data-toggle="tab" href="#emergency" role="tab" aria-controls="emergency" aria-selected="false">Emergency Responders</a>
</li>
<li class="nav-item">
<a class="nav-link" id="security-tab" data-toggle="tab" href="#security" role="tab" aria-controls="security" aria-selected="false">Security</a>
</li>
<li class="nav-item">
<a class="nav-link" id="ngo-tab" data-toggle="tab" href="#ngo" role="tab" aria-controls="ngo" aria-selected="false">NGOs and INGOs</a>
</li>
<li class="nav-item">
<a class="nav-link" id="volunter-tab" data-toggle="tab" href="#volunter" role="tab" aria-controls="volunter" aria-selected="false">DRR Volunteers</a>
</li>
<li class="nav-item">
<a class="nav-link" id="person-tab" data-toggle="tab" href="#person" role="tab" aria-controls="person" aria-selected="false">Municipality Personnel</a>
</li>
<li class="nav-item">
<a class="nav-link" id="member-tab" data-toggle="tab" href="#member" role="tab" aria-controls="member" aria-selected="false">Members of Municipal Assemblysss</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="health" role="tabpanel" aria-labelledby="health-tab">
<br>
<a href="get_csv_emergency?type=health&&name=Health_Institutions&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px; float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th data-th="Health Institutions"><span>Organization</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Alternate Phone No.</span></th>
<th><span>Contact Person</span></th>
<th><span>Post</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
<th><span>Website</span></th>
</tr>
<?php foreach ($health as $health) {
?>
<tr class="tr_tbl">
<td id="<?php echo $health['id'] ?>idhealth"><?php echo $health['id'] ?></td>
<td id="<?php echo $health['id'] ?>organizationhealth"><?php echo $health['organization'] ?></td>
<td id="<?php echo $health['id'] ?>addresshealth"><?php echo $health['address'] ?></td>
<td id="<?php echo $health['id'] ?>phone_nohealth"><?php echo $health['phone_no'] ?></td>
<td id="<?php echo $health['id'] ?>alternate_phone_nohealth"><?php echo $health['alternate_phone_no'] ?></td>
<td id="<?php echo $health['id'] ?>contact_personhealth"><?php echo $health['contact_person'] ?></td>
<td id="<?php echo $health['id'] ?>contact_personhealth"><?php echo $health['post'] ?></td>
<td id="<?php echo $health['id'] ?>personal_nohealth"><?php echo $health['personal_no'] ?></td>
<td id="<?php echo $health['id'] ?>emailhealth"><?php echo $health['email'] ?></td>
<td id="<?php echo $health['id'] ?>websitehealth"><?php echo $health['website'] ?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<div class="tab-pane fade show" id="emergency" role="tabpanel" aria-labelledby="emergency-tab">
<br>
<a href="get_csv_emergency?type=responders&&name=Emergency_Responders&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th data-th="Emergency Responders"><span>Organization</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Alternate Phone No.</span></th>
<th><span>Contact Person</span></th>
<th><span>Post</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
<th><span>Website</span></th>
</tr>
<?php foreach ($responders as $responders) {
// code...
?>
<tr class="tr_tbl">
<td id="<?php echo $responders['id'] ?>idresponders"><?php echo $responders['id'] ?></td>
<td id="<?php echo $responders['id'] ?>organizationresponders"><?php echo $responders['organization'] ?></td>
<td id="<?php echo $responders['id'] ?>addressresponders"><?php echo $responders['address'] ?></td>
<td id="<?php echo $responders['id'] ?>phone_noresponders"><?php echo $responders['phone_no'] ?></td>
<td id="<?php echo $responders['id'] ?>alternate_phone_noresponders"><?php echo $responders['alternate_phone_no'] ?></td>
<td id="<?php echo $responders['id'] ?>contact_personresponders"><?php echo $responders['contact_person'] ?></td>
<td id="<?php echo $responders['id'] ?>personal_noresponders"><?php echo $responders['personal_no'] ?></td>
<td id="<?php echo $responders['id'] ?>emailresponders"><?php echo $responders['email'] ?></td>
<td id="<?php echo $responders['id'] ?>websiteresponders"><?php echo $responders['website'] ?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<div class="tab-pane fade show" id="security" role="tabpanel" aria-labelledby="security-tab">
<br>
<a href="get_csv_emergency?type=security&&name=Security&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th data-th="Security"><span>Organization</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Alternate Phone No.</span></th>
<th><span>Contact Person</span></th>
<th><span>Post</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
<th><span>Website</span></th>
</tr>
<?php foreach ($security as $security) {
// code...
} ?>
<tr class="tr_tbl">
<td id="<?php echo $security['id'] ?>idSecurity"><?php echo $security['id'] ?></td>
<td id="<?php echo $security['id'] ?>organizationSecurity"><?php echo $security['organization'] ?></td>
<td id="<?php echo $security['id'] ?>addressSecurity"><?php echo $security['address'] ?></td>
<td id="<?php echo $security['id'] ?>phone_noSecurity"><?php echo $security['phone_no'] ?></td>
<td id="<?php echo $security['id'] ?>alternate_phone_noSecurity"><?php echo $security['alternate_phone_no'] ?></td>
<td id="<?php echo $security['id'] ?>contact_personSecurity"><?php echo $security['contact_person'] ?></td>
<td id="<?php echo $security['id'] ?>personal_noSecurity"><?php echo $security['personal_no'] ?></td>
<td id="<?php echo $security['id'] ?>emailSecurity"><?php echo $security['email'] ?></td>
<td id="<?php echo $security['id'] ?>websiteSecurity"><?php echo $security['website'] ?></td>
</tr>
</table>
</div>
</div>
<div class="tab-pane fade show" id="ngo" role="tabpanel" aria-labelledby="ngo-tab">
<br>
<a href="get_csv_emergency?type=ngo&&name=NGOs_INGOs&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th data-th="NGOs and INGOs"><span>Organization</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Alternate Phone No.</span></th>
<th><span>Contact Person</span></th>
<th><span>Post</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
<th><span>Website</span></th>
</tr>
<?php foreach ($ngo as $ngo) {
// code...
?>
<tr class="tr_tbl">
<td id="<?php echo $ngo['id'] ?>idngo"><?php echo $ngo['id'] ?></td>
<td id="<?php echo $ngo['id'] ?>organizationngo"><?php echo $ngo['organization'] ?></td>
<td id="<?php echo $ngo['id'] ?>addressngo"><?php echo $ngo['address'] ?></td>
<td id="<?php echo $ngo['id'] ?>phone_nongo"><?php echo $ngo['phone_no'] ?></td>
<td id="<?php echo $ngo['id'] ?>alternate_phone_nongo" ><?php echo $ngo['alternate_phone_no'] ?></td>
<td id="<?php echo $ngo['id'] ?>contact_personngo"><?php echo $ngo['contact_person'] ?></td>
<td id="<?php echo $ngo['id'] ?>personal_nongo"><?php echo $ngo['personal_no'] ?></td>
<td id="<?php echo $ngo['id'] ?>emailngo"><?php echo $ngo['email'] ?></td>
<td id="<?php echo $ngo['id'] ?>websitengo"><?php echo $ngo['website'] ?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<div class="tab-pane fade show" id="volunter" role="tabpanel" aria-labelledby="volunter-tab">
<br>
<a href="get_csv_emergency?type=ddr&&name=DRR_Volunteers&&tbl=emergency_personnel"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th data-th="DRR Volunteers"><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<?php foreach ($ddr as $ddr) {
// code...
?>
<tr class="tr_tbl">
<td id="<?php echo $ddr['id'] ?>idddr"><?php echo $ddr['id'] ?></td>
<td id="<?php echo $ddr['id'] ?>photoddr" ><img src="<?php echo $ddr['photo']?>" height="50" width="50"></td>
<td id="<?php echo $ddr['id'] ?>nameddr"><?php echo $ddr['name'] ?></td>
<td id="<?php echo $ddr['id'] ?>organizationddr"><?php echo $ddr['organization'] ?></td>
<td id="<?php echo $ddr['id'] ?>postddr"><?php echo $ddr['post'] ?></td>
<td id="<?php echo $ddr['id'] ?>addressddr"><?php echo $ddr['address'] ?></td>
<td id="<?php echo $ddr['id'] ?>phone_noddr"><?php echo $ddr['phone_no'] ?></td>
<td id="<?php echo $ddr['id'] ?>emailddr"><?php echo $ddr['email'] ?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<div class="tab-pane fade show" id="person" role="tabpanel" aria-labelledby="person-tab">
<br>
<a href="get_csv_emergency?type=personnel&&name=Municipality_Personnel&&tbl=emergency_personnel"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th data-th="Municipality Personnel"><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<?php foreach ($personnel as $personnel) {
?>
<tr class="tr_tbl">
<td id="<?php echo $personnel['id'] ?>idpersonnel"><?php echo $personnel['id'] ?></td>
<td id="<?php echo $personnel['id'] ?>photopersonnel"><img src="<?php echo $personnel['photo']?>" height="50" width="50"></td>
<td id="<?php echo $personnel['id'] ?>namepersonnel"><?php echo $personnel['name'] ?></td>
<td id="<?php echo $personnel['id'] ?>organizationpersonnel"><?php echo $personnel['organization'] ?></td>
<td id="<?php echo $personnel['id'] ?>postpersonnel"><?php echo $personnel['post'] ?></td>
<td id="<?php echo $personnel['id'] ?>addresspersonnel"><?php echo $personnel['address'] ?></td>
<td id="<?php echo $personnel['id'] ?>phone_nopersonnel"><?php echo $personnel['phone_no'] ?></td>
<td id="<?php echo $personnel['id'] ?>emailpersonnel"><?php echo $personnel['email'] ?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
<div class="tab-pane fade show" id="member" role="tabpanel" aria-labelledby="member-tab">
<br>
<a href="get_csv_emergency?type=members&&name=Members_of_Municipal_Assembly&&tbl=emergency_personnel"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th data-th="Members of Municipal Assembly"><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<?php foreach ($members as $members) {
?>
<tr class="tr_tbl">
<td id="<?php echo $members['id'] ?>idmembers"><?php echo $members['id'] ?></td>
<td id="<?php echo $members['id'] ?>photomembers"><img src="<?php echo $members['photo']?>" height="50" width="50"></td>
<td id="<?php echo $members['id'] ?>namemembers"><?php echo $members['name'] ?></td>
<td id="<?php echo $members['id'] ?>organizationmembers"><?php echo $members['organization'] ?></td>
<td id="<?php echo $members['id'] ?>postmembers"><?php echo $members['post'] ?></td>
<td id="<?php echo $members['id'] ?>addressmembers"><?php echo $members['address'] ?></td>
<td id="<?php echo $members['id'] ?>phone_nomembers"><?php echo $members['phone_no'] ?></td>
<td id="<?php echo $members['id'] ?>emailmembers"><?php echo $members['email'] ?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
</div>
</div>
<script src="<?php echo base_url()?>assets/js/bootstrap-tabdrop.js"></script>
<script type="text/javascript">
$(".nav-tabs").tabdrop();
function myFunction() {
// Declare variables
var input, filter, div, tr, i ,j;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
//
div = document.getElementsByClassName("tab-pane");
//
// td = document.getElementsByTagName('td');
tr = document.getElementsByClassName('tr_tbl');
// console.log(td);
// console.log(h5);
// console.log(div);
// console.log(filter);
// console.log(input);
//
// // Loop through all list items, and hide those who don't match the search query
// var ab='<NAME>'
// console.log(ab.toUpperCase().indexOf(filter));
console.log(tr);
for(j = 0; j < tr.length; j++){
//console.log(tr);
var closeit = 0;
for (i = 0; i < tr[j].children.length; i++) {
var td = tr[j].children[i];
//console.log(td);
// a = h5[i].getElementsByTagName("a")[0];
//console.log(td[i].innerHTML.toUpperCase().indexOf(filter));
if(closeit == 0){
$("#"+td.id).parent().css('display','none');
//console.log("not found on"+td[i].id);
}
if ((td.innerText.toUpperCase().indexOf(filter) > -1) && closeit == 0) {
// console.log("found on"+td.id);
// console.log(closeit);
$("#"+td.id).parent().css('display','');
closeit = 1;
}
}
//console.log("row");
}
}
</script>
<file_sep>/application/views/admin/csv_file.php
<!--main content start-->
<section id="main-content" class="">
<section class="wrapper">
<!-- page start-->
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
Basic Formss
<span class="tools pull-right">
<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">Csv Format Example</button>
</span>
</header>
<div class="panel-body">
<?php
$error= $this->session->flashdata('msg');
if($error){ ?>
<div class="alert alert-info alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message!!!! </strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<div class="position-center">
<h5><i class="fa fa-info-circle"></i> Note: Select a Csv File to Upload to Table</h5><br>
<form role="form" method="POST" action="" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" name="fileToUpload" id="exampleInputFile">
</div>
<button type="submit" name="submit" class="btn btn-info">Upload</button>
</form>
</div>
</div>
<!-- modal start -->
<div class="container">
<h2></h2>
<!-- Trigger the modal with a button -->
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">csv format should be in following format</h4>
</div>
<div class="modal-body">
<!-- table start -->
<form method="POST" action="">
<div class="form-group">
<label class="col-sm-3 control-label col-lg-3" for="inputSuccess">Select Latitude or X</label>
<select name="lat" class="form-control m-bot15">
<option value=""></option>
</select>
<label class="col-sm-3 control-label col-lg-3" for="inputSuccess">Select Lobgitude or Y</label>
<select class="form-control m-bot15">
<option>1</option>
</select>
</div>
<!-- table end -->
</div>
<div class="modal-footer">
<button type="submit" name="submit" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- modal end -->
</section>
</div>
</div>
<!-- kjljlkjklj -->
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/views/admin/create_col.php
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
Add column to table
</header>
<div class="panel-body">
<div class="position-center">
<h5><i class="fa fa-info-circle"></i> Note: add column</h5><br>
<?php
$error= $this->session->flashdata('table');
if($error){ ?>
<div class="alert alert-success alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message</strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<form method="POST" action="" >
<div id='columnid'>
<br> <br>
<div class="form-group">
<label for="pwd">Column Name:</label>
<input type="text" class="form-control" id="pwd" value="Longitude" name="c_name[]" required>
</div>
<div class="form-group">
<label for="pwd">Column Length:</label>
<input type="text" class="form-control" id="pwd" placeholder="Provide Length" name="c_length[]" >
</div>
<div class="form-group">
<label for="pwd">Column Type:</label>
<select class="form-control" name="c_type[]">
<option value="varchar">long</option>
</select>
</div>
<br>
<br>
<div class="form-group">
<label for="pwd">Column Name:</label>
<font color="red"> <input type="text" class="form-control" id="pwd" value="Latitude" name="c_name[]" required> </font>
</div>
<div class="form-group">
<label for="pwd">Column Length:</label>
<input type="text" class="form-control" id="pwd" placeholder="Provide Length" name="c_length[]" >
</div>
<div class="form-group">
<label for="pwd">Column Type:</label>
<select class="form-control" name="c_type[]">
<option value="varchar">long</option>
</select>
</div>
<br>
<br>
<div class="form-group">
<label for="pwd">Column Name:</label>
<input type="text" class="form-control" id="pwd" placeholder="Enter Column Name" name="c_name[]" required>
</div>
<div class="form-group">
<label for="pwd">Column Length:</label>
<input type="text" class="form-control" id="pwd" placeholder="Provide Length" name="c_length[]" >
</div>
<div class="form-group">
<label for="pwd">Column Type:</label>
<select class="form-control" name="c_type[]">
<option value="varchar">varchar</option>
<option value="int">int</option>
</select>
</div>
</div>
<div class="panel-body">
<button type="submit" name="submit_col" class="btn btn-danger"><i class="fa fa-cloud-upload"></i> Submit</button>
</div>
</form>
<button id="btnadd" class="btn btn-info"><i class="fa fa-plus"></i> add column</button>
</div>
</div>
</section>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/models/Site_model.php
<?php
class Site_model extends CI_Model {
public function site_setting($id){
$this->db->select('*');
$this->db->where('id',$id);
$q=$this->db->get('site_setting');
return $q->row_array();
}
public function update_data($data,$id){
$this->db->where('id',$id);
$res=$this->db->update('site_setting',$data);
return $res;
}
public function do_upload($filename,$name)
{
$field_name = $name;
$config['upload_path'] = './uploads/site_setting/';
$config['allowed_types'] = 'png';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
$error['status']=0;
return $error;
}
else
{
$data = array('upload_data' => $this->upload->data());
$data['status']=1;
return $data;
}
}
public function do_upload_cover($filename,$name)
{
$field_name = $name;
$config['upload_path'] = './uploads/site_setting/';
$config['allowed_types'] = 'jpg';
$config['max_size'] = 7000;
$config['overwrite'] = TRUE;
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($field_name))
{
$error = array('error' => $this->upload->display_errors());
$error['status']=0;
return $error;
}
else
{
$data = array('upload_data' => $this->upload->data());
$data['status']=1;
return $data;
}
}
}
<file_sep>/application/views/report_page.php
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<!--<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-ajax/2.1.0/leaflet.ajax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/randomcolor/0.5.2/randomColor.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<!-- date -->
<style>
span.exit {
float: right;
margin-right: 10px;
}
.row.sent {
margin-top: 90px;
color: grey;
font-size: 13px;
}
img.read-mor {
max-height: 250px;
margin-bottom: 25px;
border: 1px solid black;
}
/*.leaflet-left .leaflet-control {
margin-left: 1300;
margin-bottom: 10;
}
.leaflet-top .leaflet-control {
margin-top: 26px;
}*/
/* ---------------------------------------------------
conten-map STYLE
----------------------------------------------------- */
.dropdown-category_dropdown .btn-light{
padding: ;
width: 100%;
border: 1px solid grey;
margin: 1px 0px 3px;
padding: 2px 0px 5px;
font-size: 14px;
}
#conten-map {
padding: 0px;
transition: all 0.3s;
position: relative;
width: 100%;
background: #fff;
}
#conten-map .navbar {
padding: 0;
background: #002052;
border: none;
border-radius: 0;
margin: 0px;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
position: relative;
}
#conten-map .navbar.navbar-default{
min-height: 25px;
font-size: 13px;
}
#sider .panel .panel-body{
padding: 0px 5px 0px;
}
#sider .panel{
margin-bottom: 0px;
}
.wrapper nav#sider{
height: 600px;
overflow: hidden;
overflow-y: hidden;
overflow-y: auto;
}
#sider .sidebar-header{
padding: 5px 10px;
}
#reportrange{
background: #eee;
cursor: pointer;
padding: 5px;
}
#sider #reporting .panel-body{
height: 600px;
overflow-y: auto;
overflow-x: hidden;
}
#reporting .page-header{
margin: 8px 15px 5px;
padding-bottom: 0px;
font-size: 16px;
font-weight: bold;
color: #444;
border-bottom: 1px solid #ddd;
}
#conten-map .nav {
text-align: center;
color: #fff;
}
#conten-map .navbar-header .navbar-nav li{
padding: 0;
color: white;
}
#conten-map .navbar-header .navbar-nav li>a{
color:#fff;
padding-top: 5px;
padding-bottom: 5px;
}
#conten-map .navbar-header .navbar-nav li>a:hover{
text-decoration: none;
color: #002052;
background: #f5f5f5;
}
#conten-map .navbar-default .navbar-nav > li > a:focus{
text-decoration: none;
color: #002052;
background: #f5f5f5;
}
.blog-panel .thumbnail img{
width: 100%;
height: 70px;
object-fit: cover;
}
.blog-panel{
padding-right:0px;
position: relative;
}
/* .blog-panel .thumbnail{
padding: 0px;
margin: 0px;
width: 100%;
height: auto;
margin-top: 10px;
overflow: auto;
}*/
.fancy h5{
color: #002052;
border-bottom: 1px solid #e7e7e7;
font-weight: bold;
word-spacing: 2px;
font-size: 0.9rem;
}
.fancy p{
font-size: 12px;
color: rgba(0,0,0,0.9);
text-align: justify;
}
.fancy a.naya{
font-size: 11px;
float: right;
color: grey;
text-decoration: none;
padding: 2px;
cursor: pointer;
color: #555;
}
.horz{
margin: 0px 40px 5px;
}
.tiny{
color: rgba(0,0,0,0.7);
font-size: 10px;
text-align: justify;
justify-content: space-around;
display: flex;
}
.tiny a{
color: grey;
}
.jana-map{
padding-left: 0;
border-left: 0.2em solid #ccc;
}
.no-padding {
padding-left: 0;
padding-right: 0;
}
.dropdown-category_dropdown{
background-color: #fff;
position: relative;
}
.filter-check{
border-bottom: 0.2em solid #fff;
padding: 8px 1px 4px;
}
.filter-check .dropdown-menu{
min-width: 170px;
}
.filter-check .dropdown-toggle{
width: 95%;
}
.filter-check .multiselect-icon{
border-radius: 0;
margin: 1px 0px 3px;
height: 30px;
padding: 0px 5px;
border: 1px solid #989696;
background-color:#bdbdbd;
width: 98%;
border-radius: 2px;
}
.filter-check .glyphicon{
color: #002052;
}
#datepicker, #datepicker1 {
height: 30px;
padding: 0px;
width: 49%;
display: inline;
margin: 1px -2px 3px;
border-radius: 2px;
border: 1px solid #989696;
background-color:#bdbdbd;
}
.filter-check p{
font-size: 14px;
border-bottom: 1px solid #ccc;
}
#map {
height: 600px; width: 100%; margin-bottom: 0px;position: relative;/*border-top: 0.3em solid #ccc;*/
}
/*popup*/
.arrow_box {
position: relative;
background: silver;
}
.arrow_box:after, .arrow_box:before {
right: 100%;
top: 50%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.arrow_box:after {
border-color: rgba(0, 0, 0, 0);
border-right-color: #silver;
border-width: 20px;
margin-top: -20px;
}
.arrow_box:before {
border-color: rgba(51, 102, 153, 0);
border-right-color: #369;
border-width: 21px;
margin-top: -21px;
}
#popup-container{
max-width: 380px;
max-height: 280px;
}
.popup-panel{
font-weight: 400;
font-family: inherit;
border-radius: .3rem;
padding: 5px;
margin-bottom: 2px;
overflow-x: hidden;
overflow-y: auto;
padding: 5px 0px;
}
.blog-panel1 .thumbnail1 img{
width: 100%;
height: auto;
}
.blog-panel1{
padding: 12px 0px;
position: relative;
}
.blog-panel1 .thumbnail1{
padding: 0px;
margin: 0px;
overflow: auto;
position: relative;
}
.fancy .list-group{
font-size: 10px;
padding: 0px;
margin: 0px;
margin-top: 5px;
border: 1px solid lightgrey;
}
.fancy .list-group .list-group-item{
padding: 3px;
margin: 2px;
}
#popup_nav_small{
padding: 15px 5px;
min-height: 30px;
}
#popup_nav_small .nav-tabs > li.active > a, .nav-tabs > li.active > a:focus, .nav-tabs > li.active > a:hover { border-width: 0; background: none;}
#popup_nav_small .nav-tabs > li > a { border: none; color: #666; }
#popup_nav_small .nav-tabs > li.active > a, .nav-tabs > li > a:hover { border: none; color: #002052 !important; background: transparent; }
#popup_nav_small .nav-tabs > li > a::after { content: ""; background: #002052; height: 2px; position: absolute; width: 100%; left: 0px; bottom: -1px; transition: all 250ms ease 0s; transform: scale(0); }
#popup_nav_small .nav-tabs > li.active > a::after, .nav-tabs > li:hover > a::after { transform: scale(1); }
#popup_nav_small .tab-nav > li > a::after { background: #21527d none repeat scroll 0% 0%; color: #fff; }
#popup_nav_small .tab-pane { font-size: 10px; }
#conten-map .navbar-expand-sm{
background: #1f5cb2;
height: 32px;
}
#conten-map .nav-item .nav-link{
color: #fff;
font-size: 13px;
}
button.btn.btn-light.btn-sm {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.bar {
fill: #2086d9;
}
.holders{
padding: .5rem;
background: rgba(0,0,0,.1);
margin-bottom: 1rem;
text-align: center;
font-size: 13px;
}
.holders >h6{
padding: .2rem 0;
}
.holders >div{
background: white;
padding: .5rem 0;
}
.news-panel{
font-weight: 400;
box-shadow: none;
border-radius: 0;
padding: .7rem;
margin-bottom: 10px;
border: 2px solid rgba(0,0,0,.06);
background: rgba(0,0,0,.03);
}
</style>
<div id="conten-map">
<nav class="navbar navbar-expand-sm">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#"><i class="fa fa-map" aria-hidden="true"></i> <?php echo $site_info['map'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" href="map_reports"><i class="fa fa-database" aria-hidden="true"></i> <?php echo $site_info['data'] ?></a>
</li>
<li class="nav-item">
<a class="nav-link" href="map_reports_table"><i class="fa fa-pencil-square" aria-hidden="true"></i> <?php echo $site_info['ghatana_bib'] ?></a>
</li>
</ul>
</nav>
<div class="wrapper">
<!-- Sidebar Holder -->
<div class="row">
<div class="col-md-3 col-sm-12" style="padding-right: 0;">
<div id="sider">
<!-- problems reposrting sections starts -->
<div class="panel" id="reporting">
<!-- report title -->
<div class="page-header">
<p>Citizen reports</p>
</div>
<div class="panel-body">
<!-- report 1 -->
<!-- report 5 -->
<?php foreach($report_data as $data){ ?>
<div class="news-panel clearfix report_div" value="<?php echo $data['latitude'] ;?>" name="<?php echo $data['longitude'] ;?>">
<div class="row">
<div class="col-md-3 blog-panel">
<a href="#" class="thumbnail">
<img src="<?php echo $data['photo_thumb'] ;?>" alt="image">
</a>
</div>
<div class="fancy col-md-9">
<h5><?php echo $data['incident_type'] ;?></h5>
<p class="small">
<?php echo $data['message'] ;?>
<!-- readmore -->
<a class="naya" data-toggle="modal" data-target=".<?php echo $data['id'] ;?>_">Read More</a>
<div class="modal fade <?php echo $data['id'] ;?>_" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true" style="color: #111" class="exit">×</span><span class="sr-only">Close</span></button>
<div class="container">
<h3>Incident Type : <?php echo $data['incident_type'] ;?></h3>
<hr>
<div class="row">
<div class="col-md-4"><img src="<?php echo $data['photo_thumb'] ;?>" alt="image" class="read-mor"></div>
<div class="col-md-8">
<?php echo $data['message'] ;?>
<div class="row sent">
<div class="col-md-4">Name: <?php echo $data['name'] ;?></div>
<div class="col-md-4"> Date: <?php echo $data['incident_time'] ;?></div>
<!-- <div class="col-md-4">3 Days Ago</div> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- read more modal -->
</p>
</div>
</div>
<hr class="horz">
<div class="row">
<div class="col-md-12">
<ul class="list-inline tiny">
<li class="list-inline-item"><i class="fa fa-list" aria-hidden="true"></i> Category: <a href="#"><?php echo $data['incident_type'] ;?></a> </li>
<li class="list-inline-item"><i class="icon-calendar" aria-hidden="true"></i> Status: <a href="#"> <?php echo $data['status'] ;?></a></li>
<li class="list-inline-item"><i class="fa fa-clock-o" aria-hidden="true"></i> <?php echo $data['incident_time'] ;?></li>
</ul>
</div>
</div>
</div>
<?php } ?>
<!-- //end -->
<div class="text-center mt-3 mb-3">
<a href="#" title="" class="btn btn-primary btn-sm">View All <i class="la la-arrow-right"></i></a>
</div>
</div>
</div>
<!-- problems reposrting sections ends -->
</div>
</div>
<div class="col-md-9 col-sm-12 jana-map">
<?php
$error= $this->session->flashdata('msg');
if($error){ ?>
<div class="alert alert-danger alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message!!!!</strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<div id="filter-section" class="filter-wrap">
<form action="" method="post">
<div class="row" style="margin-left: 0; margin-right: 0;">
<!-- map contrl items -->
<div class="col-md-4 no-padding">
<div class="text-center dropdown-category_dropdown filter-check">
<div class="form-group" style="margin-bottom: 0;">
<input name="from_date" class="form-control" type="date" id="datepicker" placeholder="From">
<input name="to_date" class="form-control" type="date" id="datepicker1" placeholder="To">
</div>
</div>
</div>
<div class="col-md-2 no-padding">
<div class="text-center dropdown-category_dropdown filter-check">
<select name="ward" class="custom-select multiselect-icon">
<option value="0" selected>Select ward</option>
<option value="1" >ward no 1</option>
<option value="2" >ward no 2</option>
<option value="3" >ward no 3</option>
<option value="4" >ward no 4</option>
<option value="5" >ward no 5</option>
<option value="6" >ward no 6</option>
<option value="7" >ward no 7</option>
<option value="8" >ward no 8</option>
</select>
</div>
</div>
<div class="col-md-2 no-padding">
<div class="text-center dropdown-category_dropdown filter-check">
<select name="incident_type" class="custom-select multiselect-icon">
<option value="0" selected>Select Category</option>
<option value="Fire" >Fire</option>
<option value="Earth" >Earth</option>
<option value="Water" >Water</option>
</select>
</div>
</div>
<div class="col-md-2 no-padding">
<div class="text-center dropdown-category_dropdown filter-check">
<select name="status" class="custom-select multiselect-icon">
<option value="0" selected>Status</option>
<option value="ongoing" >Ongoing</option>
<option value="pending" >Pending</option>
<option value="completed" >Completed</option>
</select>
</div>
</div>
<div class="col-md-2 no-padding">
<div class="text-center dropdown-category_dropdown filter-check">
<button name="submit" class="btn btn-light btn-sm" type="submit"><?php echo $site_info['apply'] ?></button>
</div>
</div>
</div>
</form>
</div>
<!-- main map -->
<div class="position-relative">
<div class="row no-gutters">
<div class="col-md-9">
<div id="filter-section-toggle" class="filter-toggle">
<i class="la la-filter"></i> Filter
</div>
<div id="map" style="margin-top: 0;"></div>
</div>
<div class="col-md-3">
<!-- <div class="info-panel bg-white"> -->
<div class="bg-white">
<!-- <div class="panel-toggle"><i class="la la-close"></i></div> -->
<div class="panel-content padding">
<div id="bar_graph" style="display:block;" >
<div class="holders">
<h6><strong>Wards</strong></h6>
<div id="graphic"></div>
</div>
<div class="holders">
<h6><strong>Incident Type</strong></h6>
<div id="graphic1"></div>
</div>
<div class="holders">
<h6><strong>Report status</strong></h6>
<div id="graphic2"></div>
</div>
</div>
<!-- <ul class="chart-panel-list">
<li class="chart-wrap">
<h6>Ward</h6>
<ul class="h-chart-list">
<li>
<label>Ward 1</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Ward 2</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 75%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Ward 1</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Ward 2</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 75%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Ward 1</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Ward 2</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 75%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
</ul>
</li>
<li class="chart-wrap">
<h6>Type</h6>
<ul class="h-chart-list">
<li>
<label>Fire</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 55%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Flood</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 35%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Fire</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 55%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Flood</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 35%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
</ul>
</li>
<li class="chart-wrap">
<h6>Status</h6>
<ul class="h-chart-list">
<li>
<label>Pending</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 55%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Ongoing</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 35%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
<li>
<label>Completed</label>
<div class="progress bg-white" style="height: 13px;">
<div class="progress-bar" role="progressbar" style="width: 55%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</li>
</ul>
</li>
</ul> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#filter-section-toggle').click(function(){
$('#filter-section').toggleClass('active');
$(this).find('i').toggleClass('la-close');
});
$('.panel-toggle').click(function(){
$(this).parent('.info-panel').addClass('d-none');
});
});
</script>
<script>
var report = '<?php echo $report_map_layer ;?>';
var map_lat='<?php echo $map_set['map_lat'] ?>';
var map_long='<?php echo $map_set['map_long'] ?>';
var map_zoom='<?php echo $map_set['map_zoom'] ?>';
report_layer = JSON.parse(report);
//console.log(report_layer);
/*-- LayerJS--*/
$(document).ready(function(){
$(".layer-toggle").click(function(){
$(".panel.panel-success").toggle(800);
$(".layer-toggle i").toggleClass("fa-chevron-right");
});
//map part
var map = L.map('map').setView([map_lat,map_long], map_zoom);
map.attributionControl.addAttribution("<a href='http://www.naxa.com.np' title = 'Contributor'>NAXA</a>");
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);
var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
});
googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
googleHybrid = L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
googleTerrain = L.tileLayer('http://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
//var none = "";
var baseLayers = {
"OpenStreetMap": osm,
"Google Streets": googleStreets,
"Google Hybrid": googleHybrid,
"Google Satellite": googleSat,
"Google Terrain": googleTerrain//,
//"None": none
};
map.addLayer(osm);
layerswitcher = L.control.layers(baseLayers, {}, {collapsed: true}).addTo(map);
$(".layer-toggle").click(function(){
$(".panel.panel-success").toggle(1000);
$(".layer-toggle i").toggleClass("fa-chevron-right");
});
var sankhu = new L.geoJson.ajax("http://app.naxa.com.np/geojson/Changunarayan_Ward.geojson", {
onEachFeature: function(feature,layer){
layer.on('click', function() {
map.fitBounds(layer.getBounds());
});
layer.setStyle({
fillColor:"Green",
fillOpacity:0,
weight: 1,
opacity: 1,
color: 'black',
//dashArray: '3'
});
}
}).addTo(map);
sankhu.on('data:loaded', function (data) {
map.fitBounds(sankhu.getBounds());
});
var report_map = new L.GeoJSON(report_layer, {
pointToLayer: function(feature, latlng) {
icons = L.icon({
//iconSize: [27, 27],
iconAnchor: [13, 27],
popupAnchor: [2, -24],
iconUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon.png'
});
//console.log(icon.options);
var marker = L.marker(latlng, {icon: icons});
return marker;
},
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties.type);
//feature.properties.layer_name = "transit_stops";
}
});
report_map.on('data:loaded', function (data) {
});
report_map.addTo(map);
//filter start
$('.report_div').click(function(){
var long =$(this).attr("name");
var lat =$(this).attr("value");
console.log(typeof lat);
console.log(long);
map.setView([parseFloat(lat),parseFloat(long)], 18);
//$.ajax({
// url: 'ReportController/search?data='+srch,
// success: function(response) {
//alert(response);
//var srchd= JSON.parse(response);
// alert(response);
// map.removeLayer(report_map);s
// single_report=JSON.parse(response);
//
// console.log(parseFloat(single_report.features.geometry.coordinates[0]));
// var single_map = new L.GeoJSON(single_report, {
// pointToLayer: function(feature, latlng) {
// icons = L.icon({
// //iconSize: [27, 27],
// iconAnchor: [13, 27],
// popupAnchor: [2, -24],
// iconUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon.png'
// });
// //console.log(icon.options);
// var marker = L.marker(latlng, {icon: icons});
// return marker;
//
// },
// onEachFeature: function(feature, layer) {
// layer.bindPopup(feature.properties.name);
// //feature.properties.layer_name = "transit_stops";
//
// }
// });
// single_map.on('data:loaded', function (data) {
//
// map.addLayer(single_map);
//
//
// });
//map.setView(parseFloat(single_report.features.geometry.coordinates[1]),parseFloat(single_report.features.geometry.coordinates[0]), 18);
//}
//});
});
//filter end
//start chart
chart_dataa='<?php echo $bar_ward ?>'
chart_data=(JSON.parse(chart_dataa));
chart_dataa1='<?php echo $bar_cat ?>'
chart_data1=(JSON.parse(chart_dataa1));
chart_dataa2='<?php echo $bar_stat ?>'
chart_data2=(JSON.parse(chart_dataa2));
console.log(chart_data2);
// chart_data=[
// {"name": "1", "value": 201 },
// {"name": "2", "value": 20 },
// {"name": "3", "value": 80 },
// {"name": "4", "value": 102 },
// {"name": "5", "value": 300 },
// {"name": "6", "value": 233 },
// {"name": "7", "value": 100 }
// ];
function CreateChart(chart_data, bar_id){
data = chart_data.sort(function (a, b) {
// console.log(d3.ascending(a.value, b.value));
return d3.descending(a.name, b.name);
})
var hig=75;
if(bar_id=="graphic"){
hig=160;
}
//set up svg using margin conventions - we'll need plenty of room on the left for labels
var margin = {
top: 5,
right: 10,
bottom: 5,
left: 70
};
var width = 120 - margin.left - margin.right,
height = hig - margin.top - margin.bottom;
var svg = d3.select("#"+bar_id).append("svg")
.attr("width", width + margin.left + margin.right + 110)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.style("margin-top", "30px")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scale.linear()
.range([0, width])
.domain([0, d3.max(chart_data, function (d) {
return d.value;
})]);
var y = d3.scale.ordinal()
.rangeRoundBands([height, 0], .3)
.domain(chart_data.map(function (d) {
if(bar_id=="graphic"){
return 'Ward'+' '+d.name;
}else{
return d.name;
}
}));
//make y axis to show bar names
var yAxis = d3.svg.axis()
.scale(y)
//no tick marks
.tickSize(0)
.orient("left");
var gy = svg.append("g")
.attr("class", "y axis")
.call(yAxis)
var bars = svg.selectAll(".bar")
.data(chart_data)
.enter()
.append("g")
//append rects
bars.append("rect")
.attr("class", "bar")
.attr("y", function (d) {
if(bar_id=="graphic"){
return y('Ward'+' '+d.name);
}else{
return y(d.name);
}
})
.attr("height", y.rangeBand())
.attr("x", 0)
.attr("width", function (d) {
return x(d.value);
});
//add a value label to the right of each bar
bars.append("text")
.attr("class", "label")
//y position of the label is halfway down the bar
.attr("y", function (d) {
if(bar_id=="graphic"){
return y('Ward'+' '+d.name) + y.rangeBand() / 2 + 4;
}else{
return y(d.name) + y.rangeBand() / 2 + 4;
}
})
//x position is 3 pixels to the right of the bar
.attr("x", function (d) {
return x(d.value) + 3;
})
.text(function (d) {
return d.value;
});
}
bar_id="graphic";
bar_idd="graphic1";
bar_iddd="graphic2";
CreateChart(chart_data, bar_id);
CreateChart(chart_data1, bar_idd);
CreateChart(chart_data2, bar_iddd);
//chart end
}); //document --ends
$('#datepicker').datepicker({
dateFormat: 'dd/mm/yy'
});
</script>
<file_sep>/application/models/Mapapi_model.php
<?php
class Mapapi_model extends CI_Model {
public function get_list(){
$this->db->select('category_name,category_table,category_type,category_photo');
$q=$this->db->get('categories_tbl');
return $q->result_array();
}
}
<file_sep>/application/views/admin/edit_emerg_personnel.php
<!--main content start-->
<section id="main-content" class="">
<section class="wrapper">
<!-- page start-->
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
Form Elements
</header>
<div class="panel-body">
<form class="form-horizontal bucket-form" method="post" action="">
<input type="hidden" value="<?php echo $e_data['id']; ?>" name="id">
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-sm-6">
<input type="text" value="<?php echo $e_data['name']; ?>" name="name" class="form-control round-input">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Organization</label>
<div class="col-sm-6">
<input type="text" value="<?php echo $e_data['organization']; ?>" name="organization" class="form-control round-input">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Post</label>
<div class="col-sm-6">
<input type="text" value="<?php echo $e_data['post']; ?>" name="post" class="form-control round-input">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Address</label>
<div class="col-sm-6">
<input type="text" value="<?php echo $e_data['address']; ?>" name="address" class="form-control round-input">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Phone No</label>
<div class="col-sm-6">
<input type="text" value="<?php echo $e_data['phone_no']; ?>" name="phone_no" class="form-control round-input">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Email</label>
<div class="col-sm-6">
<input type="text" value="<?php echo $e_data['email']; ?>" name="email" class="form-control round-input">
</div>
</div>
<div class="col-md-6">
<button type="submit" name="submit" class="btn btn-info">Submit</button>
</div>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/views/admin/edit_feature_nep.php
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!-- page start-->
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
Feature Dataset Nepali
</header>
<div class="panel-body">
<div class="position-center">
<h5><i class="fa fa-info-circle"></i> Note: Select a Layer File to Upload to Table</h5><br>
<form role="form" method="POST" action="" enctype="multipart/form-data">
<?php
$error= $this->session->flashdata('msg');
if($error){ ?>
<div class="alert alert-info alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message!!!!</strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<div class="form-group">
<label for="exampleInputFile">Data Category</label>
<select name="table">
<?php foreach($cat as $d){
if($e_data['table']== $d['category_table']){
?>
<option selected="selected" value="<?php echo $d['category_table'] ?>"><?php echo $d['category_name']?></option>
<?php } ?>
<option value="<?php echo $d['category_table'] ?>"><?php echo $d['category_name']?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nepali Title</label>
<input type="text" name="nepali_title" value="<?php echo $e_data['nepali_title'] ?>" class="form-control" id="exampleInputEmail1" required>
<input type="hidden" name="id" value="<?php echo $e_data['id'] ?>" class="form-control" id="exampleInputEmail1" required>
</div>
<div class="form-group">
<label class="col-sm-3 control-label col-sm-2">Nepali Summary</label>
<div class="col-sm-10">
<textarea class="form-control" name="nepali_summary" rows="5" required><?php echo $e_data['nepali_summary'] ?></textarea>
</div>
</div>
<button type="submit" name="submit" class="btn btn-info">Upload</button>
</form>
</div>
</div>
</section>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/views/contact_static.php
<style>
.nav-tabs,
.nav-pills {
position: relative;
}
.tabdrop{
width: 120px;
margin-top: .5rem;
}
.nav-tabs li li i{
visibility: hidden;
}
.hide {
display: none;
}
.input-group-addon {
position: absolute;
right: 10px;
bottom: 13px;
z-index: 2;
}
.contact-search-1 {
padding: 50px;
border-bottom: 1px solid #eee;
padding-left: 0px;
}
.responstable th {
display: none;
border: 1px solid transparent;
background-color: lightslategray;
color: #FFF;
padding: 1em;
}
#reportable{
overflow: auto;
margin: 0em auto 3em;
}
.responstable {
margin: 1em 0em;
width: 100%;
overflow: hidden;
background: #FFF;
color: #000;
border-radius: 0px;
border: 1px solid #1f5cb2;
font-size: 16px;
}
.responstable tr {
border: 1px solid #D9E4E6;
}
.responstable tr:nth-child(odd) {
background-color: #EAF3F3;
}
.responstable th:first-child {
display: table-cell;
text-align: center;
}
.responstable th:nth-child(2) {
display: table-cell;
}
.responstable th:nth-child(2) span {
display: none;
}
.responstable th:nth-child(2):after {
content: attr(data-th);
}
@media (min-width: 480px) {
.responstable th:nth-child(2) span {
display: block;
}
.responstable th:nth-child(2):after {
display: none;
}
}
.responstable td {
display: block;
word-wrap: break-word;
max-width: 7em;
}
.responstable td:first-child {
display: table-cell;
text-align: center;
border-right: 1px solid #D9E4E6;
}
@media (min-width: 480px) {
.responstable td {
border: 1px solid #D9E4E6;
}
}
.responstable th, .responstable td {
text-align: left;
margin: .5em 1em;
}
@media (min-width: 480px) {
.responstable th, .responstable td {
display: table-cell;
padding: 0.3em;
}
}
.tabdrop .dropdown-menu a{
padding: 20px;
}
</style>
<!--advance Search starts-->
<div class="container ">
<div class="contact-search-1">
<div class="row">
<div class="col-sm-12 text-center">
<div class="row no-gutters">
<div class="col">
<input class="form-control border-secondary border-right-0 rounded-0" type="search" placeholder="Search For.." id="myInput" onkeyup="myFunction()">
</div>
<div class="col-auto">
<button class="btn btn-secondary border-left-0 rounded-0 rounded-right" type="button">
<i class="fa fa-search"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!--advance Search ends-->
<!-- table List -->
<div class="container" id="emergency_no">
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="health-tab" data-toggle="tab" href="#health" role="tab" aria-controls="health" aria-selected="true">Chairpersons of Local Units</a>
</li>
<li class="nav-item">
<a class="nav-link" id="emergency-tab" data-toggle="tab" href="#emergency" role="tab" aria-controls="emergency" aria-selected="false">Chief of local level offices</a>
</li>
<li class="nav-item">
<a class="nav-link" id="security-tab" data-toggle="tab" href="#security" role="tab" aria-controls="security" aria-selected="false">Elected Representatives</a>
</li>
<li class="nav-item">
<a class="nav-link" id="ngo-tab" data-toggle="tab" href="#ngo" role="tab" aria-controls="ngo" aria-selected="false">Municipal Executive Members</a>
</li>
<li class="nav-item">
<a class="nav-link" id="volunter-tab" data-toggle="tab" href="#volunter" role="tab" aria-controls="volunter" aria-selected="false">Municipality Level Disaster Management Committee,</a>
</li>
<li class="nav-item">
<a class="nav-link" id="person-tab" data-toggle="tab" href="#person" role="tab" aria-controls="person" aria-selected="false">NNTDS's Executive Committee</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="health" role="tabpanel" aria-labelledby="health-tab">
<br>
<a href="get_csv_emergency?type=health&&name=Health_Institutions&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px; float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<tr class="tr_tbl">
<td>1</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Chairperson</td>
<td>Bhaktapur</td>
<td>9851190724/6614826</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>2</td>
<td></td>
<td>Ms. <NAME></td>
<td></td>
<td>Vice-Chairperson</td>
<td>Bhaktapur</td>
<td>9803746106/6610364</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>3</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Mayor</td>
<td>Changunaryan</td>
<td>9751001744</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>4</td>
<td></td>
<td>Ms. <NAME></td>
<td></td>
<td>Deputy Mayor</td>
<td>Changunaryan</td>
<td>9841590313</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>5</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunaryan 1</td>
<td>9851054332</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>6</td>
<td></td>
<td>Mr. <NAME>c</td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunaryan 2</td>
<td>9851218757</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>7</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunaryan 3</td>
<td>9741087544</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>8</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunaryan 4</td>
<td>9841692325</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>9</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunaryan 5</td>
<td>9860025471</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>10</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunaryan 6</td>
<td>9841271607</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>11</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunarayan 7</td>
<td>9841788376</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>12</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunarayan 8</td>
<td>9851036476</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>13</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward Chairperson</td>
<td>Changunarayan 9</td>
<td>9851078002</td>
<td></td>
</tr>
</table>
</div>
</div>
<div class="tab-pane fade show" id="emergency" role="tabpanel" aria-labelledby="emergency-tab">
<br>
<a href="get_csv_emergency?type=responders&&name=Emergency_Responders&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<tr class="tr_tbl">
<td>1</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>LDO</td>
<td>DCC</td>
<td>9851184826</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>2</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Chief Executive Officer</td>
<td>Changunarayan Municipality</td>
<td>9851191068</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>3</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 1 , Duwakot</td>
<td>9841393771</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>4</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretaryr</td>
<td>Changunarayan 2 , Duwakot</td>
<td>9851048489</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>5</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 3 Jhoukhel</td>
<td>9841393990</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>6</td>
<td></td>
<td>Mr. Shankar KCc</td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 4 Changu</td>
<td>9841208670</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>7</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 5 Chhaling</td>
<td>9841725492</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>8</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 6 Nagarkot</td>
<td>9841249993</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>9</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 7 Bageshwori</td>
<td>9841299358</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>10</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 8 Sudal</td>
<td>9841249993</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>11</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 9 Tathali</td>
<td>9841279066</td>
<td></td>
</tr>
</table>
</div>
</div>
<div class="tab-pane fade show" id="security" role="tabpanel" aria-labelledby="security-tab">
<br>
<a href="get_csv_emergency?type=security&&name=Security&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<tr class="tr_tbl">
<td>1</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Ward Chairperson</td>
<td>Ward no. 1</td>
<td>9851054332</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>2</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Women Member</td>
<td>Ward no. 1</td>
<td>9841148428</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>3</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Dalit Women Member</td>
<td>Ward no. 1</td>
<td>9803684271</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>4</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Member</td>
<td>Ward no. 1</td>
<td>9851048489</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>5</td>
<td></td>
<td><NAME>hadka</td>
<td>Nepal Local Government</td>
<td>Member</td>
<td>Ward no. 1</td>
<td9841368575</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>6</td>
<td></td>
<td>Shivhari KC</td>
<td>Nepal Local Government</td>
<td>Ward Chairperson</td>
<td>Ward no. 2</td>
<td>9851218757</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>7</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Women Member</td>
<td>Ward no. 2</td>
<td>9841130754</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>8</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Dalit Women Member</td>
<td>Ward no. 2</td>
<td>9849296613</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>9</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Member</td>
<td>Ward no. 2</td>
<td>9851094430</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>10</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Member</td>
<td>Ward no. 2</td>
<td>9843054370</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>11</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Ward Chairperson</td>
<td>Ward no. 3</td>
<td>9741087544</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>12</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Women Member</td>
<td>Ward no. 3</td>
<td>9841987236</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>13</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Dalit Women Member</td>
<td>Ward no. 3</td>
<td>9823156413</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>14</td>
<td></td>
<td><NAME></td>
<td>Nepal Local Government</td>
<td>Member</td>
<td>Ward no. 3</td>
<td>9841560350</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>15</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretaryr</td>
<td>Changunarayan 2 , Duwakot</td>
<td>9851048489</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>16</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 3 Jhoukhel</td>
<td>9841393990</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>17</td>
<td></td>
<td>Mr. Shankar KCc</td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 4 Changu</td>
<td>9841208670</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>18</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 5 Chhaling</td>
<td>9841725492</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>19</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 6 Nagarkot</td>
<td>9841249993</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>20</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 7 Bageshwori</td>
<td>9841299358</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>21</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 8 Sudal</td>
<td>9841249993</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>22</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 9 Tathali</td>
<td>9841279066</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>23</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>LDO</td>
<td>DCC</td>
<td>9851184826</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>24</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Chief Executive Officer</td>
<td>Changunarayan Municipality</td>
<td>9851191068</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>25</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 1 , Duwakot</td>
<td>9841393771</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>26</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretaryr</td>
<td>Changunarayan 2 , Duwakot</td>
<td>9851048489</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>27</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 3 Jhoukhel</td>
<td>9841393990</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>28</td>
<td></td>
<td>Mr. Shankar KCc</td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 4 Changu</td>
<td>9841208670</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>29</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 5 Chhaling</td>
<td>9841725492</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>30</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 6 Nagarkot</td>
<td>9841249993</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>31</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 7 Bageshwori</td>
<td>9841299358</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>32</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 8 Sudal</td>
<td>9841249993</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>33</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 9 Tathali</td>
<td>9841279066</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>34</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>LDO</td>
<td>DCC</td>
<td>9851184826</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>35</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Chief Executive Officer</td>
<td>Changunarayan Municipality</td>
<td>9851191068</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>36</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 1 , Duwakot</td>
<td>9841393771</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>37</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretaryr</td>
<td>Changunarayan 2 , Duwakot</td>
<td>9851048489</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>38</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 3 Jhoukhel</td>
<td>9841393990</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>39</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 4 Changu</td>
<td>9841208670</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>40</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 5 Chhaling</td>
<td>9841725492</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>41</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 6 Nagarkot</td>
<td>9841249993</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>42</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 7 Bageshwori</td>
<td>9841299358</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>43</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 8 Sudal</td>
<td>9841249993</td>
<td></td>
</tr>
<tr class="tr_tbl">
<td>44</td>
<td></td>
<td>Mr. <NAME></td>
<td></td>
<td>Ward secretary</td>
<td>Changunarayan 9 Tathali</td>
<td>9841279066</td>
<td></td>
</tr>
</tr>
</table>
</div>
</div>
<div class="tab-pane fade show" id="ngo" role="tabpanel" aria-labelledby="ngo-tab">
<br>
<a href="get_csv_emergency?type=ngo&&name=NGOs_INGOs&&tbl=emergency_contact"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<tr class="tr_tbl">
<td>1</td>
<td>Nepal</td>
<td>Kathmandu</td>
<td>01647687</td>
<td>98657664675</td>
<td>John</td>
<td>Clerk</td>
<td>0980909809</td>
<td><EMAIL></td>
<td>wwww.test.com.np</td>
</tr>
</table>
</div>
</div>
<div class="tab-pane fade show" id="volunter" role="tabpanel" aria-labelledby="volunter-tab">
<br>
<a href="get_csv_emergency?type=ddr&&name=DRR_Volunteers&&tbl=emergency_personnel"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
<tr class="tr_tbl">
<td>1</td>
<td>Img</td>
<td>Aditi</td>
<td>KCC</td>
<td>Collector</td>
<td>Bhaktapur</td>
<td>0980909809</td>
<td><EMAIL></td>
</tr>
</table>
</div>
</div>
<div class="tab-pane fade show" id="person" role="tabpanel" aria-labelledby="person-tab">
<br>
<a href="get_csv_emergency?type=personnel&&name=Municipality_Personnel&&tbl=emergency_personnel"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<tr class="tr_tbl">
<td>1</td>
<td>Nepal</td>
<td>Kathmandu</td>
<td>01647687</td>
<td>98657664675</td>
<td>John</td>
<td>Clerk</td>
<td>0980909809</td>
<td><EMAIL></td>
<td>wwww.test.com.np</td>
</tr>
</table>
</div>
</div>
<div class="tab-pane fade show" id="member" role="tabpanel" aria-labelledby="member-tab">
<br>
<a href="get_csv_emergency?type=members&&name=Members_of_Municipal_Assembly&&tbl=emergency_personnel"><button type="submit" name="upload_data" class="btn btn-danger" style="background-color: #1f5cb2;border-color: #1f5cb2;margin-top: -7px;float: right;"><i class="fa fa-download"></i> Download</button></a>
<br>
<div class="row" id="reportable">
<!-- responsive table for displaying contact directory -->
<table class="responstable">
<tr>
<th><span>S.N</span></th>
<th><span>Photo</span></th>
<th><span>Name</span></th>
<th><span>Organization</span></th>
<th><span>Post</span></th>
<th><span>Address</span></th>
<th><span>Phone No.</span></th>
<th><span>Email</span></th>
</tr>
<tr class="tr_tbl">
<td>1</td>
<td>Img</td>
<td>Aditi</td>
<td>KMC</td>
<td>Collector</td>
<td>0998989080</td>
<td>0980909809</td>
<td><EMAIL></td>
</tr>
</table>
</div>
</div>
</div>
</div>
<script src="<?php echo base_url()?>assets/js/bootstrap-tabdrop.js"></script>
<script type="text/javascript">
$(".nav-tabs").tabdrop();
function myFunction() {
// Declare variables
var input, filter, div, tr, i ,j;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
//
div = document.getElementsByClassName("tab-pane");
//
// td = document.getElementsByTagName('td');
tr = document.getElementsByClassName('tr_tbl');
// console.log(td);
// console.log(h5);
// console.log(div);
// console.log(filter);
// console.log(input);
//
// // Loop through all list items, and hide those who don't match the search query
// var ab='<NAME>'
// console.log(ab.toUpperCase().indexOf(filter));
console.log(tr);
for(j = 0; j < tr.length; j++){
//console.log(tr);
var closeit = 0;
for (i = 0; i < tr[j].children.length; i++) {
var td = tr[j].children[i];
//console.log(td);
// a = h5[i].getElementsByTagName("a")[0];
//console.log(td[i].innerHTML.toUpperCase().indexOf(filter));
if(closeit == 0){
$("#"+td.id).parent().css('display','none');
//console.log("not found on"+td[i].id);
}
if ((td.innerText.toUpperCase().indexOf(filter) > -1) && closeit == 0) {
// console.log("found on"+td.id);
// console.log(closeit);
$("#"+td.id).parent().css('display','');
closeit = 1;
}
}
//console.log("row");
}
}
</script>
<file_sep>/application/views/admin/header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="ThemeBucket">
<meta http-equiv=”X-UA-Compatible” content=”IE=EmulateIE9”>
<meta http-equiv=”X-UA-Compatible” content=”IE=9”>
<link rel="shortcut icon" href="images/favicon.png">
<title>Admin</title>
<!--Core CSS -->
<link href="<?php echo base_url();?>assets/admin/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/admin/css/bootstrap-reset.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/admin/css/font-awesome.css" rel="stylesheet" />
<link href="<?php echo base_url();?>assets/admin/css/onoffbtn.css" rel="stylesheet" />
<link rel="stylesheet" href="<?php echo base_url();?>assets/admin/css/DT_bootstrap.css" />
<!-- //step forms css -->
<link rel="stylesheet" href="<?php echo base_url();?>assets/admin/css/jquery.steps.css?1">
<!-- fileupload drop box css -->
<link rel="stylesheet" href="<?php echo base_url();?>assets/admin/css/dropzone.css">
<!-- data css -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<!-- end -->
<!-- fileuplaod css -->
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/admin/css/bootstrap-fileupload.css" />
<!-- Custom styles for this template -->
<link href="<?php echo base_url();?>assets/admin/css/style.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/admin/css/style-responsive.css" rel="stylesheet" />
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]>
<script src="js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<style>
section#wizard-p-0 {
overflow-y: scroll;
}
.panel-body {
overflow: auto;
}
.form-control {
color: #110000;
}
</style>
</head>
<body>
<section id="container">
<!--header start-->
<header class="header fixed-top clearfix">
<!--logo start-->
<div class="brand">
<a href="<?php echo base_url()?>dashboard" class="logo">
<img src="<?php echo base_url()?>assets/img/changu.png" alt="admin" height=60;><div class="cnm">Changunarayan <br>Municipality </div>
</a>
<div class="sidebar-toggle-box">
<div class="fa fa-bars"></div>
</div>
</div>
<!--logo end-->
<!-- notification start -->
<!-- notification end -->
<div class="top-nav clearfix">
<!--search & user info start-->
<ul class="nav pull-right top-menu">
<li>
<input type="text" class="form-control search" placeholder=" Search">
</li>
<!-- user login dropdown start-->
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<span class="username"><i class="fa fa-user"></i> Admin</span>
<b class="caret"></b>
</a>
<ul class="dropdown-menu extended logout">
<li><a href="#"><i class=" fa fa-suitcase"></i>Profile</a></li>
<li><a href="#"><i class="fa fa-cog"></i> Settings</a></li>
<li><a href="<?php echo base_url()?>logout"><i class="fa fa-key"></i> Log Out</a></li>
</ul>
</li>
<!-- user login dropdown end -->
<!-- <li>
<div class="toggle-right-box">
<div class="fa fa-bars"></div>
</div>
</li> -->
</ul>
<!--search & user info end-->
</div>
</header>
<!--header end-->
<!--sidebar start-->
<aside>
<div id="sidebar" class="nav-collapse">
<!-- sidebar menu start-->
<div class="leftside-navigation">
<ul class="sidebar-menu" id="nav-accordion">
<li>
<a href="<?php echo base_url()?>dashboard" >
<i class="fa fa-dashboard"></i>
<span>Dashboard</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-laptop"></i>
<span>Home Page</span>
</a>
<ul class="sub">
<li><a href="<?php echo base_url()?>view_proj">Project Partners</a></li>
<!-- <li><a href="<?php echo base_url()?>emergency_contact">Emergency Contact</a></li> -->
<!-- <li><a href="<?php echo base_url()?>background">Background Image</a></li> -->
<li><a href="<?php echo base_url();?>feature">Featured Datasets</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-laptop"></i>
<span>Categorie Management</span>
</a>
<ul class="sub">
<li><a href="<?php echo base_url();?>categories_tbl">Categories</a></li>
<li><a href="<?php echo base_url();?>sub_categories"> Sub-Categories</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-th"></i>
<span>Emergency Contact</span>
</a>
<ul class="sub">
<!-- <li><a href="<?php echo base_url();?>create_categories_tbl">Create Database Tables</a></li>
<li><a href="<?php echo base_url();?>view_cat_tables">View Categories Data Tables</a></li> -->
<li><a href="<?php echo base_url()?>emergency_contact?name=Health Institutions&&cat=health">Health Institutions</a></li>
<li><a href="<?php echo base_url()?>emergency_contact?name=Emergency Responders&&cat=responders">Emergency Responders</a></li>
<li><a href="<?php echo base_url()?>emergency_contact?name=Security&&cat=security">Security</a></li>
<li><a href="<?php echo base_url()?>emergency_contact?name=NGOs and INGOs&&cat=ngo">NGOs and INGOs</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=DRR Volunteers&&cat=ddr">DRR Volunteers</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=Municipality Personnel&&cat=personnel">Municipality Personnel</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=Members of Municipal Assemblysss&&cat=members">Members of Municipal Assemblysss</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=Chairpersons of Local Units&&cat=chairpersons">Chairpersons of Local Units</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=Chief of local level offices&&cat=chief">Chief of local level offices</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=Elected Representatives&&cat=elected">Elected Representatives</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=Municipal Executive Members&&cat=municipal_ex">Municipal Executive Members</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=Municipality Level Disaster Management Committee&&cat=disaster">Municipality Level Disaster Management Committee</a></li>
<li><a href="<?php echo base_url()?>emergency_personnel?name=Municipality Level Disaster Management Committee&&cat=nntds">NNTDS's Executive Committee</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-th"></i>
<span>Report Management</span>
</a>
<ul class="sub">
<li><a href="<?php echo base_url();?>report_manage">View Reports</a></li>
<li><a href="<?php echo base_url();?>ghatana">Ghatana Bibaran Management</a></li>
<!-- <li><a href="<?php echo base_url();?>view_cat_tables">View Categories Data Tables</a></li> -->
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-th"></i>
<span>Publication Management</span>
</a>
<ul class="sub">
<li><a href="<?php echo base_url();?>view_publication">Publication</a></li>
<!-- <li><a href="<?php echo base_url();?>view_cat_tables">View Categories Data Tables</a></li> -->
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-th"></i>
<span>Municipal Map</span>
</a>
<ul class="sub">
<li><a href="<?php echo base_url();?>map_show">Map Download Management</a></li>
<!-- <li><a href="<?php echo base_url();?>view_cat_tables">View Categories Data Tables</a></li> -->
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-th"></i>
<span>About Us</span>
</a>
<ul class="sub">
<li><a href="<?php echo base_url();?>view_about">About Management</a></li>
<!-- <li><a href="<?php echo base_url();?>view_cat_tables">View Categories Data Tables</a></li> -->
</ul>
</li>
<!-- <li class="sub-menu">
<a href="javascript:;">
<i class=" fa fa-bar-chart-o"></i>
<span>Layers</span>
</a>
<ul class="sub">
<li><a href="<?php echo base_url();?>layers_view">Layers</a></li>
<li><a href="chartjs.html">Chartjs</a></li>
<li><a href="flot_chart.html">Flot Charts</a></li>
<li><a href="c3_chart.html">C3 Chart</a></li>
</ul>
</li> -->
<?php if($admin==1){?>
<li class="sub-menu">
<a href="javascript:;">
<i class=" fa fa-bar-chart-o"></i>
<span>Site Management</span>
</a>
<ul class="sub">
<li><a href="site_setting">Site Setting</a></li>
<!-- <li><a href="vector_map.html">Vector Map</a></li> -->
</ul>
</li>
<?php } else{
} ?>
</ul>
</div>
<!-- sidebar menu end-->
</div>
</aside>
<file_sep>/application/models/Login_model.php
<?php
class Login_model extends CI_Model {
public function login($login_condition){
$result_set = $this->db->get_where("users",$login_condition);
if($result_set->num_rows()>0)
{
return $result_set->row_array();
}
else
{
return FALSE;
}
}
public function validate_user($password,$hash){
if(password_verify($password, $hash))
{
return TRUE;
} else{
return FALSE;
}
}
}
<file_sep>/application/views/admin/data_tables.php
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!-- page start-->
<div class="row">
<div class="col-sm-12">
<section class="panel">
<header class="panel-heading">
Data OF Table <?php echo $name ?>
<span class="tools pull-right">
<a href="csv_upload?tbl=<?php echo base64_encode($tbl_name)?>"><button type="submit" name="upload_data" class="btn btn-danger"><i class="fa fa-cloud-upload"></i> Upload Data </button></a>
</span>
</header>
<div class="panel-body">
<?php
$error= $this->session->flashdata('msg');
if($error){ ?>
<div class="alert alert-info alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Message!!!!</strong> <?php echo $error ; ?>
</div>
<?php
}
?>
<?php if($data == NULL){ ?>
<h4> NO Data </h4>
<?php }else{ ?>
<table class="table table-hover" id="tb1">
<thead>
<tr>
<td>Id</td>
<?php foreach($data_nep as $value){
if($value['nepali_lang']=='gid'){}else{
?>
<td>
<?php
echo $value['nepali_lang']
// $cleanname = explode("_", $key);
// foreach ($cleanname as $r) {
// echo ucfirst($r)." ";
// }?>
</td>
<?php } }?>
<td>
Operations
</td>
</tr>
</thead>
<tbody>
<?php foreach($data as $v ){ ?>
<tr>
<?php foreach($v as $key => $value) {
?>
<td><?php echo $value;?></td>
<?php } ?>
<td><a href="<?php echo base_url()?>edit?id=<?php echo base64_encode($v['id']);?>&& tbl=<?php echo base64_encode($tbl_name);?> ">Edit</a>/<a onclick="return confirm('Are you sure you want to delete?')" href="<?php echo base_url()?>delete_data?id=<?php echo $v['id'];?> && tbl=<?php echo $tbl_name;?>">Delete</a></td>
</tr>
<?php }?>
</tbody>
</table>
<?php }?>
<!-- table hidden start -->
<!-- <div class="col-sm-12">
<section class="panel">
<header class="panel-heading">
Download CSV format OF Table <?php echo $tbl_name?>
</header>
<span class="tools pull-center">
<div class="panel-body">
<p> Click below csv button to downlaod the empty table format to add data </p>
<table class="table table-hover" id="tb2" style="display:none" >
<thead>
<tr>
<?php foreach($data_nep as $value){
if($value['nepali_lang']=='id'){}else{
?>
<td>
<?php
echo($value['nepali_lang'])
?>
</td>
<?php }} ?>
</tr>
</thead>
<tbody>
<tr>
<?php for($i=0; $i<sizeof($fields);$i++){
if($fields[$i]=='id'){}else{
?>
<td></td>
<?php }} ?>
</tr>
</tbody>
</table>
</div>
</span>
</section>
</div> -->
<!-- table hidden end -->
</div>
</section>
</section>
</div>
</div>
</div>
<!-- page end-->
</section>
</section>
<!--main content end-->
<file_sep>/application/controllers/Admin/ProjectController.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ProjectController extends CI_Controller
{
function __construct()
{
parent::__construct();
if(($this->session->userdata('logged_in'))!=TRUE)
{
redirect('admin');
}else{
}
$this->load->helper('url');
$this->load->model('Project_model');
$this->load->model('Dash_model');
$this->load->library('form_validation');
}
public function add_proj(){
$this->form_validation->set_rules('proj_name','Name is required','required');
$this->form_validation->set_rules('proj_text','Name is required','required');
if($this->form_validation->run() == FALSE){
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/create_project');
$this->load->view('admin/footer');
}else{
$proj_name=$this->input->post('proj_name');
$proj_text=$this->input->post('proj_text');
$file_name = $_FILES['proj_pic']['name'];
//$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$img_upload=$this->Project_model->do_upload($file_name,$proj_name);
if($img_upload != ""){
$ext=$img_upload['upload_data']['file_ext'];
$image_path=base_url() . 'uploads/project_partner/'.$proj_name.$ext ;
$data=array(
'project_name'=>$proj_name,
'project_brief'=>$proj_text,
'project_pic'=>$image_path
);
$insert=$this->Project_model->add_proj('project_tbl',$data);
if($insert!=""){
// $table_name=$this->uri->segment(4);
// $this->body['id']=insert;
// $this->body['error']="New category ".$cat_name." created";
// $this->load->view('admin/header');
// $this->load->view('admin/create_categories',$this->body);
// $this->load->view('admin/footer');
$this->session->set_flashdata('msg', $proj_name.' project partner successfully added');
redirect('view_proj');
}else{
var_dump($insert);
}
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('add_proj');
}
}
}//
public function view_proj(){
$this->body['data']=$this->Project_model->get_proj('project_tbl');
$this->body['tbl_name']= 'project_tbl';
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/project_tbl',$this->body);
$this->load->view('admin/footer');
}
public function delete_data(){
$id=$this->input->get('id');
$tbl_name=$this->input->get('tbl');
$this->Dash_model->delete_data($id,$tbl_name);
$this->session->set_flashdata('msg','Id number '.$id.' row data was deleted successfully');
redirect('view_proj');
}
public function edit_proj(){
if(isset($_POST['submit'])){
//var_dump($_POST);
//unset($_POST['project_'])
//var_dump($_FILES);
$this->input->post('project_name');
$this->input->post('project_brief');
if( $_FILES['proj_pic']['name']==''){
$data= array(
'project_name'=>$this->input->post('project_name'),
'project_brief'=>$this->input->post('project_brief'),
);
$update=$this->Project_model->update_data($this->input->post('id'),$data);
if($update==1){
$this->session->set_flashdata('msg','Data successfully Updated');
redirect('view_proj');
}else{
//error
}
}else{
$proj_name=$this->input->post('project_name');
$file_name = $_FILES['proj_pic']['name'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$img_upload=$this->Project_model->do_upload($file_name,$proj_name);
if($img_upload==1){
$proj_name=$this->input->post('project_name');
$image_path=base_url() . 'uploads/project_partner/'.$proj_name.'.'.$ext ;
$data=array(
'project_name'=>$this->input->post('project_name'),
'project_brief'=>$this->input->post('project_brief'),
'project_pic'=>$image_path
);
$update=$this->Project_model->update_data($this->input->post('id'),$data);
if($update==1){
$this->session->set_flashdata('msg','Data successfully Updated');
redirect('view_proj');
}else{
//error
}
}else{
$code= strip_tags($img_upload['error']);
$this->session->set_flashdata('msg', $code);
redirect('view_proj');
}
}
}else{
$this->body['edit_data']=$this->Project_model->get_edit_data(base64_decode($this->input->get('id')),'project_tbl');
//admin check
$admin_type=$this->session->userdata('user_type');
$this->body['admin']=$admin_type;
//admin check
$this->load->view('admin/header',$this->body);
$this->load->view('admin/proj_edit',$this->body);
$this->load->view('admin/footer');
}
}
public function test_arr(){
$tbl=array(
'article','project_tbl','categories_tbl',
);
for($i=0;$i<sizeof($tbl);$i++){
$data=$this->Project_model->get_proj($tbl[$i]);
var_dump($dsta.'<br>');
}
$this->load->view('admin/arr.php',$this->body);
}
}//end
|
fb01d48f423aaeaca12d0296d6a7b84cf0c00a9c
|
[
"PHP"
] | 47 |
PHP
|
naxadeve/vso
|
1a2c697c1a66c9b187b32a9db327d7cdc2f4529a
|
9c9f9b6ba2f2ba82c0c3cbdbb503d79776d156ee
|
refs/heads/master
|
<repo_name>adhiiisetiawan/stack-widget<file_sep>/README.md
# stack-widget
Simple stack widget in android
<file_sep>/app/src/main/java/com/example/simplestackwidget/StackRemoteViewsFactory.java
package com.example.simplestackwidget;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import java.util.ArrayList;
import java.util.List;
public class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private final List<Bitmap> widgetItems = new ArrayList<>();
private final Context context;
StackRemoteViewsFactory(Context context){
this.context = context;
}
@Override
public void onCreate() {
}
@Override
public void onDataSetChanged() {
widgetItems.add(BitmapFactory.decodeResource(context.getResources(), R.drawable.darth_vader));
widgetItems.add(BitmapFactory.decodeResource(context.getResources(), R.drawable.star_wars_logo));
widgetItems.add(BitmapFactory.decodeResource(context.getResources(), R.drawable.storm_trooper));
widgetItems.add(BitmapFactory.decodeResource(context.getResources(), R.drawable.starwars));
widgetItems.add(BitmapFactory.decodeResource(context.getResources(), R.drawable.falcon));
}
@Override
public void onDestroy() {
}
@Override
public int getCount() {
return widgetItems.size();
}
@Override
public RemoteViews getViewAt(int i) {
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_item);
rv.setImageViewBitmap(R.id.img_view, widgetItems.get(i));
Bundle extras = new Bundle();
extras.putInt(ImageBannerWidget.EXTRA_ITEM, i);
Intent fillIntent = new Intent();
fillIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.img_view, fillIntent);
return rv;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public boolean hasStableIds() {
return false;
}
}
|
82b742b8b8e1f53314648fb0bf3e6b4103cd11a1
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
adhiiisetiawan/stack-widget
|
52a159b334c849b040fe0486214ae2d6b53d918d
|
7c222547d71dfc91ea230c92ae67f46afa096611
|
refs/heads/master
|
<file_sep>plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.amazonaws:aws-lambda-java-core:1.2.0'
implementation 'com.amazonaws:aws-lambda-java-events:2.2.7'
// https://mvnrepository.com/artifact/software.amazon.awssdk/bom
implementation 'software.amazon.awssdk:bom:2.10.25'
implementation 'software.amazon.awssdk:regions:2.4.3'
implementation 'software.amazon.awssdk:s3:2.10.27'
testImplementation 'junit:junit:4.12'
}
<file_sep>package com.techceed.example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class NoActionFunction implements RequestHandler<Object, Object> {
public Object handleRequest(final Object input, final Context context) {
System.out.println(input.toString());
return "成功!";
}
}<file_sep>#!/bin/bash
# lambda functionに対してS3のイベントを設定するサンプル
# lambda functionのARN
FUNCARN="${FUNCARN:?}"
# イベントのID
EVENT_ID="${EVENT_ID:-"ExampleEventsName"}"
# S3バケット名
S3_BUCKET_NAME="${S3_BUCKET_NAME:?}"
JSON=$(cat <<-EOF
{
"LambdaFunctionConfigurations": [
{
"Id": "${EVENT_ID}",
"LambdaFunctionArn": "${FUNCARN}",
"Events": [ "s3:ObjectCreated:*" ],
"Filter": {
"Key": {
"FilterRules": [{
"Name": "prefix",
"Value": "upload/"
}]
}
}
}
]
}
EOF
)
aws s3api \
put-bucket-notification-configuration \
--bucket="${S3_BUCKET_NAME}" \
--notification-configuration "${JSON}"
<file_sep># example-aws-lambda-sam-java
AWS Lambda / AWS SAM / AWS SAM Local のサンプルプロジェクトです。
Java / Gradle前提です。
| lambda関数 | 内容 |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| HelloWorldFunction | `sam init`で生成されるlambda関数 |
| UploadTriggerFunction | S3へのファイルアップロードイベントをトリガとして起動する想定のlambda関数 |
| S3ManipulateFunction | S3上のファイル操作を行う |
| InvokeLambdaFunction | 環境変数`FUNCTION_NAME`で設定したlambda関数名のlambda関数を起動する。この例では`FUNCTION_NAME`のデフォルトは`NoActionFunction`としている |
| NoActionFunction | 何もしない。InvokeLambdaFunctionから呼び出されるスタブ。 |
## 前提
- JDKが導入されていること
- `AWS CLI`が導入されていること
- `aws cli config`コマンドを実行して`AWS CLI`が設定されていること
- `SAM CLI`が導入されていること
- ローカル実行を行う場合、Dockerが導入されていること
- 使用するS3バケット、IAM Roleが存在すること
## ビルド・デプロイ
1. `samconfig.toml.sample`を`samconfig.toml`にリネームし、`要変更`の部分を環境に合わせて編集する
2. `template.yaml.sample`を`template.yaml`にリネームし、`要変更`の部分を環境に合わせて編集する
3. `sam build`コマンドでビルド
4. `sam deploy`でAWS環境へデプロイ(※デプロイしなくとも後述の方法でローカルで実行可能)
## `sam local`でのローカル実行
Dockerが導入されている場合、`sam local invoke`コマンドでローカル実行が可能。
但し、依存するリソースを再現するわけではないので注意。あくまでlambda部分のみ。
| 実行コマンド | 備考 |
| ---------------------------------------------------------- | -------------------------------------------------------------------- |
| `sam local invoke UploadTriggerFunction -e events/s3.json` | `./events/s3.json`の内容をイベントとして渡す |
| `sam local invoke S3ManipulateFunction` | S3バケットはAWS側に必要 |
| `sam local invoke NoActionFunction` | |
| `sam local invoke InvokeLambdaFunction` | ローカルで動かす際も`NoActionFunction`がデプロイされている必要がある |
<file_sep>plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.amazonaws:aws-lambda-java-core:1.2.0'
implementation 'com.amazonaws:aws-lambda-java-events:2.2.7'
implementation 'software.amazon.awssdk:bom:2.10.25'
implementation 'software.amazon.awssdk:regions:2.4.3'
implementation 'software.amazon.awssdk:lambda:2.10.30'
testImplementation 'junit:junit:4.12'
}
// デプロイ済みのlambda関数をinvokeする想定のため、未デプロイの場合にbuildがfailするので無視する
test {
ignoreFailures = true
}
|
8f145ddd18aae6fa8f200848bcf894193ce72e59
|
[
"Markdown",
"Java",
"Shell",
"Gradle"
] | 5 |
Gradle
|
yamada-a/toppan-dp-smap
|
8352cdd4aeb9ca6e1a8feae61f8ee02fbe092de2
|
7f7f46a463f9b26cf3233d73a3015a44043dd09a
|
refs/heads/master
|
<repo_name>ghesketh76/palmares-be<file_sep>/app/controllers/refresh_tokens_controller.rb
class RefreshTokensController < ApplicationController
def show
@refresh_token = RefreshToken.find(params[:user_id])
render json: @refresh_token
end
def create
@refresh_token = RefreshToken.create(
user_id: params[:user_id],
refresh_token: params[:refresh_token],
scope: params[:scope]
)
render json: @refresh_token, status: :created
end
end
<file_sep>/app/controllers/scores_controller.rb
class ScoresController < ApplicationController
def index
@score = Score.all
render json: @score, include: :user
end
def create
@score = Score.create(user_id: params[:user_id], score: params[:score])
render json: @score
end
def non_user_scores
@scores = Score.all.filter do |score|
score.user_id != @user.id
end
render json: @scores, include: :user
end
end
<file_sep>/app/controllers/access_tokens_controller.rb
class AccessTokensController < ApplicationController
def show
@access_token = AccessToken.all
render json: @access_token
end
def create
@access_token = AccessToken.create(
user_id: params[:user_id],
scope: params[:scope],
access_token: params[:access_token],
expires_at: params[:expires_at]
)
render json: @access_token, status: :created
end
def update
@access_token = AccessToken.find(params[:user_id])
@access_token.update(access_token: params[:access_token], expires_at: params[:expires_at])
render json: @access_token, status: :reset_content
end
end
|
2bfb90100852e6f17b766e408e66d56888c1525b
|
[
"Ruby"
] | 3 |
Ruby
|
ghesketh76/palmares-be
|
4eb56ee05408ba0b67b2069cf4b65ee1c82b8615
|
6e720a4e889e5d60dca6b25ca59442683a386c7a
|
refs/heads/master
|
<repo_name>angeal185/tweekdb<file_sep>/lib/enc.js
const crypto = require('crypto');
const enc = {
encrypt: function(text, key, defaults) {
try {
const iv = crypto.randomBytes(defaults.iv_len),
cipher = crypto.createCipheriv(
[defaults.cipher, defaults.bit_len, defaults.mode].join('-'),
Buffer.from(key, defaults.encode),
iv,
{authTagLength: defaults.tag_len}
),
encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
let final;
if(['gcm', 'ocb', 'ccm'].indexOf(defaults.mode) !== -1){
final = [iv, cipher.getAuthTag(), encrypted]
} else {
final = [iv, encrypted]
}
return Buffer.concat(final).toString(defaults.encode);
} catch (err) {
if (err) {
console.error(err);
return undefined;
}
}
},
decrypt: function(encdata, key, defaults) {
try {
encdata = Buffer.from(encdata, defaults.encode);
const decipher = crypto.createDecipheriv(
[defaults.cipher, defaults.bit_len, defaults.mode].join('-'),
Buffer.from(key, defaults.encode),
encdata.slice(0, defaults.iv_len),
{authTagLength: defaults.tag_len}
);
if(['gcm', 'ocb', 'ccm'].indexOf(defaults.mode) !== -1){
let tag_slice = defaults.iv_len + defaults.tag_len;
decipher.setAuthTag(encdata.slice(defaults.iv_len, tag_slice));
return decipher.update(encdata.slice(tag_slice), 'binary', 'utf8') + decipher.final('utf8');
} else {
return decipher.update(encdata.slice(defaults.iv_len), 'binary', 'utf8') + decipher.final('utf8');
}
} catch (err) {
if (err) {
console.error(err);
return undefined;
}
}
},
hash: function(data, digest, encode) {
if(typeof data !== 'string'){
data = JSON.stringify(data)
}
return crypto.createHash(digest).update(data).digest(encode)
},
hmac: function(data, secret, digest, encode) {
if(typeof data !== 'string'){
data = JSON.stringify(data)
}
return crypto.createHmac(digest, Buffer.from(secret, encode).toString()).update(data).digest(encode)
},
uuidv4: function() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, function(c){
return (c ^ crypto.randomBytes(1)[0] & 15 >> c / 4).toString(16)
});
},
keygen: function(keylen, iterations, digest, encode){
let secret = crypto.randomBytes(keylen)
return crypto.pbkdf2Sync(
crypto.randomBytes(keylen),
crypto.randomBytes(keylen),
iterations, keylen, digest
).toString(encode)
},
rnd: function(len,enc){
return crypto.randomBytes(len).toString(enc);
}
}
module.exports = enc;
<file_sep>/README.md
# tweekdb
The flat-file, in-memory, remote-sync or hybrid db that is as lightning fast as you configure it to be.
![cd-img] ![dep-img] ![syn-img] ![sz-img]
[![NPM Version][npm-img]][npm-url] ![lic-img]
#### [Live playground](https://runkit.com/angeal185/tweekdb)
## Installation
npm
```sh
$ npm install tweekdb --save
```
git
```sh
$ git clone https://github.com/angeal185/tweekdb.git
```
## setup
```js
const { tweek, tweekdb } = require('tweekdb');
//minimal base setup example
const db = tweek(new tweekdb('./db'));
//minimal cache only setup example
const db = tweek(new tweekdb());
//complete custom base setup example
const db = tweek(new tweekdb('./db',{
//add custom db serialize function
serialize: function(data){
return Buffer.from(JSON.stringify(data), 'utf8').toString('base64')
},
//add custom db deserialize function
deserialize: function(data){
return JSON.parse(Buffer.from(data, 'base64').toString())
},
//default db schema ~ overrides config file settings
schema: {
array: [],
object:{},
key: 'value'
},
//custom cron job entry point
cron: function(current_db_state){
console.log(JSON.stringify(current_db_state))
},
//enable db encryption ~ overrides config file settings
encryption: false,
//enable db backup ~ overrides config file settings
backup: false,
//enable db gzip ~ overrides config file settings
gzip: false,
//remote db fetch settings ~ overrides config file settings
fetch_config: {
hostname: "",
port: 443,
path: "",
method: "GET",
headers:{}
},
//remote db sync settings ~ overrides config file settings
sync_config {
hostname: "",
port: 443,
path: "",
method: "POST",
headers:{}
},
}));
//multiple db can be created with different configurations like so:
const db1 = tweek(new tweekdb('./db1',{
backup: false,
encryption: false,
gzip: true
}));
const db2 = tweek(new tweekdb('./db2',{
backup: true,
encryption: true,
gzip: false,
schema: {
array: []
}
}));
//create config file in cwd
db.clone_config();
```
## config
```js
{
"settings": {
"verbose": true, //log to console
"dev": true, //development mode
"lodash_path": "lodash", //require path to lodash or custom lodash
"noconflict": false, // fixes lodash conflict issues at a cost
"crypto_utils": true // enable extra crypto utils
},
"backup": { //db backup config
"enabled": false,
"ext": "tmp", //db backup file extention
"pre": "." //db backup file prefix
},
"turbo": { // turbo mode config
"enabled": true,
"ms": 5 // debounce delay in milliseconds
},
"cron": { // cronjobs config
"enabled": false,
"ms": 10000 // cron task interval in milliseconds
},
"fetch": { // remote db fetch config
"enabled": true,
"config": { // accepts all nodejs https config options
"hostname": "",
"port": 443,
"path": "",
"method": "GET",
"headers":{}
// optional key/cert/pfx as path relative to cwd() ~ ./demo.cert
}
},
"sync": {// remote db save config
"enabled": false,
"config": { // accepts all nodejs https config options
"hostname": "",
"port": 443,
"path": "",
"method": "POST",
"headers":{}
// optional key/cert/pfx as path relative to cwd() ~ ./demo.pfx
}
},
"gzip":{ // db gzip config
"enabled": false, // gzip db
"backup": true, // gzip db backup
"settings":{
"level": 9,
"memLevel": 9,
"strategy": 0
}
},
"hmac": {
"secret": "", // hmac secret (encoded with hmac.encode)
"encode": "hex", // hmac/hash encoding
"digest": "sha512" // hmac/hash digest sha256/sha384/sha512
//sha3-256/sha3-384/sha3-512
},
"encryption":{
"enabled": false,
"secret": "", // encryption secret (encoded with encryption.settings.encode)
"secret_len": 32, // secret length 16/24/32
"iterations": 60000, // pbkdf2 iterations
"settings": {
"cipher": "aes", // encryption cipher aes/camellia/aria
"bit_len": "256", // 128/192/256
"iv_len": 32, // encryption iv length
"tag_len": 16, // encryption tag length
"encode": "hex", // encryption encoding
"mode": "gcm", // gcm/cbc/ccm/ctr/cfb/cfb1/cfb8/ocb/ofb
"digest": "sha512" // keygen digest sha256/sha384/sha512
//sha3-256/sha3-384/sha3-512 ...
}
},
"static":{ //db static file generator options
"enabled": true,
"dest": "./" //static file dest
},
"schema": {} //default db schema
}
```
## config file
the tweekdb config file can be generated by calling `db.clone_config()` and will create a `tweekdb.json` in your working directory. without this config file, settings will fall back to their defaults. this file is key to optimizing your db. should you have more than one db using the same config file, certain overrides can be set when calling `new tweekdb('./db', overrides)`. by default the config file is set for speed optimization with most features disabled.
## backup mode
the `config.backup` setting will enable db backups on save() and load from the backup file in the unlikely event of data corruption to the db. this setting can be used in conjunction with `config.gzip` to compress your backups. if you are using a large sized db `config.turbo` is recommended. db backups can also be called manually. this method is non blocking.
## turbo mode
the `config.turbo` setting will debounce file writes in a non blocking way within the time-frame that you specify. for example, if you set `config.turbo.ms` to 100, all calls to .save() will have .val() stored to cache but the file write will be debounced for 100ms. if another call to .save() is detected within 100ms, the timeframe is reset and write is debounced again. out of all the consecutive writes you receive within 100ms of each other, only the last write will be written. this process is non blocking and will return/callback to the user at the point of .val() being updated. the speed gains of this feature should theoretically grow with the size of your db.
## encryption
tweekdb supports encryption out of the box and can be configured at `config.encryption`. prior to enabling this feature an appropriately sized encryption key must be generated with the appropriate encoding. this can be created and returned by calling `db.keygen()`. this method is non blocking when used in conjunction with `config.turbo`.
## gzip
the `config.gzip` setting will enable db compression should you wish to compress your db and or backup. if you are using a large sized db `config.turbo` is recommended. this method is non blocking when used in conjunction with `config.turbo`.
## cron
the `config.cron` setting will enable you to set a recurring cron job to be carried out at the inteval in milliseconds you specify at `config.cron.ms`. the cron function has one arg which the current state of the db. an example function can be found in the settings section.
## serialize/deserialize
by default, tweekdb will serialize/deserialize valid json. this can be customized via the serialize/deserialize functions so that tweekdb will serialize/deserialize from and to any format and or encoding.
for example:
```js
// store db as json pretty
const db = tweek(new tweekdb('./db.json',{
serialize: function(data){
return JSON.stringify(data,0,2)
}
}));
// store db as byte array
const db = tweek(new tweekdb('./db',{
deserialize: function(data){
return JSON.parse(Buffer.from(JSON.parse(data)).toString())
},
serialize: function(data){
return JSON.stringify(Array.from(Buffer.from(JSON.stringify(data))))
}
}));
// store db hex encoded
const db = tweek(new tweekdb('./db',{
serialize: function(data){
return Buffer.from(JSON.stringify(data), 'utf8').toString('hex')
},
deserialize: function(data){
return JSON.parse(Buffer.from(data, 'hex').toString())
}
}))
```
## lodash
tweekdb is built using lodash. should you wish, you can create your own filtered lodash module and update the require() path at `config.settings.lodash_path`.
tweekdb uses all the same chain-able methods as lodash. be mindful that many of these methods will mutate your items in place while others will return a new item.
for example:
```js
{
"array": [1,2,3,4,5]
}
// remove value 2 from the array and mutates the array.
// this action will update the db cache
db.get('array').pull(2).val()
console.log(db.get('array').val()) // [1,3,4,5]
// remove value 2 from the array but returns a new array
// this action will not update the db cache but will return
// a new array without 2
let x = db.get('array').without(2).val()
console.log(db.get('array').val()) // [1,2,3,4,5]
console.log(x) // [1,3,4,5]
db.set('array',x).val()
console.log(db.get('array').val()) // [1,3,4,5]
```
## examples
```js
// db.load/db.fetch/db.cache will store your db to cache and should only be called once.
// db load from file to cache sync
db.load();
//db load from file to cache async
db.load(function(err, data){
if(err){return console.error(err)};
// db. in now available outside of this scope
console.log(data.val())
});
//load remode db to cache using the settings in your config file
db.fetch(function(err,data){
if(err){return console.error(err)}
// db. in now available outside of this scope
console.log(data.val())
})
//manually set db cache from any source
db.cache({
test: "scema"
})
// calling .save() will update cache state as well as write state to file.
// calling .val() will update only the cache state.
//save cached db state to file sync
db.save();
//save cached db state to async
db.save(function(err){
if(err){return console.error(err)};
});
//save a remode db using the settings in your config file
db.sync(function(err){
if(err){return console.error(err)}
console.log('done')
})
// add defaults to base db schema and save state to cache.
db.defaults({
collection:[{"test":"ok"}],
array:[],
key: 'val'
}).val()
// add defaults to base db schema and save state to db file.
db.defaults({
collection:[{"test":"ok"}],
array:[1,2,3,4,5],
key: 'val'
}).save()
// create a key val pair and save state to cache.
db.set('key', 'value').val();
// create an array named array and save state to cache.
db.set('array', []).val();
// create a collection named collection
db.set('collection', [{test:'working'}]).val();
// create object and save state to cache
db.set('obj', {test:'working'}).val()
// append an object to a collection
db.get('collection').push({ id: db.uuid()}).val()
// append a value then prepend a value to an array
db.get('array').push(1).unshift(2).val()
// prepend an object to a collection
db.get('collection').unshift({ id: db.uuid()}).val()
// prepend a value and append a value to an array
db.get('collection').unshift({ id: db.uuid()}).push({ id: db.uuid()}).val()
// remove an object from a collection and add a new object
db.get('collection').remove({"test":"working"}).push({"test":"working2"}).val()
// remove a value from an array and append a new value
db.get('array').pull('test').unshift('test2').val()
// find an object in a collection
console.log(
db.get('collection').find({"test":"working"}).val()
) // {test:'working'}
// find index of an object in a collection
console.log(
db.get('collection').findIndex({"test":"working"}).val()
) // 0
// return first item in a collection or array
console.log(
db.get('array').head().val()
) // 1
// return first item in a collection or array
console.log(
db.get('array').tail().val()
) // 5
// return last item in a collection or array
console.log(
db.get('collection').head().val()
) // {test:'working'}
```
## static method
tweekdb can also be used as a dev tool to generate json files by calling `.static('filename')`
from your db items.
```js
db.set('blog_posts', [{
id: 1,
title: "post 1",
author: "x",
},{
id: 2,
title: "post 2",
author: "x"
},{
id: 3,
title: "post 3",
author: "x"
},{
id: 4,
title: "post 4",
author: "x"
},{
id: 5,
title: "post 5",
author: "x"
}]
)
// create a json file for each post in the config.static.dest folder
let x = db.get('blog_posts').val();
for (let i = 0; i < x.length; i++) {
db.get('blog_posts['+ i +']').static('post_'+ x[i].id)
}
```
## utils
`config.settings.crypto_utils` will add the following utils to the build.
```js
//create config file in cwd
db.clone_config();
//create new cryptographically secure secret
db.keygen();
//generate uuidv4
db.uuid();
/**
* encrypt a string
* @param {string} data ~ data to be encrypted
* @param {string} secret ~ optional / fallback to config file
**/
db.encrypt(data,secret);
/**
* decrypt a string
* @param {string} data ~ data to be encrypted
* @param {string} secret ~ optional / fallback to config file
**/
db.decrypt(data,secret);
/**
* hmac a string
* @param {string} data ~ data for hmac
* @param {string} secret ~ optional / fallback to config file
**/
db.hmac(data,secret)
/**
* hash a string
* @param {string} data ~ data for hash
**/
db.hash(data);
/**
* random bytes
* @param {integer} len ~ length
* @param {string} encode ~ hex/base64 ...
**/
db.rnd(len,encode)
```
## mixins
you can create your own custom chain-able methods using `db._.mixin()`;
```js
// mixin to replace an object within a collection
db._.mixin({
replaceRecord: function(arr, current_object, new_object) {
return arr.splice( _.findIndex(arr, current_object), 1, new_object)
}
})
// use mixin like so.
db.get('collection').replaceRecord({"test":"working"}, {"test":"working2"}).val();
```
[cd-img]: https://app.codacy.com/project/badge/Grade/526610b860784ec08094f0c0b1b8f907
[npm-img]: https://badgen.net/npm/v/tweekdb?style=flat-square
[dep-img]:https://badgen.net/david/dep/angeal185/tweekdb?style=flat-square
[sz-img]:https://badgen.net/packagephobia/publish/tweekdb?style=flat-square
[lic-img]: https://badgen.net/npm/license/tweekdb?style=flat-square
[syn-img]: https://snyk.io.cnpmjs.org/test/npm/tweekdb
[npm-url]: https://npmjs.org/package/tweekdb
<file_sep>/index.js
const fs = require('fs'),
zlib = require('zlib'),
utils = require('./lib/utils'),
enc = require('./lib/enc');
let config,
cwd = process.cwd(),
cnf_url = cwd + '/tweekdb.json';
try {
config = require(cnf_url);
utils.cl(config.settings.verbose,['init','config file found.'],96);
} catch (err) {
config = require('./config');
utils.cl(config.settings.verbose,['init','config file not found, loading defaults.'],96);
}
Object.freeze(config);
const vb = config.settings.verbose,
lp = config.settings.lodash_path;
let _ = require(lp);
if(config.settings.noconflict){
_ = _.runInContext();
}
function tweekdb(src, cnf){
cnf = cnf || {};
this.src = src;
this.schema = cnf.schema || config.schema;
this.serialize = cnf.serialize || JSON.stringify;
this.deserialize = cnf.deserialize || JSON.parse;
this.cron = cnf.cron || null;
this.encryption = cnf.encryption || config.encryption.enabled;
this.backup = cnf.backup || config.backup.enabled;
this.gzip = cnf.gzip || config.gzip.enabled;
this.gzip_backup = config.gzip.backup;
if(config.static.enabled){
this.static_dest = config.static.dest;
}
if(config.fetch.enabled){
this.fetch_config = cnf.fetch_config || config.fetch.config;
}
if(config.sync.enabled){
this.sync_config = cnf.sync_config || config.sync.config;
}
if(this.encryption){
this.secret = config.encryption.secret || null;
this.enc_cnf = config.encryption.settings || null;
}
if(this.backup){
this.backup_pre = config.backup.pre || '.';
this.backup_ext = config.backup.ext || 'tmp';
}
}
tweekdb.prototype = {
load: function(cb) {
let src = this.src,
data;
if(!cb){
try {
data = fs.readFileSync(src);
data = utils.check_read(this, data, config);
utils.cl(vb,['status','db '+ src +' cached and ready.'],96);
return this.deserialize(data);
} catch(e) {
utils.cl(vb,['warning','unable to load data, creating new...'],91);
try {
data = fs.readFileSync(this.backup_pre + src +'.'+ this.backup_ext);
data = utils.check_read(this, data, config);
utils.cl(vb,['status','db '+ src +' backup cached and ready.'],96);
return data ? this.deserialize(data) : this.schema;
} catch (err) {
data = this.serialize(this.schema);
if(this.encryption){
data = enc.encrypt(data, this.secret, this.enc_cnf);
}
if(this.gzip){
data = zlib.gzipSync(data, config.gzip.settings);
}
fs.writeFileSync(src, data);
utils.cl(vb,['status','new db '+ src +' cached and ready.'],96);
return this.schema;
}
}
} else {
let $this = this;
fs.readFile(src, function(err,data){
if(err){
fs.readFile(this.backup_pre + src +'.'+ this.backup_ext, function(err, res){
if(err){
data = $this.serialize($this.schema);
if($this.encryption){
data = enc.encrypt(data, $this.secret, $this.enc_cnf);
}
if($this.gzip){
data = zlib.gzipSync(data, config.gzip.settings);
}
fs.writeFileSync(src, data);
cb(false, $this.schema);
utils.cl(vb,['status','new db '+ src +' cached and ready.'],96);
return
}
if($this.gzip || this.gzip_backup){
res = zlib.unzipSync(res, config.gzip.settings);
}
res = res.toString('utf8');
if($this.encryption){
res = enc.decrypt(res, $this.secret, $this.enc_cnf);
}
cb(false, $this.deserialize(res));
utils.cl(vb,['status','db '+ src +' backup cached and ready.'],96);
});
} else {
data = utils.check_read($this, data, config);
cb(false, $this.deserialize(data));
utils.cl(vb,['status','db '+ src +' cached and ready.'],96);
}
})
}
},
save: function(data, cb) {
let src = this.src;
data = utils.check_write(this, data, config);
if(!cb){
let res = fs.writeFileSync(src, data);
utils.write_backup(this, data, config);
if(!config.turbo.enabled){
return res;
}
} else {
let $this = this;
fs.writeFile(src, data, function(err){
if(!config.turbo.enabled){
if(err){return cb(err)}
cb(false)
} else {
if(err){
return utils.cl(vb,['error','Turbo file write failed'],91);
}
}
utils.write_backup($this, data, config);
})
}
},
set_backup: function(data, cb) {
let dest = config.backup.pre + this.src +'.'+ config.backup.ext;
data = utils.check_write(this, data, config);
if(!cb){
return fs.writeFileSync(dest, data);
}
fs.writeFile(dest, data, function(err){
if(err){return cb(err)}
cb(false)
})
},
cron_job: function(db){
this.cron(db)
}
}
if(config.static.enabled){
tweekdb.prototype.static = function(data, title, cb){
if(typeof data !== 'string'){
data = JSON.stringify(data)
}
let dest = this.static_dest + title + '.json';
if(!cb){
return fs.writeFileSync(dest, data);
} else {
fs.writeFile(dest, data, function(err){
if(err){return cb(err)}
cb(false)
})
}
}
}
if(config.fetch.enabled){
tweekdb.prototype.fetch = function(cb){
let $this = this,
arr = ['key','cert','pfx'];
for (let i = 0; i < arr.length; i++) {
if(this.fetch_config[arr[i]]){
this.fetch_config[arr[i]] = fs.readFileSync(this.fetch_config[arr[i]])
if(arr[i] === 'ca'){
this.fetch_config[arr[i]] = [this.fetch_config[arr[i]]]
}
}
}
utils.req($this, 'fetch_config', config, function(err,data){
if(err){return cb(err)}
try {
if($this.encryption){
data = enc.decrypt(data, $this.secret, $this.enc_cnf);
}
data = $this.deserialize(data);
cb(false, data);
utils.cl(vb,['status','db from '+ $this.fetch_config.hostname +' cached and ready.'],96);
} catch (err) {
throw err;
}
})
}
}
if(config.sync.enabled){
tweekdb.prototype.sync = function(body, cb){
let $this = this,
arr = ['key','cert','pfx'];
if(typeof body !== 'string'){
try {
body = JSON.stringify(body);
} catch (err) {
return cb('invalid sync data')
}
}
if(this.encryption){
body = enc.encrypt(body, this.secret, this.enc_cnf);
}
for (let i = 0; i < arr.length; i++) {
if(this.sync_config[arr[i]]){
this.sync_config[arr[i]] = fs.readFileSync(this.sync_config[arr[i]])
if(arr[i] === 'ca'){
this.sync_config[arr[i]] = [this.sync_config[arr[i]]]
}
}
}
this.sync_config.headers['Content-Length'] = body.length;
utils.req($this, 'sync_config', config, function(err,data){
if(err){return cb(err)}
try {
data = $this.deserialize(data);
cb(false, data);
utils.cl(vb,['status','db from '+ $this.sync_config.hostname +' cached and ready.'],96);
} catch (err) {
throw err;
}
})
}
}
function tweek(src) {
const db = _.chain({});
_.prototype.save = _.wrap(_.prototype.value, function(func, cb) {
if(!cb){
return db.save(func.apply(this))
} else {
db.save(func.apply(this), function(err,res){
if(err){return cb(err)}
cb(false,res)
})
}
})
if(config.static.enabled){
_.prototype.static = _.wrap(_.prototype.value, function(func, title, cb) {
if(!cb){
return src.static(func.apply(this), title)
} else {
src.static(func.apply(this), title, function(err,res){
if(err){return cb(err)}
cb(false,res)
})
}
})
}
_.prototype.val = _.prototype.value
function set_state(state) {
db.__wrapped__ = state
return db
}
db._ = _
db.load = function(cb){
if(!cb){
return set_state(src.load())
} else {
src.load(function(err,data){
if(err){return cb(err)}
cb(false, set_state(data))
})
}
}
if(config.fetch.enabled){
db.fetch = function(cb){
src.fetch(function(err,data){
if(err){return cb(err)}
cb(false, set_state(data))
})
}
}
if(config.sync.enabled){
db.sync = function(cb){
src.sync(db.val(), cb)
}
}
db.save_state = function(data, cb){
if(!cb){
src.save(db.val());
return data;
} else {
src.save(db.val(), function(err){
if(err){return cb(err)}
cb(false, data)
})
}
}
db.backup = function(cb){
return src.set_backup(db.val(), cb);
}
if(config.turbo.enabled){
let timeout;
db.save = function(data, cb) {
const later = function() {
timeout = null;
db.save_state(data, cb)
};
if(!timeout || typeof timeout === 'object'){
clearTimeout(timeout);
timeout = setTimeout(later, config.turbo.ms);
if(typeof timeout === 'object'){
if(cb){
return cb(false)
}
return true
}
}
}
} else {
db.save = db.save_state;
}
db.cache = function(state){
return set_state(state);
}
if(config.settings.crypto_utils){
let cnf_enc = config.encryption;
db.hmac = function(data, secret){
return enc.hmac(data, secret, config.hmac.digest, config.hmac.encode);
}
db.hash = function(data){
return enc.hash(data, config.hmac.digest, config.hmac.encode);
}
db.uuid = enc.uuidv4;
db.rnd = enc.rnd;
db.encrypt = function(data, secret){
if(!secret){
secret = cnf_enc.secret;
}
return enc.encrypt(data, secret, cnf_enc.settings);
}
db.decrypt = function(data, secret){
if(!secret){
secret = cnf_enc.secret;
}
return enc.decrypt(data, cnf_enc.secret, cnf_enc.settings);
}
db.keygen = function(){
return enc.keygen(
cnf_enc.secret_len,
cnf_enc.iterations,
cnf_enc.settings.digest,
cnf_enc.settings.encode
)
}
}
if(config.settings.dev){
db.clone_config = function(){
fs.writeFileSync(cnf_url, JSON.stringify(config,0,2))
}
}
if(config.cron.enabled){
utils.cl(vb,['build','initializing cron tasks...'],96);
setInterval(function(){
src.cron_job(db.value())
},config.cron.ms)
}
utils.cl(vb,['build','build status success.'],96);
return db;
}
module.exports = { tweek, tweekdb }
|
bc694b570ba0f8f12cd30467bf3266a73579dee4
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
angeal185/tweekdb
|
523e6ac8e1c0d6487db4128de9088a8750b060de
|
0e3272dba590dd861a049aa88ff86e332aab7749
|
refs/heads/master
|
<file_sep>$(document).ready(function () {
// document.getElementById("message").
$('#message').popup('show');
});
|
d1587815ead749f6c466690dbc16c45891816d5d
|
[
"JavaScript"
] | 1 |
JavaScript
|
GondarOleg/homework13
|
7a9fcf09c4286453b3f269f9cc5a03fb70b974c9
|
23baf233d525c707ca1cb331a18dca513dc6fac1
|
refs/heads/master
|
<file_sep># vose-lua
----
lua module implements Vose's Alias Method as described here http://www.keithschwarz.com/darts-dice-coins/
This algorithm can be used to efficiently find weighted random data ex. rolling a weighted dice.
### How to use
```Lua
local Vose = require("PATH_TO_VOSE/vose")
local result = Vose({
ele_1 = 25, -- element = weight
ele_2 = 35, -- element = weight
ele_3 = 45
}):get()
```
----
Vose的Alias算法的lua实现,参考的是 http://www.keithschwarz.com/darts-dice-coins/ 。
这是一个高效的用来计算加权随机结果的算法,比如说,一个有掉率的宝箱应该掉落什么?
### 使用方法
```Lua
local Vose = require("PATH_TO_VOSE/vose")
local result = Vose({
ele_1 = 25, -- 元素 = 权重
ele_2 = 35,
ele_3 = 45
}):get()
```
<file_sep>--[[
This lua module implements Vose's Alias Method as described
here http://www.keithschwarz.com/darts-dice-coins/ . This algorithm
can be used to efficiently find weighted random data ex. rolling a
weighted dice.
-- Usage
local Vose = require('PATH_TO_VOSE/Vose')
local result = Vose({
element_1 = 25, -- element_name = drop_rate
element_2 = 35,
element_3 = 55
})
-- test
-- local plist = {
-- a = 25,
-- b = 65,
-- c = 10
-- }
-- local v = Vose(plist)
-- local r = {}
-- for i = 1, 1000 do
-- local res = v:get()
-- r[res] = r[res] or 0
-- r[res] = r[res] + 1
-- end
-- for k,v in pairs(r) do
-- print(k,v)
-- end
Created on 2016.1.15
@author XavierCHN
]]
local Vose = {}
Vose.__index = Vose
setmetatable(Vose, Vose)
local function tablecount(t)
local c = 0
for _ in pairs(t) do
c = c + 1
end
return c
end
function Vose.__call(self, plist)
local probs = {}
for k,v in pairs(plist) do
table.insert(probs, {k, v})
end
local sum = 0
local count = 0
-- Normalize probabilities
for _, prob in pairs(probs) do
sum = sum + prob[2]
count = count + 1
end
for _, prob in pairs(probs) do
prob[2] = prob[2] / sum
end
local n = #probs
local alias = {}
local prob = {}
local small = {}
local large = {}
for _, prob in pairs(probs) do
prob[2] = prob[2] * n
if prob[2] < 1 then
table.insert(small, prob)
else
table.insert(large, prob)
end
end
if large == {} then
large, small = small, large
end
while( tablecount(small) > 0 and tablecount(large) > 0) do
local l = table.remove(small, 1)
local g = table.remove(large, 1)
table.insert(prob, l[2])
table.insert(alias, {l[1], g[1]})
g[2] = g[2] - (1 - l[2])
if g[2] >= 1 then
table.insert(large, g)
else
table.insert(small, g)
end
end
while(tablecount(large) > 0) do
local g = table.remove(large, 1)
table.insert(prob, 1)
table.insert(alias, {g[1], g[1]})
g[2] = g[2] - 1
if g[2] >= 1 then
table.insert(large, g)
else
table.insert(small, g)
end
end
self.prob = prob
self.alias = alias
self.n = n
self.plist = plist
self.prob_count = tablecount(prob)
return self
end
function Vose:get()
local i = math.floor(math.random(1, self.prob_count))
if self.prob[i] >= math.random() then
return self.alias[i][1]
else
return self.alias[i][2]
end
end
-- test
-- if os then
-- math.randomseed(tostring(os.time()):reverse():sub(1, 6))
-- end
-- local plist = {
-- a = 25,
-- b = 65,
-- c = 10
-- }
-- local v = Vose(plist)
-- local r = {}
-- for i = 1, 100000 do
-- local res = v:get()
-- r[res] = r[res] or 0
-- r[res] = r[res] + 1
-- end
-- for k,v in pairs(r) do
-- print(k,v)
-- end
return Vose
|
c897aae724f8b2c07f57bc26c18fc9ec76e4f434
|
[
"Markdown",
"Lua"
] | 2 |
Markdown
|
XavierCHN/vose-lua
|
2bf4a71be90000933cf89c0c6dd6f9bd1e43bb1b
|
c8f1355274dc99f4df26691c0e96120ad7b3391d
|
refs/heads/master
|
<file_sep>import { Map } from 'immutable';
import * as mutate from '../utils/Mutators';
import {mutators} from '@jimib/react-native-libs';
import {
LOGIN_SUCCESS,
LOGIN_FAILURE
} from '../actions/Types';
const INITIAL_STATE = Map({
});
export default (state = INITIAL_STATE, action) => {
const { payload } = action;
//example reducer
switch (action.type) {
case LOGIN_SUCCESS: {
return mutators.applyState(state, {
user : payload,
isLoading : false
});
}
case LOGIN_FAILURE: {
return mutators.applyState(state, {
error : payload,
isLoading : false
});
}
default: {
return state;
}
}
};
|
078659d6bd90ecf494d4751806a7a35ec86239d0
|
[
"JavaScript"
] | 1 |
JavaScript
|
jimib/React-Native-Templates
|
d46f4c83c8a45c7644b02982e3bbc1cd80c81ddb
|
c4dc131e7a837f0db478bc2303f810c8dbb462cf
|
refs/heads/master
|
<file_sep>package reader
import (
"bytes"
"testing"
"fmt"
"golang.org/x/net/html"
)
func TestNewReader(t *testing.T) {
s := "hi there"
b := &bytes.Buffer{}
n, err := b.ReadFrom(NewReader(s))
if n != int64(len(s)) || err != nil {
t.Logf("n=%d err=%s", n, err)
t.Fail()
}
if b.String() != s {
t.Logf(`"%s" != "%s"`, b.String(), s)
}
}
func TestNewReaderWithHTML(t *testing.T) {
s := "<html><body><p>Hello, NewReader!</p></body></html>"
doc, err := html.Parse(NewReader(s))// html.Parse returns doc with nodes in it
if err != nil {
t.Log(err)
t.Fail()
}
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.TextNode {
fmt.Println(n.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
}
<file_sep>package main
import (
"fmt"
"bytes"
)
func main() {
rs := []rune{'世','g','o',' ', ' ','l','a', ' ' ,'n'}
bs := []byte(string(rs))
fmt.Println(rs)
fmt.Println(bs)
fmt.Printf("%08b\n,%T\n",bs,bs)
bs = bytes.Replace(bs, []byte(" "), []byte(" "), -1)
fmt.Println(bs)
}<file_sep>/*
Write two goroutines which have a race condition when executed concurrently. Explain what the race condition is and how it can occur.
Here, we can see that the getNumber function is setting the value of i in a separate goroutines. We are also returning i from the function without any knowledge of which of our goroutines has completed. So now, there are three operations that are taking place:
The value of i is being set to 5
The value of i is being set to 4
The value of i is being returned from the function
Now depending on which of these three operations completes first, our value printed will be either 0 (the default integer value) or 5 or 4.
This is why it’s called a data race : the value returned from getNumber changes depending on which of the operations 1 or 2 finish first.
*/
package main
import (
"fmt"
)
func main() {
fmt.Println(getNumber())
}
func getNumber() int {
var i int
go func() {
i = 5
}()
go func() {
i = 4
}()
return i
}
<file_sep>package main
import (
"testing"
)
func TestJoin(t *testing.T) {
var tests = []struct {
vals []string
sep string
want string
}{
{[]string{"1","2","3"}, "," , "1,2,3"},
{[]string{"-1"}, " ", "-1"},
{[]string{"asd", "asdf", ""}, "", "asdasdf"},
{[]string{}, "", ""},
}
for _, test := range tests {
if got := Join(test.sep, test.vals...); got != test.want {
t.Errorf("Join(%v, %v) = %v", test.vals, test.sep, got)
}
}
}
<file_sep>//Echo prints its command-line arguments. And shows times of multiple executions for different approaches.
package main
import (
"fmt"
"os"
"strings"
"time"
)
func main() {
i := 0
start := time.Now()
for i = 1; i <9999990; i++ {
ex1()
}
resex1 := time.Since(start).Seconds()
start = time.Now()
for i = 1; i <9999990; i++ {
ex2()
}
resex2 := time.Since(start).Seconds()
start = time.Now()
for i = 1; i <9999990; i++ {
ex3()
}
resex3 := time.Since(start).Seconds()
fmt.Println(resex1)
fmt.Println(resex2)
fmt.Println(resex3)
}
func ex1() {
var s, sep string
for i := 1; i < len(os.Args); i++ {
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
}
func ex2() {
s, sep := "", ""
for _, arg := range os.Args[1:] {
s += sep + arg
sep = " "
}
fmt.Println(s)
}
func ex3() {
fmt.Println(strings.Join(os.Args[1:], " "))
}
<file_sep>This repository contains the solutions of the exercises in the book Go Programming Language.
Similar to #gopl-solutions
How to run
1.3
$ go run main.go
1.4
$ go run main.go t1 t2 t3
1.5
& go build
./1.5 > out.gif
1.6
& go build
./1.6 > out.gif
1.7
$ go build
./1.7 http://gopl.io
1.8
$ go build
./1.8 http://gopl.io
./1.8 gopl.io
1.9
$ go build
./1.9 http://gopl.io
./1.9 gopl.io
1.10
$ go build
./1.10 http://gopl.io
1.11
./1.10 http://Google.Com http://Youtube.Com http://Facebook.Com http://Wikipedia.Org http://Yahoo.Com http://Twitter.Com http://Amazon.Com http://Instagram.Com
1.12
$ go run main.go
http://localhost:8000/?cycles=20;res=0.001;size=100;nframes=64;delay=8
2.1
//add $GOPATH variable:
GOPATH="/home/alex/go"
//test the package
tempconv$ go build
//install the package
tempconv$ go install
//run code from the package
go run main.go
2.2
//using package without compiling:
go build main.go
./main -40
//altarnative way without build:
go run main.go 30 50
3.1
//using SVG standard for XML line drawings (advanced)
go run main.go
//result file is in tmp/yourfile folder
//insert result here:
https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_myfirst
3.2
//same as 3.1
//eggbox folder
//moguls folder
//saddle folder
3.3
//same as 3.1
3.4
go run main.go
http://localhost:8000/?width=1000;height=540;cells=49;fill=black
3.5
go run main.go
3.6
go run main.go
3.7
go run main.go
3.8
go run main.go
//21.08s elapsed
go run mainC64.go
//5.85s elapsed
go run mainBigFloat.go
//56.61s elapsed
go run mainBigRat.go
//28.51s elapsed
3.9
go run main.go
http://localhost:8000/?xmin=-2;ymin=-2;zoom=1
3.10
$ go run main.go 123456 1234567890
3.11
$ go run main.go -46237123.456 -123.4567890 -12.3 -46237123.456765
3.12
$ go run main.go
3.13
$ go run main.go
4.1
$ go run main.go
4.2
$go build
$./4.2 < main.go SHA512
or
$./4.2 input text manually
4.3
$go run main.go
4.4
$go run main.go
4.5
$go run main.go
4.6
$go run main.go
4.7
$go run main.go
4.8
$go run main.go
4.9
$go run main.go < main.go
4.10
$go run main.go repo:golang/go is:open json decoder
4.11
$go run main.go create
$go run main.go read
$go run main.go update
$go run main.go delete
$go run main.go search repo:golang/go is:open json decoder
4.11 borrowed
$go run main.go
go run *.go read Julineo golang1training 1
//not working
go run *.go create Julineo golang1training 2
go run *.go delete Julieno golang1training 2
4.12
$go run main.go
//idx will be created
$go run xkcd.go
4.13
Became a patreon at https://omdbapi.com/
Generay API keys at https://omdbapi.com/apikey.aspx
$go run poster.go [your key here] Batman
4.14
//run webserver
$go run main.go repo:golang/go is:open json
open browser and navigate to users, issues, milestones
http://localhost:8000
5.1
$ go build golang1training/5.1/findlinksr
$ ./fetch https://golang.org | ./findlinksr
5.2
$ go build golang1training/5.2/popmap
$ ./fetch https://golang.org | ./popmap
5.3
$ go build golang1training/5.3/htmltext
$ ./fetch https://golang.org | ./htmltext
5.4
$ go run main.go https://golang.org
5.5
$ go run main.go https://golang.org/doc/
5.6
$ go run main.go
//result file is in yourfile
//insert result here:
https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_myfirst
5.7
$ go run outline.go https://golang.org
$ go test
5.8
$ go run getbyid.go topbar https://golang.com https://golang.org/project/
5.9
$ go test
5.10
5.11
//not solved, will get back later
5.12
$ go run outline.go http://www.golang.com
5.13
go run findlinks.go https://www.derekshoemaker.com http://www.alexfast.org http://www.bradfitz.com https://www.calhoun.io
5.15
$ go test
5.16
$ go test
5.17
$ go run main.go
5.18
$ go run main.go https://www.golang.com https://www.golang.com/doc
6.1
$ go run main.go
6.2
$ go run main.go
7.1
$ go run main.go
7.2
$ go run main.go
7.3
$ go test
7.6
$ go run tempflag.go -temp 273.15K
The Go Programming Language Exercises:
chapter.exercise
Index
01.01 Modify the echo program to also print @c(os.Args[0])
01.02 echo program to print the index and value of each of its arguments, one per line.
01.03 str += VS strings.Join
01.04 dup2 to print the names of all files in which each duplicated line occurs
01.05 Change the Lissajous program’s color palette to green on black
01.06 Modify the Lissajous program to produce images in multiple colors
01.07 Use io.Copy(dst, src) it instead of ioutil.ReadAll to copy the response http.Body to os.Stdout
01.08 Modify fetch to add the prefix "http://" to each argument URL if it is missing.
01.09 Modify fetch to also print the HTTP status code, found in resp.Status.
01.10 Find a web site that produces a large amount of data. Investigate
caching by running @c(fetchall) twice in succession to see whether the
reported time changes much. Do you get the same content each time?
Modify @c(fetchall) to print its output to a file so it can be examined.
01.11 Try fetchall) with longer argument lists, such as samples from the top
million web sites available at http://www.alexa.com/. How does the
program behave if a web site just doesn’t respond? (Section 8.9
describes mechanisms for coping in such cases.)
01.12 Modify the Lissajous server to read parameter values from the URL. For
example, you might arrange it so that a URL like
http://localhost:8000/?cycles=20 sets the number of cycles to 20
instead of the default 5. Use the strconv.Atoi function to convert the
string parameter into an integer. You can see its documentation with go
doc strconv.Atoi.
02.01 Add types, constants, and functions to tempconv for processing
temperatures in the Kelvin scale, where zero Kelvin is -273.15°C and a
difference of 1K has the same magnitude as 1°C.
02.02 Write a general-purpose unit-conversion program analogous to cf that
reads numbers from its command-line arguments or from the standard
input if there are no arguments, and converts each number into units
like temperature in Celsius and Fahrenheit, length in feet and meters,
weight in pounds and kilograms, and the like.
02.03 Rewrite PopCount to use a loop instead of a single expression. Compare
the performance of the two versions. (#Section 11.4 shows how to
compare the performance of different implementations systematically.)
02.04 Write a version of PopCount that counts bits by shifting its argument
through 64 bit positions, testing the rightmost bit each time. Compare
its performance to the tablelookup version.
02.05 The expression x&(x-1) clears the rightmost non-zero bit of x. Write a
version of PopCount that counts bits by using this fact, and assess its
performance.
03.01 If the function f returns a non-finite float64 value, the SVG file
will contain invalid <polygon> elements (although many SVG renderers
handle this gracefully). Modify the program to skip invalid polygons.
03.02 Experiment with visualizations of other functions from the math
package. Can you produce an egg box, moguls, or a saddle?
03.03 Color each polygon based on its height, so that the peaks are colored
red (#ff0000) and the valleys blue (#0000ff).
03.04 Following the approach of the Lissajous example in Section 1.7,
construct a web server that computes surfaces and writes SVG data to
the client. The server must set the Content-Type header like this:
03.05 Implement a full-color Mandelbrot set using the function image.NewRGBA
and the type color.RGBA or color.YCbCr.
03.06 Supersampling is a technique to reduce the effect of pixelation by
computing the color value at several points within each pixel and
taking the average. The simplest method is to divide each pixel into
four subpixels. Implement it.
03.07 Another simple fractal uses Newton’s method to find complex solutions
to a function such as z4-1 = 0. Shade each starting point by the number
of iterations required to get close to one of the four roots. Color
each point by the root it approaches.
03.08 Rendering fractals at high zoom levels demands great arithmetic
precision. Implement the same fractal using four different
representations of numbers: complex64, complex128, big.Float, and
big.Rat. (The latter two types are found in the math/big package.
Float uses arbitrary but bounded-precision floating-point; Rat uses
unbounded-precision rational numbers.) How do they compare in
performance and memory usage? At what zoom levels do rendering
artifacts become visible?
03.09 Write a web server that renders fractals and writes the image data to
the client. Allow the client to specify the x, y, and zoom values as
parameters to the HTTP request.
03.10 Write a non-recursive version of comma, using bytes.Buffer instead of
string concatenation.
03.11 Enhance comma so that it deals correctly with floating-point numbers
and an optional sign.
03.12 Write a function that reports whether two strings are anagrams of each
other, that is, they contain the same letters in a different order.
03.13 Write const declarations for KB, MB, up through YB as compactly as you
can.
04.01 Write a function that counts the number of bits that are different in
two SHA256 hashes. (See PopCount from Section 2.6.2.)
04.02 Write a program that prints the SHA256 hash of its standard input by
default but supports a command-line flag to print the SHA384 or SHA512
hash instead.
04.03 Rewrite reverse to use an array pointer instead of a slice.
04.04 Write a version of rotate that operates in a single pass.
04.05 Write an in-place function to eliminate adjacent duplicates in a
[]string slice.
04.06 Write an in-place function that squashes each run of adjacent Unicode
spaces (see unicode.IsSpace) in a UTF-8-encoded []byte slice into a
single ASCII space.
04.07 Modify reverse to reverse the characters of a []byte slice that
represents a UTF-8-encoded string, in place. Can you do it without
allocating new memory?
04.08 Modify charcount to count letters, digits, and so on in their Unicode
categories, using functions like unicode.IsLetter.
04.09 Write a program wordfreq to report the frequency of each word in an
input text file. Call input.Split(bufio.ScanWords) before the first
call to Scan to break the input into words instead of lines.
04.10 Modify issues to report the results in age categories, say less than a
month old, less than a year old, and more than a year old.
04.11 Build a tool that lets users create, read, update, and delete GitHub
issues from the command line, invoking their preferred text editor when
substantial text input is required.
04.12 The popular web comic xkcd has a JSON interface. For example, a request
to https://xkcd.com/571/info.0.json produces a detailed description of
comic 571, one of many favorites. Download each URL (once!) and build
an offline index. Write a tool xkcd that, using this index, prints the
URL and transcript of each comic that matches a search term provided on
the command line.
04.13 The JSON-based web service of the Open Movie Database lets you search
https://omdbapi.com/ for a movie by name and download its poster
image. Write a tool poster that downloads the poster image for the
movie named on the command line.
04.14 Create a web server that queries GitHub once and then allows navigation
of the list of bug reports, milestones, and users.
05.01 Change the findlinks program to traverse the n.FirstChild linked list
using recursive calls to visit instead of a loop.
05.02 Write a function to populate a mapping from element names—p, div, span,
and so on—to the number of elements with that name in an HTML document
tree.
05.03 Write a function to print the contents of all text nodes in an HTML
document tree. Do not descend into <script> or <style> elements, since
their contents are not visible in a web browser.
05.04 Extend the visit function so that it extracts other kinds of links from
the document, such as images, scripts, and style sheets.
05.05 Implement countWordsAndImages. (See Exercise 4.9 for word-splitting.)
05.06 Modify the corner function in gopl.io/ch3/surface (Section 3.2) to use
named results and a bare return statement.
05.07 Develop startElement and endElement into a general HTML pretty-printer.
Print comment nodes, text nodes, and the attributes of each element (<a
href='...'>). Use short forms like <img/> instead of <img></img> when
an element has no children. Write a test to ensure that the output can
be parsed successfully. (See #Chapter 11.)
05.08 Modify forEachNode so that the pre and post functions return a boolean
result indicating whether to continue the traversal. Use it to write a
function ElementByID with the following signature that finds the first
HTML element with the specified id attribute. The function should stop
the traversal as soon as a match is found.
05.09 Write a function expand(s string, f func(string) string) string that
replaces each substring $foo within s by the text returned by f("foo").
05.10 Rewrite topoSort to use maps instead of slices and eliminate the
initial sort. Verify that the results, though nondeterministic, are
valid topological orderings.
05.11 The instructor of the linear algebra course decides that calculus is
now a prerequisite. Extend the topoSort function to report cycles.
05.12 The startElement and endElement functions in gopl.io/ch5/outline2
(Section 5.5) share a global variable, depth. Turn them into anonymous
functions that share a variable local to the outline function.
05.13 Modify crawl to make local copies of the pages it finds, creating
directories as necessary. Don’t make copies of pages that come from a
different domain. For example, if the original page comes from
https://golang.org, save all files from there, but exclude ones from
https://vimeo.com.
05.14 Use the breadthFirst function to explore a different structure. For
example, you could use the course dependencies from the topoSort
example (a directed graph), the file system hierarchy on your computer
(a tree), or a list of bus or subway routes downloaded from your city
government’s web site (an undirected graph).
05.15 Write variadic functions max and min, analogous to sum. What should
these functions do when called with no arguments? Write variants that
require at least one argument.
05.16 Write a variadic version of strings.Join.
05.17 Write a variadic function ElementsByTagName that, given an HTML node
tree and zero or more names, returns all the elements that match one of
those names. Here are two example calls:
05.18 Without changing its behavior, rewrite the fetch function to use defer
to close the writable file.
05.19 Use panic and recover to write a function that contains no return
statement yet returns a non-zero value.
06.01 Implement these additional methods:
06.02 Define a variadic (*IntSet).AddAll(...int) method that allows a list of
values to be added, such as s.AddAll(1, 2, 3).
06.03 (*IntSet).UnionWith computes the union of two sets using |, the
word-parallel bitwise OR operator. Implement methods for IntersectWith,
DifferenceWith, and SymmetricDifference for the corresponding set
operations. (The symmetric difference of two sets contains the elements
present in one set or the other but not both.)
06.04 Add a method Elems that returns a slice containing the elements of the
set, suitable for iterating over with a range loop.
06.05 The type of each word used by IntSet is uint64, but 64-bit arithmetic
may be inefficient on a 32-bit platform. Modify the program to use the
uint type, which is the most efficient unsigned integer type for the
platform. Instead of dividing by 64, define a constant holding the
effective size of uint in bits, 32 or 64. You can use the perhaps
too-clever expression 32 << (^uint(0) >> 63) for this purpose.
07.01 Using the ideas from ByteCounter, implement counters for words and for
lines. You will find bufio.ScanWords useful.
07.02 Write a function CountingWriter with the signature below that, given an
io.Writer, returns a new Writer that wraps the original, and a pointer
to an int64 variable that at any moment contains the number of bytes
written to the new Writer.
07.03 Write a String method for the *tree type in gopl.io/ch4/treesort
(Section 4.4) that reveals the sequence of values in the tree.
07.04 The strings.NewReader function returns a value that satisfies the
io.Reader interface (and others) by reading from its argument, a
string. Implement a simple version of NewReader yourself, and use it to
make the HTML parser (Section 5.2) take input from a string.
07.05 The LimitReader function in the io package accepts an io.Reader r and a
number of bytes n, and returns another Reader that reads from r but
reports an end-of-file condition after n bytes. Implement it.
07.06 Add support for Kelvin temperatures to tempflag.
07.07 Explain why the help message contains °C when the default value of 20.0
does not.
07.08 Many GUIs provide a table widget with a stateful multi-tier sort: the
primary sort key is the most recently clicked column head, the
secondary sort key is the second-most recently clicked column head, and
so on. Define an implementation of sort.Interface for use by such a
table. Compare that approach with repeated sorting using sort.Stable.
07.09 Use the html/template package (Section 4.6) to replace printTracks with
a function that displays the tracks as an HTML table. Use the solution
to the previous exercise to arrange that each click on a column head
makes an HTTP request to sort the table.
07.10 The sort.Interface type can be adapted to other uses. Write a function
IsPalindrome(s sort.Interface) bool that reports whether the sequence s
is a palindrome, in other words, reversing the sequence would not
change it. Assume that the elements at indices i and j are equal if
!s.Less(i, j) && !s.Less(j, i).
07.11 Add additional handlers so that clients can create, read, update, and
delete database entries. For example, a request of the form
/update?item=socks&price=6 will update the price of an item in the
inventory and report an error if the item does not exist or if the
price is invalid. (Warning: this change introduces concurrent variable
updates.)
07.12 Change the handler for /list to print its output as an HTML table, not
text. You may find the html/template package (Section 4.6) useful.
07.13 Add a String method to Expr to pretty-print the syntax tree. Check that
the results, when parsed again, yield an equivalent tree.
07.14 Define a new concrete type that satisfies the Expr interface and
provides a new operation such as computing the minimum value of its
operands. Since the Parse function does not create instances of this
new type, to use it you will need to construct a syntax tree directly
(or extend the parser).
07.15 Write a program that reads a single expression from the standard input,
prompts the user to provide values for any variables, then evaluates
the expression in the resulting environment. Handle all errors
gracefully.
07.16 Write a web-based calculator program.
07.17 Extend xmlselect so that elements may be selected not just by name, but
by their attributes too, in the manner of CSS, so that, for instance,
an element like <div id="page" class="wide"> could be selected by a
matching id or class as well as its name.
07.18 Using the token-based decoder API, write a program that will read an
arbitrary XML document and construct a tree of generic nodes that
represents it. Nodes are of two kinds: CharData nodes represent text
strings, and Element nodes represent named elements and their
attributes. Each element node has a slice of child nodes.
08.01 Modify clock2 to accept a port number, and write a program, clockwall,
that acts as a client of several clock servers at once, reading the
times from each one and displaying the results in a table, akin to the
wall of clocks seen in some business offices. If you have access to
geographically distributed computers, run instances remotely ;
otherwise run local instances on different ports with fake time zones.
08.02 Implement a concurrent File Transfer Protocol (FTP) server. The server
should interpret commands from each client such as cd to change
directory, ls to list a directory, get to send the contents of a file,
and close to close the connection. You can use the standard ftp command
as the client, or write your own.
08.03 In netcat3, the interface value conn has the concrete type *net.TCPConn,
which represents a TCP connection. A TCP connection consists of two
halves that may be closed independently using its CloseRead and
CloseWrite methods. Modify the main goroutine of netcat3 to close only
the write half of the connection so that the program will continue to
print the final echoes from the reverb1 server even after the standard
input has been closed. (Doing this for the reverb2 server is harder;
see Exercise 8.4.)
08.04 Modify the reverb2 server to use a sync.WaitGroup per connection to
count the number of active echo goroutines. When it falls to zero,
close the write half of the TCP connection as described in Exercise
8.3. Verify that your modified netcat3 client from that exercise waits
for the final echoes of multiple concurrent shouts, even after the
standard input has been closed.
08.05 Take an existing CPU-bound sequential program, such as the Mandelbrot
program of Section 3.3 or the 3-D surface computation of Section 3.2,
and execute its main loop in parallel using channels for
communication. How much faster does it run on a multiprocessor machine?
What is the optimal number of goroutines to use?
08.06 Add depth-limiting to the concurrent crawler. That is, if the user sets
-depth=3, then only URLs reachable by at most three links will be
fetched.
08.07 Write a concurrent program that creates a local mirror of a web site,
fetching each reachable page and writing it to a directory on the local
disk. Only pages within the original domain (for instance,
https://golang.org) should be fetched. URLs within mirrored pages
should be altered as needed so that they refer to the mirrored page,
not the original.
08.08 Using a select statement, add a timeout to the echo server from Section
8.3 so that it disconnects any client that shouts nothing within 10
seconds.
08.09 Write a version of du that computes and periodically displays separate
totals for each of the root directories.
08.10 HTTP requests may be cancelled by closing the optional Cancel channel
in the http.Request struct. Modify the web crawler of Section 8.6 to
support cancellation.
08.11 Following the approach of mirroredQuery in Section 8.4.4, implement a
variant of fetch that requests several URLs concurrently. As soon as
the first response arrives, cancel the other requests.
08.12 Make the broadcaster announce the current set of clients to each new
arrival. This requires that the clients set and the entering and
leaving channels record the client name too.
08.13 Make the chat server disconnect idle clients, such as those that have
sent no messages in the last five minutes. Hint: calling conn.Close()
in another goroutine unblocks active Read calls such as the one done by
input.Scan().
08.14 Change the chat server’s network protocol so that each client provides
its name on entering. Use that name instead of the network address when
prefixing each message with its sender’s identity.
08.15 Failure of any client program to read data in a timely manner
ultimately causes all clients to get stuck. Modify the broadcaster to
skip a message rather than wait if a client writer is not ready to
accept it. Alternatively, add buffering to each client’s outgoing
message channel so that most messages are not dropped; the broadcaster
should use a non-blocking send to this channel.
09.01 Add a function Withdraw(amount int) bool to the gopl.io/ch9/bank1
program. The result should indicate whether the transaction succeeded
or failed due to insufficient funds. The message sent to the monitor
goroutine must contain both the amount to withdraw and a new channel
over which the monitor goroutine can send the boolean result back to
Withdraw.
09.02 Rewrite the PopCount example from Section 2.6.2 so that it initializes
the lookup table using sync.Once the first time it is
needed. (Realistically, the cost of synchronization would be
prohibitive for a small and highly optimized function like PopCount.)
09.03 Extend the Func type and the (*Memo).Get method so that callers may
provide an optional done channel through which they can cancel the
operation (Section 8.9). The results of a cancelled Func call should
not be cached.
09.04 Construct a pipeline that connects an arbitrary number of goroutines
with channels. What is the maximum number of pipeline stages you can
create without running out of memory? How long does a value take to
transit the entire pipeline?
09.05 Write a program with two goroutines that send messages back and forth
over two unbuffered channels in ping-pong fashion. How many
communications per second can the program sustain?
09.06 Measure how the performance of a compute-bound parallel program (see
Exercise 8.5) varies with GOMAXPROCS. What is the optimal value on your
computer? How many CPUs does your computer have?
10.01 Extend the jpeg program so that it converts any supported input format
to any output format, using image.Decode to detect the input format and
a flag to select the output format.
10.02 Define a generic archive file-reading function capable of reading ZIP
files (archive/zip) and POSIX tar files (archive/tar). Use a
registration mechanism similar to the one described above so that
support for each file format can be plugged in using blank imports.
10.03 Using fetch http://gopl.io/ch1/helloworld?go-get=1, find out which
service hosts the code samples for this book. (HTTP requests from go
get include the go-get parameter so that servers can distinguish them
from ordinary browser requests.)
10.04 Construct a tool that reports the set of all packages in the workspace
that transitively depend on the packages specified by the
arguments. Hint: you will need to run go list twice, once for the
initial packages and once for all packages. You may want to parse its
JSON output using the encoding/json package (Section 4.5).
11.01 Write tests for the charcount program in Section 4.3.
11.02 Write a set of tests for IntSet (Section 6.5) that checks that its
behavior after each operation is equivalent to a set based on built-in
maps. Save your implementation for benchmarking in Exercise 11.7.
11.03 TestRandomPalindromes only tests palindromes. Write a randomized test
that generates and verifies non-palindromes.
11.04 Modify randomPalindrome to exercise IsPalindrome’s handling of
punctuation and spaces.
11.05 Extend TestSplit to use a table of inputs and expected outputs.
11.06 Write benchmarks to compare the PopCount implementation in Section
2.6.2 with your solutions to Exercise 2.4 and Exercise 2.5. At what
point does the table-based approach break even?
11.07 Write benchmarks for Add, UnionWith, and other methods of *IntSet
(Section 6.5) using large pseudo-random inputs. How fast can you make
these methods run? How does the choice of word size affect performance?
How fast is IntSet compared to a set implementation based on the
built-in map type?
12.01 Extend Display so that it can display maps whose keys are structs or
arrays.
12.02 Make display safe to use on cyclic data structures by bounding the
number of steps it takes before abandoning the recursion. (In Section
13.3, we’ll see another way to detect cycles.)
12.03 Implement the missing cases of the encode function. Encode booleans as
t and nil, floating-point numbers using Go’s notation, and complex
numbers like 1+2i as #C(1.0 2.0). Interfaces can be encoded as a pair
of a type name and a value, for instance ("[]int" (1 2 3)), but beware
that this notation is ambiguous: the reflect.Type.String method may
return the same string for different types.
12.04 Modify encode to pretty-print the S-expression in the style shown
above.
12.05 Adapt encode to emit JSON instead of S-expressions. Test your encoder
using the standard decoder, json.Unmarshal.
12.06 Adapt encode so that, as an optimization, it does not encode a field
whose value is the zero value of its type.
12.07 Create a streaming API for the S-expression decoder, following the
style of json.Decoder (Section 4.5).
12.08 The sexpr.Unmarshal function, like json.Marshal, requires the complete
input in a byte slice before it can begin decoding. Define a
sexpr.Decoder type that, like json.Decoder, allows a sequence of values
to be decoded from an io.Reader. Change sexpr.Unmarshal to use this new
type.
12.09 Write a token-based API for decoding S-expressions, following the style
of xml.Decoder (Section 7.14). You will need five types of tokens:
Symbol, String, Int, StartList, and EndList.
12.10 Extend sexpr.Unmarshal to handle the booleans, floating-point numbers,
and interfaces encoded by your solution to Exercise 12.3. (Hint: to
decode interfaces, you will need a mapping from the name of each
supported type to its reflect.Type.)
12.11 Write the corresponding Pack function. Given a struct value, Pack
should return a URL incorporating the parameter values from the struct.
12.12 Extend the field tag notation to express parameter validity
requirements. For example, a string might need to be a valid email
address or credit-card number, and an integer might need to be a valid
US ZIP code. Modify Unpack to check these requirements.
12.13 Modify the S-expression encoder (Section 12.4) and decoder (Section
12.6) so that they honor the sexpr:"..." field tag in a similar manner
to encoding/json (Section 4.5).
13.01 Define a deep comparison function that considers numbers (of any type)
equal if they differ by less than one part in a billion.
13.02 Write a function that reports whether its argument is a cyclic data
structure.
13.03 Use sync.Mutex to make bzip2.writer safe for concurrent use by multiple
goroutines.
13.04 Depending on C libraries has its drawbacks. Provide an alternative
pure-Go implementation of bzip.NewWriter that uses the os/exec package
to run /bin/bzip2 as a subprocess.
<file_sep>/*
ex 7.1: Using the ideas from ByteCounter, implement counters for words and for lines. You will find bufio.ScanWords useful.
*/
package main
import (
"fmt"
"unicode/utf8"
)
type ByteCounter int
func (c *ByteCounter) Write(p []byte) (int, error) {
*c += ByteCounter(len(p)) // convert int to ByteCounter
return len(p), nil
}
type WordsCounter int
func (d *WordsCounter) Write(p []byte) (int, error) {
i := 0
count := 0
prev := ' '
for i < len(p) {
curr, j := utf8.DecodeRune(p[i:])
if (prev != ' ' && curr == ' ') || (prev != ' ' && i + j == len(p)) {
count++
}
i += j
prev = curr
}
*d = WordsCounter(count)
return count, nil
}
type LinesCounter int
func (c *LinesCounter) Write(p []byte) (int, error) {
count := 0
for _,v := range p {
if v == 10 {
count++
}
}
*c = LinesCounter(count + 1)
return count + 1, nil
}
func main() {
var c ByteCounter
c.Write([]byte("hello"))
fmt.Println(c) // "5", = len("hello")
c = 0 // reset the counter
var name = "Dolly"
fmt.Fprintf(&c, "hello, %s", name)
fmt.Println(c) // "12", = len("hello, Dolly")
var d WordsCounter
d.Write([]byte(" I say 世界 to you"))
fmt.Println(d) // "5"
var e LinesCounter
s := `line1
line2`
e.Write([]byte(s))
fmt.Println(e)
s = "line1"
e.Write([]byte(s))
fmt.Println(e)
}
<file_sep>package main
import (
"fmt"
)
const MAX int = 6
func main() {
t := []int{0, 1, 2, 3, 4, 5}
var ptr [MAX]*int;
for i := 0; i < MAX; i++ {
ptr[i] = &t[i] /* assign the address of integer. */
}
fmt.Println(ptr)
reverse(&ptr)
for i := 0; i < MAX; i++ {
fmt.Printf("Value of a[%d] = %d\n", i,*ptr[i] )
} // "[5 4 3 2 1 0]"
}
func reverse(s *[MAX]*int) {
fmt.Println(s)
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
fmt.Println(s)
}
<file_sep>// Copyright © 2016 <NAME> & <NAME>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 61.
//!+
// Mandelbrot emits a PNG image of the Mandelbrot fractal.
package main
import (
"image"
"image/color"
"image/png"
"math/cmplx"
"math"
//"net/http"
"log"
"os"
)
func main() {
const (
xmin, ymin, xmax, ymax = -2, -2, +2, +2
width, height = 1024, 1024
widthP, heightP = width * 2, height * 2
)
var superSamples [widthP][heightP]color.Color
for py := 0; py < heightP; py++ {
y := float64(py) / heightP * (ymax - ymin) + ymin
for px := 0; px < widthP; px++ {
x := float64(px) / widthP * (xmax - xmin) + xmin
z := complex(x, y)
superSamples[px][py] = mandelbrot(z)
}
}
img := image.NewRGBA(image.Rect(0, 0, width, height))
for py := 0; py < height; py++ {
for px := 0; px < width; px++ {
sj, si := py * 2, px * 2
// Averaging colors
r1,g1,b1,_ := superSamples[si][sj].RGBA()
r2,g2,b2,_ := superSamples[si+1][sj].RGBA()
r3,g3,b3,_ := superSamples[si][sj+1].RGBA()
r4,g4,b4,_ := superSamples[si+1][sj+1].RGBA()
r := (r1+r2+r3+r4)/4
g := (g1+g2+g3+g4)/4
b := (b1+b2+b3+b4)/4
ru := r >> 8
gu := g >> 8
bu := b >> 8
c := color.RGBA{uint8(ru), uint8(gu), uint8(bu), 255}
img.Set(px, py, c)
}
}
f, err := os.Create("image.png")
if err != nil {
log.Fatal(err)
}
if err := png.Encode(f, img); err != nil {
f.Close()
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
func mandelbrot(z complex128) color.Color {
const iterations = 200
const contrast = 15
var v complex128
for n := uint8(0); n < iterations; n++ {
v = v*v + z
if cmplx.Abs(v) > 2 {
//return acosRGBA(v)
//return acos(v)
//return sqrt(v)
//return newton(v)
return newtonColor(v)
}
}
return color.Black
}
//!-
// Some other interesting functions:
func acosRGBA(z complex128) color.Color {
v := cmplx.Acos(z)
blue := uint8(real(v)*128) + 127
red := uint8(imag(v)*128) + 127
return color.RGBA{red, uint8(math.Abs(float64(red-blue))), blue, 255}
}
func acos(z complex128) color.Color {
v := cmplx.Acos(z)
blue := uint8(real(v)*128) + 127
red := uint8(imag(v)*128) + 127
return color.YCbCr{192, blue, red}
}
func sqrt(z complex128) color.Color {
v := cmplx.Sqrt(z)
blue := uint8(real(v)*128) + 127
red := uint8(imag(v)*128) + 127
return color.YCbCr{128, blue, red}
}
// f(x) = x^4 - 1
//
// z' = z - f(z)/f'(z)
// = z - (z^4 - 1) / (4 * z^3)
// = z - (z - 1/z^3) / 4
func newton(z complex128) color.Color {
const iterations = 37
const contrast = 7
for i := uint8(0); i < iterations; i++ {
z -= (z - 1/(z*z*z)) / 4
if cmplx.Abs(z*z*z*z-1) < 1e-6 {
return color.Gray{255 - contrast*i}
}
}
return color.Black
}
func newtonColor(z complex128) color.Color {
const iterations = 37
const contrast = 7
for i := uint8(0); i < iterations; i++ {
z -= (z - 1/(z*z*z)) / 4
if cmplx.Abs(z*z*z*z-1) < 1e-6 {
return color.RGBA{uint8(real(z)*128) + 127,uint8(imag(z)*128) + 127,uint8(math.Abs(float64(real(z)+imag(z))))*128,255}
}
}
return color.Black
}<file_sep>package main
import (
"testing"
"fmt"
"bytes"
"strings"
"io"
"os"
"golang.org/x/net/html"
)
func TestOutline (t *testing.T) {
input := `
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6"><img src="http://placehold.it/100x100"></div>
<div class="col-md-6 text-right">
<h1><NAME></h1>
<h3>Software Engineer</h3>
</div>
</div>
</div>
</body>
</html>
`
doc, err := html.Parse(strings.NewReader(input))
if err != nil {
t.Log(err)
t.Fail()
}
var out io.Writer = os.Stdout
out = new(bytes.Buffer) //to capture output
forEachNode(doc, startElement, endElement)
fmt.Println(out.(*bytes.Buffer).String())
_, err = html.Parse(strings.NewReader(out.(*bytes.Buffer).String()))
if err != nil {
t.Log(err)
t.Fail()
}
}
<file_sep>/*
Exercise 5.19: Use panic and recover to write a function that contains no return statement yet returns a non-zero value.
*/
package main
import "fmt"
func main() {
fmt.Println(f(3))
}
func f(x int) (s string) {
defer func() {
recover()
s = "division by zero"
}()
fmt.Printf("f(%d)\n", x+0/x) // panics if x == 0
defer fmt.Printf("defer %d\n", x)
f(x - 1)
panic("No return")
}
<file_sep>package main
import (
"fmt"
)
type animal interface {
Eat() string
Move() string
Speak() string
}
type cow struct {
food string
locomotion string
noise string
}
type bird struct {
food string
locomotion string
noise string
}
type snake struct {
food string
locomotion string
noise string
}
func (a *cow) Eat() string { return a.food }
func (a *cow) Move() string { return a.locomotion }
func (a *cow) Speak() string { return a.noise }
func (a *bird) Eat() string { return a.food }
func (a *bird) Move() string { return a.locomotion }
func (a *bird) Speak() string { return a.noise }
func (a *snake) Eat() string { return a.food }
func (a *snake) Move() string { return a.locomotion }
func (a *snake) Speak() string { return a.noise }
func main() {
m := make(map[string]animal)
var com, name, class string
loop:
for {
fmt.Println(">")
fmt.Scanf("%s %s %s", &com, &name, &class)
switch com {
case "newanimal":
switch class {
case "cow":
m[name] = &cow{"grass", "walk", "moo"}
fmt.Println("Created it!")
case "bird":
m[name] = &bird{"worms", "fly", "peep"}
fmt.Println("Created it!")
case "snake":
m[name] = &snake{"mice", "slither", "hsss"}
fmt.Println("Created it!")
default:
fmt.Println("wrong animal")
}
case "query":
switch class {
case "eat":
fmt.Println(m[name].Eat())
case "move":
fmt.Println(m[name].Move())
case "speak":
fmt.Println(m[name].Speak())
default:
fmt.Println("wrong action")
}
case "x":
break loop
default:
fmt.Println("wrong command!")
}
}
}
<file_sep>/*5.13: Modify crawl to make local copies of the pages it finds, creating directories as necessary. Ignore external links*/
// Findlinks3 crawls the web, starting with the URLs on the command line.
package main
import (
"fmt"
"log"
"os"
"path"
"net/http"
"net/url"
"io"
"strings"
"path/filepath"
"gopl.io/ch5/links"
)
//for test purpose. to limit working time
var ext int
func breadthFirst(f func(item string) []string, worklist []string) {
seen := make(map[string]bool)
for len(worklist) > 0 {
items := worklist
worklist = nil
for _, item := range items {
if !seen[item] {
seen[item] = true
ext++
if ext > 200 {
return
}
worklist = append(worklist, f(item)...)
}
}
}
}
//modified crawl for saving data on local disk
var local []string
func crawl(urla string) []string {
//fmt.Println(urla)
//fmt.Println(path.Base(urla))
u, err := url.Parse(urla)
if err != nil {
log.Fatal(err)
}
//check if local page
flag := false
for _, v := range local {
if strings.Replace(u.Host, "www.", "", 1) == v {
flag = true
}
}
if ! flag {
return []string{}
}
fmt.Println(urla)
fmt.Println(path.Base(urla))
download(urla)
list, err := links.Extract(urla)
if err != nil {
log.Print(err)
}
return list
}
var origHost string
// Download url to filename
func download(rawurl string) error {
url, err := url.Parse(rawurl)
if err != nil {
return fmt.Errorf("bad url: %s", err)
}
if origHost == "" {
origHost = url.Host
}
if origHost != url.Host {
return nil
}
dir := url.Host
var filename string
if filepath.Ext(filename) == "" {
dir = filepath.Join(dir, url.Path)
filename = filepath.Join(dir, "index.html")
} else {
dir = filepath.Join(dir, filepath.Dir(url.Path))
filename = url.Path
}
err = os.MkdirAll(dir, 0777)
if err != nil {
return err
}
resp, err := http.Get(rawurl)
if err != nil {
return err
}
defer resp.Body.Close()
file, err := os.Create(filename)
if err != nil {
return err
}
_, err = io.Copy(file, resp.Body)
if err != nil {
return err
}
// Check for delayed write errors section 5.8.
err = file.Close()
if err != nil {
return err
}
return nil
}
func main() {
// Crawl the web breadth-first,
// starting from the command-line arguments.
// saving only local pages, ignoring eternal links
for _, v := range os.Args[1:] {
local = append(local, strings.Replace(path.Base(v), "www.", "", 1))
}
fmt.Println(local)
breadthFirst(crawl, os.Args[1:])
}
<file_sep>// Package github provides a Go API for the GitHub issue tracker.
// See https://developer.github.com/v3/search/#search-issues.
package github
import "time"
const IssuesURL = "https://api.github.com/search/issues"
const APIURL = "https://api.github.com"
type IssuesSearchResult struct {
TotalCount int `json:"total_count"`
Items []*Issue
}
type Issue struct {
Number int
HTMLURL string `json:"html_url"`
Title string `json:"Tit"`
State string
User *User
Milestone *Milestone `json:",omitempty"`
CreatedAt time.Time `json:"created_at"`
Body string // in Markdown format
}
type User struct {
Login string
HTMLURL string `json:"html_url"`
}
type Milestone struct {
Title string
HTMLURL string `json:"html_url"`
}
//`json:"omitempty"`
<file_sep>package main
import (
"bufio"
"fmt"
"io"
"os"
"unicode"
)
func main() {
countsCat := make(map[string]int)
in := bufio.NewReader(os.Stdin)
for {
r, _, err := in.ReadRune()
if err == io.EOF {
break
}
if err != nil {
fmt.Fprintf(os.Stderr, "charcount: %v\n", err)
os.Exit(1)
}
switch true {
case unicode.IsLetter(r):
countsCat["IsLetter"]++
case unicode.IsNumber(r):
countsCat["IsNumber"]++
case unicode.IsControl(r):
countsCat["IsControl"]++
default:
countsCat["Other"]++
}
}
fmt.Printf("function\tcount\n")
for cat, n := range countsCat {
fmt.Printf("%q\t%d\n", cat, n)
}
}
<file_sep>//Read text files and print
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
arr := [][]string{}
countsf := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts, &arr)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts, &arr)
f.Close()
}
}
for i := 0; i < len(arr); i++ {
for j := 0; j < len(arr); j++ {
if arr[i][1] == arr[j][1] {
countsf[arr[i][0]]++
countsf[arr[j][0]]++
}
}
}
for line, n := range countsf {
if n > 2 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
func countLines(f *os.File, counts map[string]int, arr *[][]string) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
*arr = append(*arr, []string{f.Name(), input.Text()})
}
// potential errors from input.Err() ignored
}
<file_sep>package main
import (
"encoding/json"
"fmt"
"log"
"os"
"html/template"
"strings"
)
var data []byte
var movieList = template.Must(template.New("movielist").Parse(`
<table>
<tr style='text-align: left'>
<th>Title</th>
<th>Actor</th>
</tr>
{{range .Movies}}
<tr>
<td>{{.Title}}</td>
<td>{{if .Actor}}{{.Actor.Name}}{{end}}</td>
</tr>
{{end}}
</table>
`))
type DataS struct {
Movies []*Movie
}
type Movie struct {
Title string
Actor *Actor
}
type Actor struct {
Name string
}
func main() {
data := `{"Movies":
[
{
"Title": "Cool Hand Luke",
"Actor": {"Name": "<NAME>"}
},
{
"Title": "Bullitt",
"Actor": {"Name":"<NAME>"}
},
{
"Title": "Casablanca"
}
]
}`
/*
,
"Actor": {"Name":"<NAME>"}
*/
fmt.Printf("%s\n", data)
r := strings.NewReader(data)
var result DataS
if err := json.NewDecoder(r).Decode(&result); err != nil {
fmt.Println(1)
log.Fatal(err)
}
fmt.Printf("%s\n", result)
if err := movieList.Execute(os.Stdout, result); err != nil {
fmt.Println(2)
log.Fatal(err)
}
}<file_sep>package main
import (
"fmt"
"os"
"bytes"
)
func main() {
for i := 1; i < len(os.Args); i++ {
fmt.Printf(" %s\n", comma(os.Args[i]))
}
}
// comma inserts commas in a non-negative decimal integer string.
func comma(s string) string {
var buf bytes.Buffer
var n int
for i := len(s); i > 0; i-- {
if n == 3 {
buf.WriteString(",")
n = 0
}
n++
v := s[i-1:i]
fmt.Fprintf(&buf, "%v", string(v))
}
return reverse(buf.String() )
}
func reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}<file_sep>/*
Write a program to sort an array of integers. The program should partition the array into 4 parts, each of which is sorted by a different goroutine. Each partition should be of approximately equal size. Then the main goroutine should merge the 4 sorted subarrays into one large sorted array.
The program should prompt the user to input a series of integers. Each goroutine which sorts ¼ of the array should print the subarray that it will sort. When sorting is complete, the main goroutine should print the entire sorted list.
*/
package main
import (
"fmt"
"sort"
"sync"
)
func main() {
/* var n int
_, err := fmt.Scanf("%d", &n)
if err != nil {
log.Fatal(err)
}
fmt.Println(n)
*/
//initial slice
sl := []int{10, 45, 23, 126, 432, 349, 2, 86, 23, 123, 865, 90, 3980, 21, 345, 15, 3, 789, 23, 0, 32, 34, 33, 133, 456}
//4 slices
sl1, sl2, sl3, sl4 := []int{}, []int{}, []int{}, []int{}
//dividing slice to 4 parts:
steps := len(sl) / 4
counter := 0
_ = counter
for i, v := range sl {
switch i / steps {
case 0:
sl1 = append(sl1, v)
case 1:
sl2 = append(sl2, v)
case 2:
sl3 = append(sl3, v)
default:
sl4 = append(sl4, v)
}
}
//sorting 4 slices
var wg sync.WaitGroup
sortSl := func(sl []int) {
sort.Ints(sl)
fmt.Println(sl)
wg.Done()
}
wg.Add(4)
go sortSl(sl1)
go sortSl(sl2)
go sortSl(sl3)
go sortSl(sl4)
wg.Wait()
fmt.Println(sl)
//result slice
fmt.Println(mergeSl(mergeSl(sl1, sl2), mergeSl(sl3, sl4)))
}
func mergeSl(sl1, sl2 []int) []int {
i, j := 0, 0
res := []int{}
for i < len(sl1) && j < len(sl2) {
if sl1[i] > sl2[j] {
res = append(res, sl2[j])
j++
} else {
res = append(res, sl1[i])
i++
}
}
if i == len(sl1) {
for j < len(sl2) {
res = append(res, sl2[j])
j++
}
} else {
for i < len(sl1) {
res = append(res, sl1[i])
i++
}
}
return res
}
/*
inplace version
package main
import (
"fmt"
"os"
"bufio"
"strings"
"strconv"
"sort"
"sync"
"bytes"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Printf("Please enter integers space separated on one line\nints: ")
scanner.Scan()
ints := strings.Fields(scanner.Text())
isli := make([]int, 0, 1)
for i:=0;i<len(ints);i++ {
n,e := strconv.Atoi(ints[i])
if e != nil {
fmt.Printf("Error parsing input: %s\n", e)
return
}
isli = append(isli, n)
}
chunk := 4
delim := len(isli) / chunk
if len(isli) % chunk > 0 {delim++}
var wg sync.WaitGroup
var buf bytes.Buffer
wg.Add(chunk)
// Loop through and concurrently sort sections of the array
for i,x:=1,0; x<len(isli); x,i = x+delim, i+1 {
lb := x
rb := x + delim
if rb >= len(isli) {rb -= rb-len(isli)}
// Start a goroutine...
go csort(isli[lb:rb], &buf, &wg, i)
}
wg.Wait()
sort.Ints(isli)
fmt.Print(buf.String())
fmt.Print("Final Sorted array: ")
fmt.Println(isli)
}
func csort(isli []int, buf *bytes.Buffer, wg *sync.WaitGroup, i int) {
var lbuf bytes.Buffer
//lbuf.WriteString(fmt.Sprintf("loop %d before: ", i))
//lbuf.WriteString(fmt.Sprintln(isli))
sort.Ints(isli)
//lbuf.WriteString(fmt.Sprintf("loop %d after: ", i))
lbuf.WriteString(fmt.Sprint("Interim sorted array: "))
lbuf.WriteString(fmt.Sprintln(isli))
buf.WriteString(lbuf.String())
wg.Done()
}
*/
<file_sep>package main
import (
"fmt"
)
func main() {
var u uint8 = 255
fmt.Println(u, u+1, u*u)
fmt.Printf("u: %b\n", 65025)
var i int8 = 127
fmt.Println(i, i+1, i*i)
fmt.Printf("i: %b\n", i)
//bitwise operations
var x uint8 = 1<<1 | 1<<5
for i := uint(0); i < 8; i++ {
if x&(1<<i) != 0 {
fmt.Println(i)
}
}
//bitwise shift
fmt.Printf("%08b\n", x)
fmt.Printf("%08b\n", x<<5)
//signed bitshifts
var j int8 = +1
fmt.Printf("%08b\n", j)
fmt.Printf("%08b\n", j>>5)
}
<file_sep>package main
import (
"bufio"
"os"
"fmt"
"encoding/json"
"log"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
m := make(map[string]string)
//read name
scanner.Scan()
m["name"] = scanner.Text()
//read address
scanner.Scan()
m["address"] = scanner.Text()
json, err := json.MarshalIndent(m, "", "\t")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(json))
}
<file_sep>package main
import (
"testing"
)
func TestMax(t *testing.T) {
var tests = []struct {
vals []int
want int
}{
{[]int{1,2,3}, 3},
{[]int{-1}, -1},
{[]int{0}, 0},
// {[]int{}, 0},
}
for _, test := range tests {
if got := max(test.vals...); got != test.want {
t.Errorf("max(%d) = %d", test.vals, got)
}
}
}
func TestMin(t *testing.T) {
var tests = []struct {
vals []int
want int
}{
{[]int{1,2,3}, 1},
{[]int{-1}, -1},
{[]int{0}, 0},
}
for _, test := range tests {
if got := min(test.vals...); got != test.want {
t.Errorf("min(%d) = %d", test.vals, got)
}
}
}
<file_sep>/*
Write a Bubble Sort program in Go. The program should prompt the user to type in a sequence of up to 10 integers. The program should print the integers out on one line, in sorted order, from least to greatest. Use your favorite search tool to find a description of how the bubble sort algorithm works.
As part of this program, you should write a function called BubbleSort() which takes a slice of integers as an argument and returns nothing. The BubbleSort() function should modify the slice so that the elements are in sorted order.
A recurring operation in the bubble sort algorithm is the Swap operation which swaps the position of two adjacent elements in the slice. You should write a Swap() function which performs this operation. Your Swap() function should take two arguments, a slice of integers and an index value i which indicates a position in the slice. The Swap() function should return nothing, but it should swap the contents of the slice in position i with the contents in position i+1.
*/
package main
import (
"fmt"
)
func main() {
s := []int{}
f := .0
for i := 0; i < 10; i++ {
_, err := fmt.Scan(&f)
s = append(s, int(f))
if err != nil {
panic(err)
}
}
BubbleSort(s)
fmt.Println(s)
}
func BubbleSort(s []int) {
for i, _ := range s {
for j := 0; j < len(s) - i - 1; j++ {
if s[j] > s[j+1] {
Swap(s, j)
}
}
}
}
func Swap(s []int, i int) {
s[i], s[i+1] = s[i+1], s[i]
}
<file_sep>/*
Let us assume the following formula for displacement s as a function of time t, acceleration a, initial velocity vo, and initial displacement so.
s =½ a t2 + vot + so
Write a program which first prompts the user to enter values for acceleration, initial velocity, and initial displacement. Then the program should prompt the user to enter a value for time and the program should compute the displacement after the entered time.
You will need to define and use a function called GenDisplaceFn() which takes three float64 arguments, acceleration a, initial velocity vo, and initial displacement so. GenDisplaceFn() should return a function which computes displacement as a function of time, assuming the given values acceleration, initial velocity, and initial displacement. The function returned by GenDisplaceFn() should take one float64 argument t, representing time, and return one float64 argument which is the displacement travelled after time t.
For example, let’s say that I want to assume the following values for acceleration, initial velocity, and initial displacement: a = 10, vo = 2, so = 1. I can use the following statement to call GenDisplaceFn() to generate a function fn which will compute displacement as a function of time.
fn := GenDisplaceFn(10, 2, 1)
Then I can use the following statement to print the displacement after 3 seconds.
fmt.Println(fn(3))
And I can use the following statement to print the displacement after 5 seconds.
fmt.Println(fn(5))
*/
package main
import (
"fmt"
)
func main() {
a := prompt("acceleration")
v := prompt("velocity")
s := prompt("startPoint")
fn := genDisplaceFn(a, v, s)
fmt.Println(fn(3))
fmt.Println(fn(5))
}
func genDisplaceFn(a, v, s float64) func(float64) float64 {
return func(t float64) float64 {
return 0.5 * a * t * t + v * t + s
}
}
func prompt(s string) (f float64) {
fmt.Println("enter ", s)
_, err := fmt.Scan(&f)
if err != nil {
panic(err)
}
return
}
<file_sep>package main
import (
"fmt"
. "./intset"
)
func main() {
var x, y IntSet
x.AddAll(1,4,7,500)
y.AddAll(0,4,10,100,500,1000)
fmt.Println(x)
fmt.Println(x.String())
fmt.Println(y)
fmt.Println(y.String())
x.DifferenceWith(&y)
// y.DifferenceWith(&x)
fmt.Println(x)
fmt.Println(x.String())
}
<file_sep>package main
import (
"time"
"fmt"
)
type Employee struct {
ID int
Name string
Address string
DoB time.Time
Position string
Salary int
ManagerID int
}
func main() {
var dilbert Employee
dilbert.Salary -= 5000
fmt.Println(dilbert.Salary)
fmt.Printf("%T\n", dilbert)
var employeeOfTheMonth *Employee = &dilbert
employeeOfTheMonth.Position += " (proactive team player)"
fmt.Println(dilbert.Position)
fmt.Println(employeeOfTheMonth.Position)
}
<file_sep>/*
ex 7.3 Write a String method for the *tree type in gopl.io/ch4/treesort (§4.4) that reveals the sequence of values in the tree.
*/
package treesort
import (
"testing"
"fmt"
// "golang1training/7/7.3"
)
func TestString(t *testing.T) {
// creates binary tree
read := func() []tree {
var input = []struct {
val int
left int
right int
}{
{3, -1, -1},
{6, -1, -1},
{1, -1, -1},
{4, 0, 1},
{5, 2, 3},
}
var nodes []tree = make([]tree, len(input))
var val, indexLeft, indexRight int
for i := 0; i < len(input); i++ {
val, indexLeft, indexRight = input[i].val, input[i].left, input[i].right
nodes[i].value = val
if indexLeft >= 0 {
nodes[i].left = &nodes[indexLeft]
}
if indexRight >= 0 {
nodes[i].right = &nodes[indexRight]
}
}
return nodes
}
ti := read()
fmt.Println(&ti[len(ti)-1])//root
add(&ti[len(ti)-1], 10)
fmt.Println(&ti[len(ti)-1])
}
<file_sep>package main
import (
"fmt"
. "./intset"
)
func main() {
var x IntSet
x.AddAll(1,4,7,500)
fmt.Println(x.Elems())
fmt.Println(x.String())
y := x.Copy()
fmt.Println(y)
}
<file_sep>package main
import (
//"net/url"
"net/http"
"fmt"
"encoding/json"
"encoding/gob"
"strconv"
"os"
//"bufio"
"strings"
)
//We'll use this const for figuring out the max number of comics.
const RequestLastURL = "https://xkcd.com/info.0.json"
type ResponseResultLast struct {
Num int
}
type ResponseResult struct {
Num int
Transcript string
Alt string
}
func saveIdx(file string, idx map[string][]int) {
f, err := os.Create(file)
if err != nil {
panic("cant open file")
}
defer f.Close()
enc := gob.NewEncoder(f)
if err := enc.Encode(idx); err != nil {
panic("can't encode")
}
}
func main() {
resp, err := http.Get(RequestLastURL)
if err != nil {
fmt.Errorf("Error : %s", err)
}
var resultLast ResponseResultLast
var result ResponseResult
if err := json.NewDecoder(resp.Body).Decode(&resultLast); err != nil {
resp.Body.Close()
fmt.Errorf("Error : %s", err)
}
resp.Body.Close()
var ResponseResults[]ResponseResult
//Loop through all comics. Read the data we need.
//for i := 1; i <= 100; i++ {//for testing purposes
for i := 1; i <= resultLast.Num; i++ {
RequestURL := "https://xkcd.com/" + strconv.FormatInt(int64(i), 10) + "/info.0.json"
resp, err := http.Get(RequestURL)
if err != nil {
fmt.Errorf("Error: %s", err)
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
resp.Body.Close()
fmt.Errorf("Error : %s", err)
}
resp.Body.Close()
ResponseResults = append(ResponseResults, result)
fmt.Println(RequestURL)
}
//Build the index.
idx := make(map[string][]int)
for _, result := range ResponseResults {
for _, word := range strings.Split(result.Alt," ") {
idx[word] = append(idx[word], result.Num)
}
}
for _, result := range ResponseResults {
for _, word := range strings.Split(result.Transcript," ") {
idx[word] = append(idx[word], result.Num)
}
}
//Save to a file
saveIdx("idx", idx)
//var idx2 map[string][]int
//idx2 = loadIdx("idx")
}
<file_sep>package main
import (
"fmt"
. "./intset"
)
func main() {
var x IntSet
x.AddAll(1,4,7)
fmt.Println(x.String())
}
<file_sep>// Write a function to populate a mapping from element names p, div, span, and so on to the number of elements with that name in an HTML document tree.
package main
import (
"fmt"
"os"
"golang.org/x/net/html"
)
func main() {
doc, err := html.Parse(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "popmap: %v\n", err)
os.Exit(1)
}
m := make(map[string]int)
popmap(m, nil, doc)
fmt.Printf("%v\n", m)
}
// popmap populates map wich elements and their counts
func popmap(elements map[string]int, stack []string, n *html.Node) {
if n.Type == html.ElementNode {
stack = append(stack, n.Data) // push tag
elements[n.Data]++
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
popmap(elements, stack, c)
}
}
/*
//!+html
package html
type Node struct {
Type NodeType
Data string
Attr []Attribute
FirstChild, NextSibling *Node
}
type NodeType int32
const (
ErrorNode NodeType = iota
TextNode
DocumentNode
ElementNode
CommentNode
DoctypeNode
)
type Attribute struct {
Key, Val string
}
func Parse(r io.Reader) (*Node, error)
//!-html
*/
<file_sep>package main
import "fmt"
import ("crypto/sha256"
//"golang1training/4.1/popcount"//this is just for practice
)
func main() {
c1 := sha256.Sum256([]byte("x"))
c2 := sha256.Sum256([]byte("X"))
fmt.Printf("%x\n%x\n%t\n%T\n", c1, c2, c1 == c2, c1)
// Output:
// 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881
// 4b68ab3847feda7d6c62c1fbcbeebfa35eab7351ed5e78f4ddadea5df64b8015
// false
// [32]uint8
n := 0
for i := range c1 {
for j := uint(0); j < 64; j++ {
//fmt.Printf("%8b\n", c1[i])
//fmt.Printf("%8b\n", c2[i])
//fmt.Printf("%8b\n", 1<<j)
if c1[i]&(1<<j) != c2[i]&(1<<j) {
n++
}
}
}
fmt.Println(n)
//fmt.Printf("%v", popcount.PopCount(255))
}<file_sep>/* 5.15 Write variadic functions max and min, analogous to sum. What should these functions do when called with no arguments? Write variants that require at least one argument. */
package main
func max(vals ...int) int {
if len(vals) == 0 {
panic("no parameters, at least one parameter required for max() function")
}
max := vals[0]
for _, v := range vals {
if v > max {
max = v
}
}
return max
}
func min(vals ...int) int {
if len(vals) == 0 {
panic("no parameters, at least one parameter required for max() function")
}
min := vals[0]
for _, v := range vals {
if v < min {
min = v
}
}
return min
}
<file_sep>package main
import (
"os"
"fmt"
"encoding/gob"
"strings"
"strconv"
"net/http"
"encoding/json"
)
var usage string = `usage:
xkcd [search term]
`
func usageDie() {
fmt.Fprintln(os.Stderr, usage)
os.Exit(1)
}
type ResponseResultTranscript struct {
Transcript string
}
func loadIdx(file string) (idx map[string][]int) {
f, err := os.Open(file)
if err != nil {
panic("cant open file")
}
defer f.Close()
enc := gob.NewDecoder(f)
if err := enc.Decode(&idx); err != nil {
panic("can't decode")
}
return idx
}
func loadTranscript(number int) {
var result ResponseResultTranscript
RequestURL := "https://xkcd.com/" + strconv.Itoa(number) + "/info.0.json"
resp, err := http.Get(RequestURL)
if err != nil {
fmt.Errorf("Error: %s", err)
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
resp.Body.Close()
fmt.Errorf("Error : %s", err)
}
resp.Body.Close()
fmt.Println(result.Transcript, "\n")
}
func main() {
var idx map[string][]int
idx = loadIdx("idx")
if len(os.Args) < 2 {
usageDie()
}
args := strings.Join(os.Args[1:]," ")
for _, number := range idx[args] {
//printing link
fmt.Println("https://xkcd.com/" + strconv.Itoa(number) + "/", "\n")
//printing transcript
loadTranscript(number)
}
//https://xkcd.com/1403/info.0.json
}<file_sep>package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type Anymal struct {
food string
locomotion string
noise string
}
func (a *Anymal) Eat() {
fmt.Println(a.food)
}
func (a *Anymal) Move() {
fmt.Println(a.locomotion)
}
func (a *Anymal) Speak() {
fmt.Println(a.noise)
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
cow := Anymal{"grass", "walk", "moo"}
bird := Anymal{"worms", "fly", "peep"}
snake := Anymal{"mice", "slither", "hsss"}
for {
fmt.Println(">")
scanner.Scan()
v := scanner.Text()
an := strings.Split(v, " ")[0]
ac := strings.Split(v, " ")[1]
if an == "cow" && ac == "eat" {
cow.Eat()
}
if an == "cow" && ac == "move" {
cow.Move()
}
if an == "cow" && ac == "speak" {
cow.Speak()
}
if an == "bird" && ac == "eat" {
bird.Eat()
}
if an == "bird" && ac == "move" {
bird.Move()
}
if an == "bird" && ac == "speak" {
bird.Speak()
}
if an == "snake" && ac == "eat" {
snake.Eat()
}
if an == "snake" && ac == "move" {
snake.Move()
}
if an == "snake" && ac == "speak" {
snake.Speak()
}
}
}
<file_sep>package main
import ("fmt"
"crypto/sha256"
"crypto/sha512"
"bufio"
"os"
)
func main() {
flags := os.Args[1:]
var flag string
if len(flags) == 0 {
flag = ""
} else {
flag = flags[0]
}
input := bufio.NewScanner(os.Stdin)
fmt.Printf("%v\n", flag)
for input.Scan() {
switch flag {
case "SHA384":
c1 := sha512.Sum384([]byte(input.Text()))
fmt.Printf("%x\n", c1)
case "SHA512":
c1 := sha512.Sum512([]byte(input.Text()))
fmt.Printf("%x\n", c1)
default:
c1 := sha256.Sum256([]byte(input.Text()))
fmt.Printf("%x\n", c1)
}
}
}<file_sep>package github
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
func GetIssue(owner string, repo string, number string) (*Issue, error) {
url := strings.Join([]string{APIURL, "repos", owner, repo, "issues", number}, "/")
resp, err := http.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("read query failed: %s: %s", url, resp.Status)
}
var issue Issue
if err := json.NewDecoder(resp.Body).Decode(&issue); err != nil {
fmt.Println(issue)
resp.Body.Close()
return nil, err
}
resp.Body.Close()
return &issue, nil
}<file_sep>//Write a function to print the contents of all text nodes in an HTML document tree. Do not descend into <script> or <style> elements, since their contents are not visible in a web browser.
package main
import (
"fmt"
"os"
"golang.org/x/net/html"
)
func main() {
doc, err := html.Parse(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "htmltext %v\n", err)
os.Exit(1)
}
htmltext(doc)
}
// htmltext prints text content from web page
func htmltext(n *html.Node) {
if n.Type == html.TextNode {
fmt.Printf("n.Data: %v\n", n.Data)
//fmt.Printf("n: %v\n", n)
//fmt.Printf("n.Type: %v\n", n.Type)
//fmt.Printf("n.Data: %v\n", n.Data)
//fmt.Printf("n.Attr: %v\n", n.Attr)
//fmt.Printf("n.FirstChild: %v\n", n.FirstChild)
//fmt.Printf("n.NextSibling: %v\n", n.NextSibling)
}
if !(n.Data == "script" || n.Data == "style") {
for c := n.FirstChild; c != nil; c = c.NextSibling {
htmltext(c)
}
}
}
/*
//!+html
package html
type Node struct {
Type NodeType
Data string
Attr []Attribute
FirstChild, NextSibling *Node
}
type NodeType int32
const (
ErrorNode NodeType = iota
TextNode
DocumentNode
ElementNode
CommentNode
DoctypeNode
)
type Attribute struct {
Key, Val string
}
func Parse(r io.Reader) (*Node, error)
//!-html
*/
<file_sep>package main
import (
"fmt"
"bytes"
"unicode/utf8"
)
func main() {
rs := []rune{'世','g','o',' ', ' ','l','a', '界', ' ' ,'n'}
bs := []byte(string(rs))
fmt.Println(rs)
reverseUTF8(bs)
reverse(bs)
fmt.Println(bytes.Runes(bs))
}
//reverse runes only
func reverseUTF8(s []byte) {
for len(s) > 0 {
_, size := utf8.DecodeRune(s)
if size > 1 {
reverse(s[:size])
}
s = s[size:]
}
}
//reverse whole slice
func reverse(s []byte) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}<file_sep>// getByID prints the node by its ID.
package main
import (
"fmt"
"net/http"
"os"
"golang.org/x/net/html"
)
func main() {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "usage: getbyid id url url url...")
}
id := os.Args[1]
for _, url := range os.Args[2:] {
getNodeByID(url, id)
}
}
func getNodeByID(url, id string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
doc, err := html.Parse(resp.Body)
if err != nil {
return err
}
fmt.Printf("Result: %v\n", ElementByID(doc, id))
return nil
}
func ElementByID(doc *html.Node, id string) *html.Node {
var relmnt *html.Node
startTrav := func(n *html.Node) bool {
for _, a := range n.Attr {
if a.Key == "id" && a.Val == id {
relmnt = n
return false
}
}
return true
}
forEachNode(doc, startTrav, nil)
return relmnt
}
func forEachNode(n *html.Node, pre, post func(n *html.Node) bool) {
if pre != nil {
if !pre(n) {
return
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
forEachNode(c, pre, post)
}
//we dont need this actually
if post != nil {
fmt.Println("post !=nil")
}
}
<file_sep>// Cf converts its numeric argument to Celsius and Fahrenheit.
package main
import (
"fmt"
"gopl.ex/2.3/popcount"
)
func main() {
var pc [256]byte
for i := range pc {
pc[i] = pc[i/2] + byte(i&1)
fmt.Printf("pc[i]: %v\n", pc[i])
}
fmt.Printf("255: %b\n", byte(255))
fmt.Printf("PopCount: %b\n", popcount.PopCount(1))
}
<file_sep>//testing package usage
package main
import (
"fmt"
"gopl.ex/2.1/tempconv"
)
func main() {
fmt.Printf("Cold! %v\n", tempconv.BoilingK)
fmt.Printf("Kelvin! %v\n",tempconv.CToK(0))
}
<file_sep>package reader
import (
"bytes"
"strings"
"testing"
)
func TestNewReader(t *testing.T) {
s := "limit reader"
b := &bytes.Buffer{}
l := LimitReader(strings.NewReader(s), 5)
n, _ := b.ReadFrom(l)
if n != 5 {
t.Logf("n=%d err", n)
t.Fail()
}
if b.String() != "limit" {
t.Logf("%s != %s", b.String(), s)
}
}
<file_sep>package main
import (
"fmt"
)
func main() {
fmt.Printf("%v", ys(0,2,8,6,-5))
}
func ys(x0, y0, x1, y1, x float64) float64 {
return y0 + (x - x0)/(x1 - x0) * (y1 - y0)
}
<file_sep>package main
import (
"fmt"
. "./intset"
)
func main() {
var x, y IntSet
x.Add(0)
x.Add(1)
x.Add(2)
x.Add(3)
x.Add(4)
x.Add(5)
x.Add(6)
x.Add(7)
fmt.Println(x)
fmt.Println(x.String())
fmt.Println(x.Len())
x.Remove(2)
fmt.Println(x)
fmt.Println(x.String())
fmt.Println("Copy: ", x.Copy())
y = *x.Copy()
x.Clear()
fmt.Println(x)
fmt.Println(x.String())
x.Add(1)
fmt.Println(x.String())
fmt.Println(y.String())
}
<file_sep>/* Ex. 7.4
The strings.NewReader function returns a value that satisfies the io.Reader interface (and others) by reading from its argument, a string. Implement a simple version of NewReader yourself, and use it to make the HTML parser (§5.2) take input from a string.
*/
package reader
import (
"io"
)
type stringReader struct {
s string
}
func (r *stringReader) Read(p []byte) (n int, err error) {
n = copy(p, r.s)
r.s = r.s[n:]
if len(r.s) == 0 {
err = io.EOF // Must set EOF, otherwise it does not end
}
return
}
func NewReader(s string) io.Reader {
return &stringReader{s}
}
<file_sep>// Copyright © 2016 <NAME> & <NAME>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 58.
//!+
// Surface computes an SVG rendering of a 3-D surface function.
package main
import (
"fmt"
"math"
"net/http"
"log"
"strconv"
"net/url"
)
const (
xyrange = 30.0 // axis ranges (-xyrange..+xyrange)
angle = math.Pi / 6 // angle of x, y axes (=30°)
)
var sin30, cos30 = math.Sin(angle), math.Cos(angle) // sin(30°), cos(30°)
var width, height, cells int// size, number of grid cells
var xyscale, zscale float64
func main() {
handler := func(w http.ResponseWriter, r *http.Request) {
m, err := url.ParseQuery(r.URL.RawQuery)
//fmt.Println(r.URL.RawQuery)
width, err = strconv.Atoi(m["width"][0])
check(err)
height, err = strconv.Atoi(m["height"][0])
check(err)
cells, err = strconv.Atoi(m["cells"][0])
check(err)
fill := m["fill"][0]
//res, err := strconv.ParseFloat(m["res"][0], 64)
//check(err)
xyscale = float64(width) / 2 / xyrange // pixels per x or y unit
zscale = float64(height) * 0.1 // pixels per z unit
w.Header().Set("Content-Type", "image/svg+xml")
_, err = fmt.Fprintf(w, "<svg xmlns='http://www.w3.org/2000/svg' "+
"style='stroke: grey; fill: %s; stroke-width: 0.7' "+
"width='%d' height='%d'>", fill, width, height)
check(err)
//calculating z max and z min
var zmax, zmin, z float64 = 0, -0, 0
for i := 0; i < cells; i++ {
for j := 0; j < cells; j++ {
_, _, z = corner(+i, j)
if math.IsNaN(z) || math.IsInf(z, 0) {continue}
if z > zmax {
zmax = z
}
if z < zmin {
zmin = z
}
}
}
for i := 0; i < cells; i++ {
for j := 0; j < cells; j++ {
ax, ay, z := corner(i+1, j)
if math.IsNaN(ax) || math.IsInf(ax, 0) {continue}
if math.IsNaN(ay) || math.IsInf(ay, 0) {continue} //skip polygon if it has non-finite value
bx, by, _ := corner(i, j)
if math.IsNaN(bx) || math.IsInf(bx, 0) {continue}
if math.IsNaN(by) || math.IsInf(by, 0) {continue} //skip polygon if it has non-finite value
cx, cy, _ := corner(i, j+1)
if math.IsNaN(cx) || math.IsInf(cx, 0) {continue}
if math.IsNaN(cy) || math.IsInf(cy, 0) {continue} //skip polygon if it has non-finite value
dx, dy, _ := corner(i+1, j+1)
if math.IsNaN(dx) || math.IsInf(dx, 0) {continue}
if math.IsNaN(dy) || math.IsInf(dy, 0) {continue} //skip polygon if it has non-finite value
_, err = fmt.Fprintf(w, "<polygon points='%g,%g %g,%g %g,%g %g,%g' stroke='%s'/>\n",
ax, ay, bx, by, cx, cy, dx, dy, color(z, zmax, zmin))
check(err)
}
}
_, err = fmt.Fprintf(w, "</svg>")
check(err)
}//handler := func
http.HandleFunc("/", handler) // each request calls handler
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func corner(i, j int) (float64, float64, float64) {
// Find point (x,y) at corner of cell (i,j).
x := xyrange * (float64(i)/float64(cells) - 0.5)
y := xyrange * (float64(j)/float64(cells) - 0.5)
// Compute surface height z.
z := f(x, y)
// Project (x,y,z) isometrically onto 2-D SVG canvas (sx,sy).
sx := float64(width)/2 + (x-y)*cos30*xyscale
sy := float64(height)/2 + (x+y)*sin30*xyscale - z*zscale
return sx, sy, z
}
func f(x, y float64) float64 {
r := math.Hypot(x, y) // distance from (0,0)
return math.Sin(r) / r
}
func check(err error) {
if err != nil {
panic(err)
}
}
//extrapolation function
func ys(x0, y0, x1, y1, x float64) float64 {
return y0 + (x - x0)/(x1 - x0) * (y1 - y0)
}
//function to convert z coordinate into color from #ff0000 to #0000ff
func color(z, zmax, zmin float64) string {
blue := 255
red := 255
if z > 0 {
red = int(ys(0,255,zmax,0, z))
//if red < 0 {red = 0}
//if red > 255 {red = 255}
} else {
blue = int(ys(zmin,0,0,255, z))
//if blue < 0 {blue = 0}
}
return "#" + string(fmt.Sprintf("%02x", blue)) + "00" + string(fmt.Sprintf("%02x", red))
}
<file_sep>// Copyright © 2016 <NAME> & <NAME>.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 58.
//!+
// Surface computes an SVG rendering of a 3-D surface function.
package main
import (
"fmt"
"math"
"os"
"bufio"
)
const (
width, height = 600, 320 // canvas size in pixels
cells = 100 // number of grid cells
xyrange = 30.0 // axis ranges (-xyrange..+xyrange)
xyscale = width / 2 / xyrange // pixels per x or y unit
zscale = height * 0.1 // pixels per z unit
angle = math.Pi / 6 // angle of x, y axes (=30°)
)
var sin30, cos30 = math.Sin(angle), math.Cos(angle) // sin(30°), cos(30°)
func main() {
//writing to a file
f, err := os.OpenFile("/tmp/yourfile", os.O_APPEND|os.O_WRONLY, 0600)//try to open file
if err != nil {
f, err = os.Create("/tmp/yourfile")//create new file if can't open
}
check(err)
defer f.Close()
w := bufio.NewWriter(f)
_, err = fmt.Fprintf(w, "<svg xmlns='http://www.w3.org/2000/svg' "+
"style='stroke: grey; fill: white; stroke-width: 0.7' "+
"width='%d' height='%d'>", width, height)
check(err)
//calculating z max and z min
var zmax, zmin, z float64 = 0, -0, 0
for i := 0; i < cells; i++ {
for j := 0; j < cells; j++ {
_, _, z = corner(+i, j)
if math.IsNaN(z) || math.IsInf(z, 0) {continue}
if z > zmax {
zmax = z
}
if z < zmin {
zmin = z
}
}
}
for i := 0; i < cells; i++ {
for j := 0; j < cells; j++ {
ax, ay, z := corner(i+1, j)
if math.IsNaN(ax) || math.IsInf(ax, 0) {continue}
if math.IsNaN(ay) || math.IsInf(ay, 0) {continue} //skip polygon if it has non-finite value
bx, by, _ := corner(i, j)
if math.IsNaN(bx) || math.IsInf(bx, 0) {continue}
if math.IsNaN(by) || math.IsInf(by, 0) {continue} //skip polygon if it has non-finite value
cx, cy, _ := corner(i, j+1)
if math.IsNaN(cx) || math.IsInf(cx, 0) {continue}
if math.IsNaN(cy) || math.IsInf(cy, 0) {continue} //skip polygon if it has non-finite value
dx, dy, _ := corner(i+1, j+1)
if math.IsNaN(dx) || math.IsInf(dx, 0) {continue}
if math.IsNaN(dy) || math.IsInf(dy, 0) {continue} //skip polygon if it has non-finite value
_, err = fmt.Fprintf(w, "<polygon points='%g,%g %g,%g %g,%g %g,%g' stroke='%s'/>\n",
ax, ay, bx, by, cx, cy, dx, dy, color(z, zmax, zmin))
check(err)
}
}
_, err = fmt.Fprintf(w, "</svg>")
check(err)
w.Flush()
}
func corner(i, j int) (float64, float64, float64) {
// Find point (x,y) at corner of cell (i,j).
x := xyrange * (float64(i)/cells - 0.5)
y := xyrange * (float64(j)/cells - 0.5)
// Compute surface height z.
z := f(x, y)
// Project (x,y,z) isometrically onto 2-D SVG canvas (sx,sy).
sx := width/2 + (x-y)*cos30*xyscale
sy := height/2 + (x+y)*sin30*xyscale - z*zscale
return sx, sy, z
}
func f(x, y float64) float64 {
r := math.Hypot(x, y) // distance from (0,0)
return math.Sin(r) / r
}
func check(err error) {
if err != nil {
panic(err)
}
}
//extrapolation function
func ys(x0, y0, x1, y1, x float64) float64 {
return y0 + (x - x0)/(x1 - x0) * (y1 - y0)
}
//function to convert z coordinate into color from #ff0000 to #0000ff
func color(z, zmax, zmin float64) string {
blue := 255
red := 255
if z > 0 {
red = int(ys(0,255,zmax,0, z))
//if red < 0 {red = 0}
//if red > 255 {red = 255}
} else {
blue = int(ys(zmin,0,0,255, z))
//if blue < 0 {blue = 0}
}
return "#" + string(fmt.Sprintf("%02x", blue)) + "00" + string(fmt.Sprintf("%02x", red))
}
<file_sep>package main
import (
"fmt"
"os"
"bytes"
"strings"
"strconv"
)
func main() {
for i := 1; i < len(os.Args); i++ {
fmt.Printf(" %s\n", comma(os.Args[i]))
}
}
// comma inserts commas in a non-negative decimal integer string.
func comma(s string) string {
var buf1 bytes.Buffer
var buf2 bytes.Buffer
var s1, s2 string
if dot := strings.LastIndex(s, "."); dot >= 0 {
s1 = s[:dot]
s2 = s[dot+1:]
}
var n int = -1
var previous string
for i := len(s1)+1; i > 0; i-- {
v := s[i-1:i]
if _, err := strconv.Atoi(previous); err == nil {
n++
}
if n >= 3 {
buf1.WriteString(",")
n = 0
}
fmt.Fprintf(&buf1, "%v", string(previous))
previous = v
if i == 1 {
fmt.Fprintf(&buf1, "%v", string(previous))
}
}
n = -1
for i := 0; i < len(s2); i++ {
v := s2[i:i+1]
if _, err := strconv.Atoi(v); err == nil {
n++
}
if n >= 3 {
buf2.WriteString(",")
n = 0
}
fmt.Fprintf(&buf2, "%v", string(v))
}
return reverse(buf1.String()) + buf2.String()
}
func reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}<file_sep>/* 5.16 variadic strings.Join f-n */
package main
import "fmt"
func main() {
fmt.Println(Join(";", "1", "2", "3"))
}
func Join(sep string, a ...string) string {
res := ""
if len(a) == 0 {
return ""
}
for _, v := range a[:len(a)-1] {
res = res + v + sep
}
res = res + a[len(a) - 1]
return res
}
<file_sep>/*
Write a program which prompts the user to enter a floating point number and prints the integer which is a truncated version of the floating point number that was entered. Truncation is the process of removing the digits to the right of the decimal place.
*/
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"log"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter float: ")
str, _ := reader.ReadString('\n')
_, err := strconv.ParseFloat(str[:len(str)-1], 64)
if err != nil {
log.Fatal(err)
}
fmt.Println(strings.Split(str, ".")[0])
}
/*
//versions:
func main() {
fmt.Print("enter a floating point number: ")
var f float64
_, err := fmt.Scan(&f)
if err != nil {
panic(err)
}
i := int64(f)
fmt.Printf("truncated version: %v", i)
}
*/
<file_sep>package main
import (
"bufio"
"fmt"
"os"
)
func main() {
countsWords := make(map[string]int)
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
countsWords[scanner.Text()]++
}
for c, n := range countsWords {
fmt.Printf("%q\t%d\n", c, n)
}
}
<file_sep>package main
import (
"fmt"
)
const ( KB, MB, GB, TB, PB, EB, ZB, YB = 1e3, 1e6, 1e9, 1e12, 1e15, 1e18, 1e21, 1e24 )
func main() {
fmt.Printf("%b", MB)
}<file_sep>package main
import (
"fmt"
"sync"
"time"
)
type chopS struct{ sync.Mutex }
type philo struct {
leftCS, rightCS *chopS
number int
permis chan int
done chan int
}
func (p *philo) eat() {
for i := 0; i < 3; i++ {
permis := <-p.permis
p.leftCS.Lock()
p.rightCS.Lock()
fmt.Println("starting to eat", p.number)
fmt.Println(time.Now())
time.Sleep(1 * time.Second)
fmt.Println("finishing to eat", p.number)
p.rightCS.Unlock()
p.leftCS.Unlock()
p.done <- permis
}
}
// limits number of eating philos
func host(permis chan int, done chan int) {
permis <- 1
permis <- 1
for {
permis <- <-done
}
}
func main() {
var permis = make(chan int, 2)
var done = make(chan int, 2)
cSticks := make([]*chopS, 5)
for i := 0; i < 5; i++ {
cSticks[i] = new(chopS)
}
philos := make([]*philo, 5)
for i := 0; i < 5; i++ {
fmt.Println(i, (i+1)%5)
philos[i] = &philo{cSticks[i], cSticks[(i+1)%5], i, permis, done}
}
for i := 0; i < 5; i++ {
go philos[i].eat()
}
go host(permis, done)
time.Sleep(10 * time.Second)
}
<file_sep>package main
import (
"testing"
"strings"
)
func TestExpand(t *testing.T) {
var tests = []struct {
s string
functn func(string) string
want string
}{
{"$foolish big$foot", reverse, "ooflish bigooft"},
{"$foolish big$foot", strings.Title, "Foolish bigFoot"},
}
for _, test := range tests {
if got := expand(test.s, test.functn); got != test.want {
t.Errorf("expand(%s) = %s" , test.s, got)
}
}
}
<file_sep>/*
Write a program which prompts the user to enter a string. The program searches through the entered string for the characters ‘i’, ‘a’, and ‘n’. The program should print “Found!” if the entered string starts with the character ‘i’, ends with the character ‘n’, and contains the character ‘a’. The program should print “Not Found!” otherwise. The program should not be case-sensitive, so it does not matter if the characters are upper-case or lower-case.
Examples: The program should print “Found!” for the following example entered strings, “ian”, “Ian”, “iuiygaygn”, “I d skd a efju N”. The program should print “Not Found!” for the following strings, “ihhhhhn”, “ina”, “xian”.
*/
package main
import (
"bufio"
"os"
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("^[iI].*[aA].*[nN]$")
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter string: ")
str, _ := reader.ReadString('\n')
b := []byte(str[:len(str)-1])
if len(re.Find(b)) > 0 {
fmt.Println("Found!")
return
}
fmt.Println("Not Found!")
}
/*
//versions:
func main() {
fmt.Println("Please enter a string:")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
s := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Errorf("Problems reading input: %e.\n", err)
}
s = strings.ToLower(s)
if strings.Contains(s, "a") && strings.HasPrefix(s, "i") && strings.HasSuffix(s, "n") {
fmt.Println("Found!")
} else {
fmt.Println("Not Found!")
}
}
func main()
reader := bufio.NewReader(os.Stdin)
str, _ := reader.ReadString('\n')
str = strings.TrimSpace(str)
str = strings.ToLower(str)
if strings.HasPrefix(str, "i") && strings.HasSuffix(str, "n") && strings.Contains(str, "a") {
fmt.Println("Found!")
} else {
fmt.Println("Not Found!")
}
}
func main() {
const foundString = "Found!"
const notFoundString = "Not Found!"
fmt.Println("Enter string:")
r := bufio.NewReader(os.Stdin)
input, err := r.ReadString('\n')
if err != nil {
fmt.Println(notFoundString)
} else {
cleanedInput := strings.ToLower(input)
var startsWithI = strings.HasPrefix(cleanedInput, "i")
var containsAInBetween = strings.Index(cleanedInput, "a") > 0
var endsWithN = strings.HasSuffix(cleanedInput, "n\n")
if startsWithI && containsAInBetween && endsWithN {
fmt.Println(foundString)
} else {
fmt.Println(notFoundString)
}
}
}
*/
<file_sep>package main
import (
"fmt"
)
func main() {
var r int = 2//rotate by this number
c := []int{0, 1, 2, 3, 4, 5}
c = append(c[r:],c[:r]...)
fmt.Println(c)
}
<file_sep>package main
import (
"fmt"
//"sort"
)
// prereqs maps computer science courses to their prerequisites.
var prereqs = map[string][]string{
"algorithms": {"data structures"},
"calculus": {"linear algebra"},
"compilers": {
"data structures",
"formal languages",
"computer organization",
},
"data structures": {"discrete math"},
"databases": {"data structures"},
"discrete math": {"intro to programming"},
"formal languages": {"discrete math"},
"networks": {"operating systems"},
"operating systems": {"data structures", "computer organization"},
"programming languages": {"data structures", "computer organization"},
}
func main() {
for i, course := range topoSort(prereqs) {
fmt.Printf("%d:\t%s\n", i+1, course)
}
}
//managed to change slices with map, although it wasn't good idea
func topoSort(m map[string][]string) []string {
var list []string
seen := make(map[string]bool)
var visitAll func(items map[string]string)
visitAll = func(items map[string]string) {
for _, item := range items {
if !seen[item] {
seen[item] = true
keys2 := make(map[string]string)
for _, key2 := range m[item] {
keys2[key2] = key2
}
visitAll(keys2)
list = append(list, item)
}
}
}
keys := make(map[string]string)
for key := range m {
keys[key] = key
}
visitAll(keys)
return list
}
|
1da5b39e3c5db93d069c59f6b09bd9970b1ca148
|
[
"Markdown",
"Go"
] | 58 |
Go
|
shepardo/golang1training
|
f95da29ce52ac8932d996304f86950c13dd5f406
|
c06dd92d23a8ef4ebaf7a313b14625c486eb2229
|
refs/heads/master
|
<file_sep># confman-demo
Demonstrates the definition and use of Integrated Extension Functions using Saxon-HE.
Saxon-HE does not read a configuration file, which is one way of registering functions coded in Java with Saxon-PE or Saxon-EE.
Another way is to find the configuration in your Java code and register them yourself. Here is an example.
This example was written specifically to test the way I wanted to do this in DSpace, so it may be more elaborate than would be
necessary in the general case.
<file_sep>/*
* Copyright 2019 Indiana University. All rights reserved.
*
* <NAME>, IUPUI University Library, Dec 2, 2019
*/
package edu.iupui.ulib.saxon_integrated_functions;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.Int64Value;
import net.sf.saxon.value.IntegerValue;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;
/**
* Define a Saxon integrated extension function for access to the DSpace
* ConfigurationManager's getProperty method.
*
* @author <NAME> <<EMAIL>>
*/
public class ConfmanGetPropertyDefinition
extends ExtensionFunctionDefinition {
@Override
public StructuredQName getFunctionQName() {
return new StructuredQName("confman", "http://edu.iupui.ulib/dspace", "getProperty");
}
@Override
public SequenceType[] getArgumentTypes() {
return new SequenceType[]{SequenceType.SINGLE_STRING};
}
@Override
public SequenceType getResultType(SequenceType[] sts) {
return SequenceType.SINGLE_STRING;
}
@Override
public ExtensionFunctionCall makeCallExpression() {
return new ExtensionFunctionCall() {
@Override
public Sequence call(XPathContext context, Sequence[] arguments)
throws XPathException {
String key = ((StringValue) arguments[0]).getStringValue();
String value = ConfigurationManager.getProperty(key);
return StringValue.makeStringValue(value);
}
};
}
}
|
82e82867ca3eaaa150a005802bcc3ebb9960e131
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
mwoodiupui/confman-demo
|
b2877149275ad57995a60a9fff25eac4bda11ff0
|
4a03b5946d5043b1af6f7ed0b0ad5cd052e6db7c
|
refs/heads/master
|
<file_sep>package mn.client.body.nullbody.bug;
import io.micronaut.http.client.Client;
import mn.client.body.nullbody.bug.test.TestAPI;
@Client("/test")
public interface TestClient extends TestAPI {
// *************************************************
// **** TEST WILL WORK WHEN THIS IS UNCOMMENTED ****
// @Override
// public String testMethod(String testString);
}
<file_sep>FROM openjdk:8u171-alpine3.7
RUN apk --no-cache add curl
COPY build/libs/*-all.jar mn-client-body-null-bug.jar
CMD java ${JAVA_OPTS} -jar mn-client-body-null-bug.jar<file_sep># mn-client-body-null-bug
|
7fa4641eaf1a5955e401ed9788f2ca29a8c378f6
|
[
"Markdown",
"Java",
"Dockerfile"
] | 3 |
Java
|
alanbino/mn-client-body-null-bug
|
22ea0a639c77d05a2211c1e0856f4a5f0db939f1
|
19956c6d9e1a1e02fb6a54ab5310c22c611c94c1
|
refs/heads/master
|
<repo_name>xiaoxin901008/python<file_sep>/t1.py
from tkinter import *
import random
fontsize = 30
colors = ['red','green','blue','yellow','orange','cyan','purple']
#打开一个窗口,取随机颜色,并更改label的前景色
def onSpam():
popup = Toplevel()
color = random.choice(colors)
Label(popup, text='Popup', bg='black', fg=color).pack(fill=BOTH)
mainLabel.config(fg=color)
#随机更改label的前景色,每隔250毫秒更改一次
def onFlip():
mainLabel.config(fg=random.choice(colors))
main.after(250,onFlip)
#加大label字体,每隔100秒触发一次
def onGrow():
global fontsize
fontsize += 5
mainLabel.config(font=('arial', fontsize, 'italic'))
main.after(100, onGrow)
main = Tk() #创建主窗口
mainLabel = Label(main, text='Fun Gui!', relief=RAISED) #创建label
mainLabel.config(font=('arial', fontsize, 'italic'), fg='cyan', bg='navy') #配置label字体背景颜色和前景颜色
mainLabel.pack(side=TOP,expand=YES,fill=BOTH) #显示label
Button(main, text='spam', command=onSpam).pack(fill=X) #创建按钮,触发onSpam
Button(main, text='flip', command=onFlip).pack(fill=X) #触发onFlip
Button(main, text='grow', command=onGrow).pack(fill=X) #触发onGrow
main.mainloop() #启动主窗口<file_sep>/Preview/webserver.py
"""
用Python实现一个HTTP web服务器,它知道如何运行服务器端CGI脚本:
从当前工作目录提供文件和脚本;Python脚本必须存储在 webdir\cgi-bin或
webdir\htbin中;
"""
import os, sys
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '.' # 存放HTML文件和cgi-bin脚本文件夹的所在
port = 80 # 缺省http://localhost/,也可以使用http://localhost:xxxx/
os.chdir(webdir) #进入运行目录
srvaddr = ('',port) #定义服务器地址和端口
srvobj = HTTPServer(srvaddr, CGIHTTPRequestHandler) #创建HTTPServer对象
srvobj.serve_forever() # 以守护进程永久运行
|
f5df0ce5aa59a9a4dcf3ec8894e004f6d70b1bc2
|
[
"Python"
] | 2 |
Python
|
xiaoxin901008/python
|
e069f9e45f3a98b41a202a946b94be9d8d22dc71
|
fa68c77124d5aafcd23cbbf756cc80cd90cff751
|
refs/heads/master
|
<file_sep>import {connect} from 'react-redux';
import {Dispatch} from 'redux';
import Employees from './Employees';
import {
addEmployee,
changeNewFirstName,
changeNewLastName,
EmployeesType,
removeEmployee,
setEmployees
} from '../../redux/employeesReducer';
import {RootStateType} from '../../redux/redux-store';
//Typing for Users component props
export type EmployeesPropsType = mapStatePropsType & mapDispatchPropsType
type mapStatePropsType = {
newFirstName: string
newLastName: string
employees: EmployeesType[]
}
type mapDispatchPropsType = {
addEmployee: () => void
setEmployees: (users: EmployeesType[]) => void
removeEmployee: (employeeId: number | string) => void
changeNewFirstName: (newFirstName: string) => void
changeNewLastName: (newLastName: string) => void
}
const mapStateToProps = (state: RootStateType): mapStatePropsType => {
return {
newFirstName: state.employeesPage.newFirstName,
newLastName: state.employeesPage.newLastName,
employees: state.employeesPage.employees
}
}
const mapDispatchToProps = (dispatch: Dispatch): mapDispatchPropsType => {
return {
setEmployees: (employees: EmployeesType[]) => {
dispatch(setEmployees(employees))
},
removeEmployee: (employeeId: number | string) => {
dispatch(removeEmployee(employeeId))
},
changeNewFirstName: (newFirstName: string) => {
dispatch(changeNewFirstName(newFirstName))
},
changeNewLastName: (newLastName: string) => {
dispatch(changeNewLastName(newLastName))
},
addEmployee: () => {
dispatch(addEmployee())
}
}
}
export const EmployeesContainer = connect(mapStateToProps, mapDispatchToProps)(Employees);<file_sep>import {combineReducers, createStore} from 'redux';
import {employeesReducer} from './employeesReducer';
const rootReducer = combineReducers({
employeesPage: employeesReducer,
})
export type RootStateType = ReturnType<typeof rootReducer>
export const store = createStore(rootReducer);<file_sep>import {v1} from 'uuid'; // Добавил библиотеку для генерации id => string
//Action creators types
export type EmployeesActionTypes = ReturnType<typeof setEmployees>
| ReturnType<typeof removeEmployee>
| ReturnType<typeof addEmployee>
| ReturnType<typeof changeNewFirstName>
| ReturnType<typeof changeNewLastName>
//Action creators
export const setEmployees = (employees: EmployeesType[]) => ({type: 'SET_EMPLOYEES', employees} as const);
export const removeEmployee = (employeeId: number | string) => ({type: 'REMOVE_EMPLOYEE', employeeId} as const);
export const changeNewFirstName = (newFirstName: string) => ({type: 'CHANGE_NEW_FIRST_NAME', newFirstName} as const);
export const changeNewLastName = (newLastName: string) => ({type: 'CHANGE_NEW_LAST_NAME', newLastName} as const);
export const addEmployee = () => ({type: 'ADD_EMPLOYEE'} as const)
//Typing for initialState
export type InitialStateType = typeof initialState
export type EmployeesType = {
id: number | string
first_name: string | null
last_name: string | null
avatar: string | null
email: string | null
}
const initialState = {
newFirstName: '',
newLastName: '',
employees: [] as EmployeesType[]
}
export const employeesReducer = (state: InitialStateType = initialState, action: EmployeesActionTypes): InitialStateType => {
switch (action.type) {
case 'SET_EMPLOYEES':
return {
...state,
employees: [...action.employees]
}
case 'REMOVE_EMPLOYEE': {
const stateCopy = {...state}
stateCopy.employees = stateCopy.employees.filter(em => em.id !== action.employeeId)
return stateCopy
}
case 'CHANGE_NEW_FIRST_NAME':
return {...state, newFirstName: action.newFirstName}
case 'CHANGE_NEW_LAST_NAME':
return {...state, newLastName: action.newLastName}
case 'ADD_EMPLOYEE':
if (state.newFirstName && state.newLastName) {
return {
...state,
employees: [{
id: v1(),
first_name: state.newFirstName,
last_name: state.newLastName,
avatar: null,
email: null
}, ...state.employees],
newFirstName: '',
newLastName: ''
}
}
return state
default:
return state
}
}
|
a2ad5507038f67c8b46711c5aa0823e5343583f8
|
[
"TypeScript"
] | 3 |
TypeScript
|
KuhniaDruggist/testFromResliv
|
830ed59b6d40937b6e237afb87ca92f317f7de0c
|
b9db5f7a5fad1d6381e7998f1faa1f2897e7fb72
|
refs/heads/master
|
<file_sep>require 'pry'
class Triangle
attr_accessor :triangle_sides
@triangle_sides = [@a, @b, @c]
def initialize(a, b, c)
@a = a
@b = b
@c = c
end
def kind
if @a<=0 || @b<=0 || @c<=0 || @a+@b <= @c || @a+@c <= @b || @b+@c <= @a
raise TriangleError
elsif @a==@b && @b==@c
return :equilateral
elsif @a==@b || @b==@c || @a==@c
return :isosceles
elsif @a!=@b && @b!=@c && @a!=@c
return :scalene
end
end
# Error class used in part 2. No need to change this code.
class TriangleError < StandardError
#triangle error code
puts "Ce n'est pas un triangle."
end
end
# attr_accessor :sides
# def initialize(side_1, side_2, side_3)
# @sides = [side_1, side_2, side_3].sort
# valid_triangle?
# end
# def valid_triangle?
# if @sides.any? {|side| side <= 0}
# raise TriangleError
# elsif @sides[0] + @sides[1] <= @sides[2]
# raise TriangleError
# end
# end
# def kind
# self.sides
# if (@sides[0] == @sides[1]) && (@sides[1] == @sides[2])
# :equilateral
# elsif (@sides[0] == @sides[1]) || (@sides[1] == @sides[2])
# :isosceles
# else
# :scalene
# end
# end
|
314506337114c40f022f5c169b602fdbd322c746
|
[
"Ruby"
] | 1 |
Ruby
|
NiushaH/triangle-classification-v-000
|
b761b1674981eae30dcd3ddbe8d7f85667cfa834
|
af9c97cb8a2320d951a621c92b8213fa643640f1
|
refs/heads/master
|
<repo_name>kashesoft/clean-architecture-android<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/interactors/ReadUserInteractor.kt
package com.kashesoft.cleanarchitecture.app.bl.interactors
import com.kashesoft.cleanarchitecture.app.bl.entities.User
import com.kashesoft.cleanarchitecture.app.bl.gateways.UserGateway
import com.kashesoft.cleanarchitecture.app.bl.gateways.base.Params
import com.kashesoft.cleanarchitecture.app.bl.interactors.base.BaseInteractor
import io.reactivex.Observable
import io.reactivex.observers.DisposableObserver
import javax.inject.Inject
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
class ReadUserInteractor @Inject
internal constructor(internal val userGateway: UserGateway) :
BaseInteractor<Params.Input.Ids, Params.Output.Entities<User>, ReadUserInteractor.OnResult>() {
interface OnResult {
fun readUserOnOutput(output: Params.Output.Entities<User>)
fun readUserOnSuccess()
fun readUserOnFailure(error: Throwable)
}
override fun buildObservable(input: Params.Input.Ids): Observable<Params.Output.Entities<User>> {
return this.userGateway.readUsers(input)
}
override fun buildObserver(onResult: OnResult): DisposableObserver<Params.Output.Entities<User>> {
return object : DisposableObserver<Params.Output.Entities<User>>() {
override fun onNext(output: Params.Output.Entities<User>) {
onResult.readUserOnOutput(output)
}
override fun onComplete() {
onResult.readUserOnSuccess()
}
override fun onError(error: Throwable) {
onResult.readUserOnFailure(error)
}
}
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/gateways/base/Params.kt
package com.kashesoft.cleanarchitecture.app.bl.gateways.base
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
public class Params {
public class Input {
public data class Id(val id: String)
public data class Ids(val ids: List<Int>)
public data class Entity<E>(val entity: E)
}
public class Output {
public data class Entity<E>(val status: String, val message: String, val entity: E?)
public data class Entities<E>(val status: String, val message: String, val entities: List<E>, val progress: Int)
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/interactors/base/BaseInteractor.kt
package com.kashesoft.cleanarchitecture.app.bl.interactors.base
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
abstract class BaseInteractor<Input, Output, OnResult> internal constructor(
private val ioScheduler: Scheduler = Schedulers.io(),
private val uiScheduler: Scheduler = AndroidSchedulers.mainThread()
) {
private val subscription: CompositeDisposable = CompositeDisposable()
protected abstract fun buildObservable(input: Input): Observable<Output>
protected abstract fun buildObserver(onResult: OnResult): DisposableObserver<Output>
fun execute(input: Input, onResult: OnResult) {
val observable = buildObservable(input)
.subscribeOn(ioScheduler)
.observeOn(uiScheduler)
val observer = buildObserver(onResult)
addObserver(observable.subscribeWith(observer))
}
fun dispose() {
if (!subscription.isDisposed) {
subscription.dispose()
}
}
private fun addObserver(observer: Disposable) {
subscription.add(observer)
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/presenters/base/BasePresenter.kt
package com.kashesoft.cleanarchitecture.app.bl.presenters.base
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.OnLifecycleEvent
import android.os.Bundle
import android.support.annotation.CallSuper
import android.util.Log
import com.kashesoft.cleanarchitecture.app.bl.contracts.base.BaseContract
import com.kashesoft.cleanarchitecture.app.bl.interactors.base.BaseInteractor
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
abstract class BasePresenter<V : BaseContract.View> : LifecycleObserver, BaseContract.Presenter<V> {
private val tag: String
get() = this::class.simpleName!!
private val trail = ":::::::::::::::"
final override val stateBundle: Bundle = Bundle()
override final var view: V? = null
private set
override val isViewAttached: Boolean
get() = view != null
private val interactors = mutableListOf<BaseInteractor<*, *, *>>()
protected abstract fun provideInteractors(): Array<BaseInteractor<*, *, *>>
override fun attachLifecycle(lifecycle: Lifecycle) {
lifecycle.addObserver(this)
}
override fun detachLifecycle(lifecycle: Lifecycle) {
lifecycle.removeObserver(this)
}
override fun attachView(view: V) {
this.view = view
}
override fun detachView() {
view = null
}
@CallSuper
override fun onCreatePresenter() {
logTrailed("onCreatePresenter")
interactors.addAll(provideInteractors())
}
@CallSuper
override fun onDestroyPresenter() {
logTrailed("onDestroyPresenter")
if (!stateBundle.isEmpty) {
stateBundle.clear()
}
for (interactor in interactors) {
interactor.dispose()
}
interactors.clear()
}
@CallSuper
protected open fun onCreateView() {
logTrailed("onCreateView")
}
@CallSuper
protected open fun onStartView() {
logTrailed("onStartView")
}
@CallSuper
protected open fun onResumeView() {
logTrailed("onResumeView")
}
@CallSuper
protected open fun onPauseView() {
logTrailed("onPauseView")
}
@CallSuper
protected open fun onStopView() {
logTrailed("onStopView")
}
@CallSuper
protected open fun onDestroyView() {
logTrailed("onDestroyView")
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_CREATE)
private fun onCreateLifecycleEvent() {
onCreateView()
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_START)
private fun onStartLifecycleEvent() {
onStartView()
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_RESUME)
private fun onResumeLifecycleEvent() {
onResumeView()
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_PAUSE)
private fun onPauseLifecycleEvent() {
onPauseView()
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_STOP)
private fun onStopLifecycleEvent() {
onStopView()
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_DESTROY)
private fun onDestroyLifecycleEvent() {
onDestroyView()
}
protected fun log(message: String) {
Log.d(tag, message)
}
private fun logTrailed(message: String) {
Log.d(tag, "$trail$message$trail")
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/AppComponent.kt
package com.kashesoft.cleanarchitecture.app
import android.app.Application
import com.kashesoft.cleanarchitecture.app.al.AlModule
import com.kashesoft.cleanarchitecture.app.bl.BlModule
import com.kashesoft.cleanarchitecture.app.cl.ClModule
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-16.
*/
@Singleton
@Component(modules = arrayOf(
AndroidSupportInjectionModule::class,
AppModule::class,
AlModule::class,
BlModule::class,
ClModule::class
))
interface AppComponent : AndroidInjector<App> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/App.kt
package com.kashesoft.cleanarchitecture.app
import dagger.android.AndroidInjector
import dagger.android.support.DaggerApplication
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
class App : DaggerApplication() {
lateinit var appComponent: AppComponent
override fun applicationInjector(): AndroidInjector<App> {
appComponent = DaggerAppComponent
.builder()
.application(this)
.build()
return appComponent
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/al/BaseViewModel.kt
package com.kashesoft.cleanarchitecture.app.al
import android.arch.lifecycle.ViewModel
import com.kashesoft.cleanarchitecture.app.bl.contracts.base.BaseContract
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
class BaseViewModel<V : BaseContract.View, P : BaseContract.Presenter<V>> : ViewModel() {
private var presenter: P? = null
internal fun setPresenter(presenter: P) {
if (this.presenter == null) {
this.presenter = presenter
}
}
internal fun getPresenter(): P? {
return this.presenter
}
override fun onCleared() {
super.onCleared()
presenter!!.onDestroyPresenter()
presenter = null
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/al/fragments/base/BaseFragment.kt
package com.kashesoft.cleanarchitecture.app.al.fragments.base
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.annotation.CallSuper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.kashesoft.cleanarchitecture.app.bl.contracts.base.BaseContract
import com.kashesoft.cleanarchitecture.app.al.BaseViewModel
import com.kashesoft.cleanarchitecture.app.al.LAYOUT_NOT_DEFINED
import com.kashesoft.cleanarchitecture.app.al.Viewable
import dagger.android.support.AndroidSupportInjection
import dagger.android.support.DaggerFragment
import javax.inject.Provider
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
abstract class BaseFragment<V : BaseContract.View, P : BaseContract.Presenter<V>> :
DaggerFragment(), BaseContract.View {
protected lateinit var presenter: P
protected open lateinit var presenterProvider: Provider<P>
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val viewable = this::class.annotations.find { it is Viewable } as? Viewable
val layoutResId = viewable!!.layout
if (layoutResId != LAYOUT_NOT_DEFINED) {
return inflater!!.inflate(layoutResId, container, false)
}
return null
}
@CallSuper
@Suppress("UNCHECKED_CAST")
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
AndroidSupportInjection.inject(this)
super.onViewCreated(view, savedInstanceState)
val viewModel: BaseViewModel<V, P> = ViewModelProviders.of(this)
.get(BaseViewModel::class.java) as BaseViewModel<V, P>
var isPresenterCreated = false
if (viewModel.getPresenter() == null) {
viewModel.setPresenter(presenterProvider.get())
isPresenterCreated = true
}
presenter = viewModel.getPresenter()!!
presenter.attachLifecycle(lifecycle)
presenter.attachView(this as V)
if (isPresenterCreated) {
presenter.onCreatePresenter()
}
}
@CallSuper
override fun onDestroyView() {
super.onDestroyView()
presenter.detachLifecycle(lifecycle)
presenter.detachView()
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/al/activities/base/BaseActivity.kt
package com.kashesoft.cleanarchitecture.app.al.activities.base
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.annotation.CallSuper
import com.kashesoft.cleanarchitecture.app.al.BaseViewModel
import com.kashesoft.cleanarchitecture.app.al.LAYOUT_NOT_DEFINED
import com.kashesoft.cleanarchitecture.app.al.Viewable
import com.kashesoft.cleanarchitecture.app.bl.contracts.base.BaseContract
import dagger.android.AndroidInjection
import dagger.android.support.DaggerAppCompatActivity
import javax.inject.Provider
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
abstract class BaseActivity<V : BaseContract.View, P : BaseContract.Presenter<V>> :
DaggerAppCompatActivity(), BaseContract.View {
protected lateinit var presenter: P
protected open lateinit var presenterProvider: Provider<P>
@CallSuper
@Suppress("UNCHECKED_CAST")
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
val viewable = this::class.annotations.find { it is Viewable } as? Viewable
val layoutResId = viewable!!.layout
if (layoutResId != LAYOUT_NOT_DEFINED) {
setContentView(layoutResId)
}
val viewModel: BaseViewModel<V, P> = ViewModelProviders.of(this)
.get(BaseViewModel::class.java) as BaseViewModel<V, P>
var isPresenterCreated = false
if (viewModel.getPresenter() == null) {
viewModel.setPresenter(presenterProvider.get())
isPresenterCreated = true
}
presenter = viewModel.getPresenter()!!
presenter.attachLifecycle(lifecycle)
presenter.attachView(this as V)
if (isPresenterCreated) {
presenter.onCreatePresenter()
}
}
@CallSuper
override fun onDestroy() {
super.onDestroy()
presenter.detachLifecycle(lifecycle)
presenter.detachView()
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/al/Viewable.kt
package com.kashesoft.cleanarchitecture.app.al
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-22.
*/
const val LAYOUT_NOT_DEFINED = -1
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Viewable(val layout: Int = LAYOUT_NOT_DEFINED)
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/contracts/PrimaryContract.kt
package com.kashesoft.cleanarchitecture.app.bl.contracts
import com.kashesoft.cleanarchitecture.app.bl.contracts.base.BaseContract
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
interface PrimaryContract {
interface View : BaseContract.View {
fun showProgress()
fun hideProgress()
fun refreshProgress(percent: Int)
}
interface Presenter : BaseContract.Presenter<PrimaryContract.View> {
fun readUsers(userIds: List<Int>)
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/BlModule.kt
package com.kashesoft.cleanarchitecture.app.bl
import com.kashesoft.cleanarchitecture.app.bl.contracts.PrimaryContract
import com.kashesoft.cleanarchitecture.app.bl.gateways.UserGateway
import com.kashesoft.cleanarchitecture.app.bl.interactors.ReadUserInteractor
import com.kashesoft.cleanarchitecture.app.bl.presenters.PrimaryPresenter
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-22.
*/
@Module
class BlModule {
@Provides
internal fun providePrimaryContract_Presenter(interactor: ReadUserInteractor): PrimaryContract.Presenter {
return PrimaryPresenter(interactor)
}
@Provides
@Singleton
internal fun provideReadUserInteractor(userGateway: UserGateway): ReadUserInteractor {
return ReadUserInteractor(userGateway)
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/entities/User.kt
package com.kashesoft.cleanarchitecture.app.bl.entities
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
data class User(var id: Int, val name: String)
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/presenters/PrimaryPresenter.kt
package com.kashesoft.cleanarchitecture.app.bl.presenters
import com.kashesoft.cleanarchitecture.app.bl.contracts.PrimaryContract
import com.kashesoft.cleanarchitecture.app.bl.entities.User
import com.kashesoft.cleanarchitecture.app.bl.gateways.base.Params
import com.kashesoft.cleanarchitecture.app.bl.interactors.ReadUserInteractor
import com.kashesoft.cleanarchitecture.app.bl.interactors.base.BaseInteractor
import com.kashesoft.cleanarchitecture.app.bl.presenters.base.BasePresenter
import javax.inject.Inject
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
class PrimaryPresenter @Inject
constructor(val readUserInteractor: ReadUserInteractor): BasePresenter<PrimaryContract.View>(), PrimaryContract.Presenter,
ReadUserInteractor.OnResult {
companion object {
private val PROGRESS_PERCENT = "PROGRESS_PERCENT"
private val IN_PROGRESS = "IN_PROGRESS"
}
override fun provideInteractors(): Array<BaseInteractor<*, *, *>> {
return arrayOf(readUserInteractor)
}
override fun readUsers(userIds: List<Int>) {
readUserInteractor.execute(Params.Input.Ids(userIds), this)
startProgress()
}
override fun onCreateView() {
super.onCreateView()
if (inProgress()) {
restartProgress()
}
}
override fun onDestroyView() {
super.onDestroyView()
if (inProgress()) {
stopProgress()
}
}
override fun readUserOnOutput(output: Params.Output.Entities<User>) {
updateProgress(output.progress)
}
override fun readUserOnSuccess() {
finishProgress()
}
override fun readUserOnFailure(error: Throwable) {
finishProgress()
error.printStackTrace()
// TODO: Add error message
}
private fun startProgress() {
log("start progress!")
stateBundle.putBoolean(IN_PROGRESS, true)
stateBundle.putInt(PROGRESS_PERCENT, 0)
restartProgress()
}
private fun restartProgress() {
log("restart progress!")
view?.showProgress()
val percent = stateBundle.getInt(PROGRESS_PERCENT)
view?.refreshProgress(percent)
}
private fun updateProgress(progress: Int) {
log("update progress: $progress%")
stateBundle.putInt(PROGRESS_PERCENT, progress)
view?.refreshProgress(progress)
}
private fun stopProgress() {
log("stop progress!")
view?.hideProgress()
}
private fun finishProgress() {
log("finish progress!")
stateBundle.putBoolean(IN_PROGRESS, false)
stateBundle.putInt(PROGRESS_PERCENT, 0)
stopProgress()
}
private fun inProgress(): Boolean {
return stateBundle.getBoolean(IN_PROGRESS)
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/AppModule.kt
package com.kashesoft.cleanarchitecture.app
import android.app.Application
import android.content.Context
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-16.
*/
@Module
class AppModule {
@Provides
@Singleton
internal fun provideContext(application: Application): Context {
return application
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/cl/ClModule.kt
package com.kashesoft.cleanarchitecture.app.cl
import com.kashesoft.cleanarchitecture.app.bl.gateways.UserGateway
import com.kashesoft.cleanarchitecture.app.cl.repositories.UserRepository
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-22.
*/
@Module
class ClModule {
@Provides
@Singleton
internal fun provideUserGateway(): UserGateway {
return UserRepository()
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/contracts/base/BaseContract.kt
package com.kashesoft.cleanarchitecture.app.bl.contracts.base
import android.arch.lifecycle.Lifecycle
import android.os.Bundle
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-15.
*/
interface BaseContract {
interface View
interface Presenter<V : View> {
val stateBundle: Bundle
val view: V?
val isViewAttached: Boolean
fun attachLifecycle(lifecycle: Lifecycle)
fun detachLifecycle(lifecycle: Lifecycle)
fun attachView(view: V)
fun detachView()
fun onCreatePresenter()
fun onDestroyPresenter()
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/al/activities/PrimaryActivity.kt
package com.kashesoft.cleanarchitecture.app.al.activities
import android.app.ProgressDialog
import android.os.Bundle
import android.support.annotation.CallSuper
import android.view.View
import com.kashesoft.cleanarchitecture.R
import com.kashesoft.cleanarchitecture.app.al.Viewable
import com.kashesoft.cleanarchitecture.app.al.activities.base.BaseActivity
import com.kashesoft.cleanarchitecture.app.bl.contracts.PrimaryContract
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
import javax.inject.Provider
@Viewable(layout = R.layout.activity_main)
class PrimaryActivity : BaseActivity<PrimaryContract.View, PrimaryContract.Presenter>(),
PrimaryContract.View, View.OnClickListener {
private lateinit var progressDialog: ProgressDialog
@Inject override lateinit var presenterProvider: Provider<PrimaryContract.Presenter>
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setUpView()
}
override fun onClick(v: View) {
val userIds = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
presenter.readUsers(userIds)
}
override fun showProgress() {
progressDialog.show()
}
override fun hideProgress() {
progressDialog.dismiss()
}
override fun refreshProgress(percent: Int) {
progressDialog.progress = percent
}
private fun setUpView() {
//
button.setOnClickListener(this)
//
val progressDialog = ProgressDialog(this)
progressDialog.setMessage("Loading")
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
progressDialog.setCancelable(false)
progressDialog.progress = 0
this.progressDialog = progressDialog
}
}
<file_sep>/README.md
# clean-architecture-android
A sample app that shows clean architecture approach for Android applications.
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/al/AlModule.kt
package com.kashesoft.cleanarchitecture.app.al
import com.kashesoft.cleanarchitecture.app.AppModule
import com.kashesoft.cleanarchitecture.app.al.activities.PrimaryActivity
import dagger.Module
import dagger.android.ContributesAndroidInjector
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-16.
*/
@Module
abstract class AlModule {
@ContributesAndroidInjector(modules = arrayOf(AppModule::class))
internal abstract fun bindPrimaryActivity(): PrimaryActivity
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/cl/repositories/UserRepository.kt
package com.kashesoft.cleanarchitecture.app.cl.repositories
import com.kashesoft.cleanarchitecture.app.bl.entities.User
import com.kashesoft.cleanarchitecture.app.bl.gateways.UserGateway
import com.kashesoft.cleanarchitecture.app.bl.gateways.base.Params
import io.reactivex.Observable
import javax.inject.Inject
/**
* Copyright (c) 2017 Kashesoft. All rights reserved.
* Created on 2017-10-16.
*/
class UserRepository @Inject
constructor() : UserGateway {
private val userNames = listOf("<NAME>", "<NAME>", "<NAME>",
"<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>")
override fun fetchUsers(input: Params.Input.Ids): Observable<Params.Output.Entities<User>> {
return Observable.create<Params.Output.Entities<User>> { emitter ->
for ((index, id) in input.ids.withIndex()) {
Thread.sleep(1000)
val user = User(id, userNames[index])
val progress = 100 * (index + 1) / (input.ids.size)
emitter.onNext(Params.Output.Entities("success", "", listOf(user), progress))
}
Thread.sleep(1000)
emitter.onComplete()
}
}
override fun saveUser(input: Params.Input.Entity<User>): Observable<Params.Output.Entity<User>> {
return Observable.create<Params.Output.Entity<User>> { emitter ->
Thread.sleep(1000)
val user = input.entity
user.id *= -1
emitter.onNext(Params.Output.Entity("success", "", user))
emitter.onComplete()
}
}
override fun createUser(input: Params.Input.Entity<User>): Observable<Params.Output.Entity<User>> {
return Observable.create<Params.Output.Entity<User>> { emitter ->
Thread.sleep(1000)
val user = input.entity
user.id *= -1
emitter.onNext(Params.Output.Entity("success", "", user))
emitter.onComplete()
}
}
override fun readUsers(input: Params.Input.Ids): Observable<Params.Output.Entities<User>> {
return Observable.create<Params.Output.Entities<User>> { emitter ->
for ((index, id) in input.ids.withIndex()) {
Thread.sleep(1000)
val user = User(id, userNames[index])
val progress = 100 * (index + 1) / (input.ids.size)
emitter.onNext(Params.Output.Entities("success", "", listOf(user), progress))
}
Thread.sleep(1000)
emitter.onComplete()
}
}
override fun updateUser(input: Params.Input.Entity<User>): Observable<Params.Output.Entity<User>> {
return Observable.create<Params.Output.Entity<User>> { emitter ->
Thread.sleep(1000)
val user = input.entity
user.id *= -1
emitter.onNext(Params.Output.Entity("success", "", user))
emitter.onComplete()
}
}
override fun deleteUser(input: Params.Input.Entity<User>): Observable<Params.Output.Entity<User>> {
return Observable.create<Params.Output.Entity<User>> { emitter ->
Thread.sleep(1000)
val user = input.entity
user.id *= -1
emitter.onNext(Params.Output.Entity("success", "", user))
emitter.onComplete()
}
}
}
<file_sep>/app/src/main/java/com/kashesoft/cleanarchitecture/app/bl/gateways/UserGateway.kt
package com.kashesoft.cleanarchitecture.app.bl.gateways
import com.kashesoft.cleanarchitecture.app.bl.entities.User
import com.kashesoft.cleanarchitecture.app.bl.gateways.base.Params
import io.reactivex.Observable
interface UserGateway {
// database operations
fun fetchUsers(input: Params.Input.Ids): Observable<Params.Output.Entities<User>>
fun saveUser(input: Params.Input.Entity<User>): Observable<Params.Output.Entity<User>>
// server CRUD operations
fun createUser(input: Params.Input.Entity<User>): Observable<Params.Output.Entity<User>>
fun readUsers(input: Params.Input.Ids): Observable<Params.Output.Entities<User>>
fun updateUser(input: Params.Input.Entity<User>): Observable<Params.Output.Entity<User>>
fun deleteUser(input: Params.Input.Entity<User>): Observable<Params.Output.Entity<User>>
}
|
6fc9b2fe7defd1ad8c216ddf02a9a80e13fb4aa6
|
[
"Markdown",
"Kotlin"
] | 22 |
Kotlin
|
kashesoft/clean-architecture-android
|
d37e1223d2f767c10360885f5ae03cc775d24d19
|
1e575afe5f66a345058e541f0b8bb09a0507d3eb
|
refs/heads/master
|
<file_sep>package handlers
import "text/template"
var styledTemplate = template.Must(template.New("experiment").Parse(`
<html>
<head>
<style>
body {
font-family: "arial";
font-size: 16px;
color: #333;
position: absolute;
margin:0;
width:100%;
height:100%;
}
.goodbye {
color: #fff;
background-color: #f00;
}
dt {
color:#777;
}
.envs {
margin:10px
}
.image {
position: absolute;
top: 0px;
right: 0px;
}
.hello {
position:absolute;
top:0;
height:120px;
font-family: arial;
left:0;
right:0;
text-align:center;
font-size:50px;
font-weight:bold;
line-height:120px;
color: black;
}
.goodbye .hello {
color: #fff;
}
.my-index {
position: absolute;
top: 120px;
height: 30px;
color: #333;
font-size: 30px;
line-height: 30px;
left: 0;
right: 0;
text-align: center;
color: black;
font-family: arial;
}
.goodbye .my-index {
color: #fff;
}
.index {
position:absolute;
top:176px;
height:120px;
left:0;
right:0;
color: #fff;
font-size: 80px;
line-height: 120px;
background-color:rgb(1,169,130);
text-align:center;
font-family: arial;
}
.goodbye .index {
background-color:rgb(235, 13, 5);
}
.mid-color {
position:absolute;
top:296px;
height:120px;
left:0;
right:0;
color: #fff;
font-size: 30px;
line-height: 120px;
background-color: rgb(95,122,118);
text-align: center;
font-family: arial;
}
.goodbye .mid-color {
background-color: rgb(206, 26, 4);
}
.bottom-color {
position:absolute;
top:416px;
bottom:0;
left:0;
right:0;
background-color: rgb(198,201,202);
}
.goodbye .bottom-color {
background-color: rgb(185, 4, 9);
}
</style>
</head>
<body class="{{.Class}}">
{{.Body}}
</body>
</html>
`))
type Body struct {
Body string
Class string
}
|
df44c529c8369376fde2416b4f3903d2cd71a874
|
[
"Go"
] | 1 |
Go
|
nwright-nz/HelionDevPlat-Scale-Demo
|
b1b7cc13e7aa21019bd4599af4ef29ebeaf58b74
|
74bc2aa00e22b5b87d58271db8381e672ac1976b
|
refs/heads/master
|
<file_sep>require_relative '../lib/gilded_rose'
describe "#update_quality" do
context "with normal items" do
let(:items) {
[
Item.new("Normal item", 5, 10),
Item.new("Normal item", -1, 10)
]
}
before { update_quality(items) }
it "decreases quality and sell_in by one" do
expect(items[0].sell_in).to eq(4)
expect(items[0].quality).to eq(9)
end
it "decreases quality by two when sell_in is negative" do
expect(items[1].quality).to eq(8)
end
end
context "with backstage pass items" do
let(:items) {
[
Item.new("Backstage passes to a TAFKAL80ETC concert", 15, 10),
Item.new("Backstage passes to a TAFKAL80ETC concert", 11, 10),
Item.new("Backstage passes to a TAFKAL80ETC concert", 6, 10),
Item.new("Backstage passes to a TAFKAL80ETC concert", 0, 10),
Item.new("Backstage passes to a TAFKAL80ETC concert", 2, 48),
]
}
before { update_quality(items) }
it "increases quality when sell_in is over 10" do
expect(items[0].quality).to eq(11)
expect(items[0].sell_in).to eq(14)
end
it "increases quality by 2 when 5 < sell_in <= 10" do
expect(items[1].quality).to eq(12)
end
it "increases quality by 3 when 0 < sell_in <= 5" do
expect(items[2].quality).to eq(13)
end
it "sets quality to 0 when concert has passed" do
expect(items[3].quality).to eq(0)
end
it "caps quality at 50" do
expect(items[4].quality).to eq(50)
end
end
context "with aged brie items" do
let(:items) {
[
Item.new("Aged Brie", 5, 10),
Item.new("Aged Brie", 3, 50)
]
}
before { update_quality(items) }
it "increases quality and decreases sell_in" do
expect(items[0].sell_in).to eq(4)
expect(items[0].quality).to eq(11)
end
it "quality does not increase above 50" do
expect(items[1].quality).to eq(50)
end
end
context "with Sulfuras items" do
let(:initial_sell_in) { nil }
let(:initial_quality) { 80 }
let(:name) { "Sulfuras, Hand of Ragnaros" }
let(:item) { Item.new(name, initial_sell_in, initial_quality) }
before { update_quality([item]) }
it "keeps quality set at 80 and no sell_in" do
expect(item.quality).to eq(80)
expect(item.sell_in).to eq(nil)
end
end
context "with Conjured items" do
let(:items) {
[
Item.new("Conjured", 5, 10),
Item.new("Conjured", 1, 1),
Item.new("Conjured", -1, 10)
]
}
before { update_quality(items) }
it "decreases quality by two and sell_in by one" do
expect(items[0].sell_in).to eq(4)
expect(items[0].quality).to eq(8)
end
it "decreases quality by four when sell_in is negative" do
expect(items[2].quality).to eq(6)
end
it "does not allow quality to be negative" do
expect(items[1].quality).to eq(0)
end
end
end
<file_sep>def update_quality(items)
items.each do |item|
if item.name == 'Sulfuras, Hand of Ragnaros'
item.quality = 80
item.sell_in = nil
next
end
item.sell_in -= 1
if item.name == '<NAME>'
quality_change = 1
elsif item.name == 'Backstage passes to a TAFKAL80ETC concert'
if item.sell_in <= 0
quality_change = -item.quality
elsif item.sell_in <= 5
quality_change = 3
elsif item.sell_in <= 10
quality_change = 2
else
quality_change = 1
end
elsif item.name == 'Conjured'
quality_change = item.sell_in < 0 ? -4 : -2
else # normal items
quality_change = item.sell_in < 0 ? -2 : -1
end
item.quality += quality_change
# enforce 0 < quality < 50
if item.quality > 50
item.quality = 50
elsif item.quality < 0
item.quality = 0
end
end
end
######### DO NOT CHANGE BELOW #########
Item = Struct.new(:name, :sell_in, :quality)
|
9fc1d057d3639b772f43239ef086967c3c5a083d
|
[
"Ruby"
] | 2 |
Ruby
|
natmattison/gilded-rose
|
b574431bc1d89eda19677d2003390101189582eb
|
6f46f81e560c47c84d7c5c036b31146a3115e6b2
|
refs/heads/main
|
<repo_name>Yma-Van2020/backend_work<file_sep>/fundamentals/fundamentals/User.py
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
def make_withdrawl(self, amount):
self.account_balance -= amount
def display_user_balance(self):
print("User: " + self.name + ", Balance: $" + str(self.account_balance))
def transfer_money(self, other_user, amount):
self.account_balance -= amount
other_user.account_balance += amount
Jack = User("<NAME>", "<EMAIL>")
Wendy = User("<NAME>", "<EMAIL>")
Betty = User("<NAME>", "<EMAIL>")
Jack.make_deposit(200)
Jack.make_deposit(100)
Jack.make_deposit(50)
Jack.make_withdrawl(120)
Jack.transfer_money(Betty,30)
Jack.display_user_balance()
Wendy.make_deposit(20)
Wendy.make_deposit(10)
Wendy.make_withdrawl(2)
Wendy.make_withdrawl(1)
Wendy.display_user_balance()
Betty.make_deposit(50)
Betty.make_withdrawl(1)
Betty.make_withdrawl(2)
Betty.make_withdrawl(3)
Betty.display_user_balance()<file_sep>/flask_mysql/validation/email validation/flask_app/controllers/emails.py
from flask_app import app
from flask import render_template,redirect,request,session,flash
from flask_app.models.email import Email
@app.route("/")
def index():
return render_template("index.html")
@app.route("/success")
def dis_email():
emails = Email.get_all()
return render_template("display.html", emails = emails)
@app.route('/create', methods=["POST"])
def create_email():
data = {
"address" : request.form["address"],
}
if not Email.validate_email(request.form):
return redirect("/")
elif (Email.get_one(request.form["address"])) != ():
return redirect("/")
else:
Email.create(data)
return redirect("/success")
<file_sep>/fundamentals/fundamentals/users_with_bankacc.py
class BankAccount:
all_acc = []
def __init__(self, int_rate = 0.01, balance = 0):
self.int_rate = int_rate
self.balance = balance
BankAccount.all_acc.append(self)
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print("The current balance is: " + str(self.balance))
def yield_interest(self):
self.balance = self.balance + (self.balance * self.int_rate)
return self
@classmethod
def print_acc_info(cls):
for account in cls.all_acc:
account.display_account_info()
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account = BankAccount(int_rate = 0.015, balance = 0)
def make_deposit(self, amount):
self.account.deposit(amount)
return self
def make_withdrawl(self, amount):
self.account.withdraw(amount)
return self
def display_user_balance(self):
print("User: " + self.name + ", Balance: $" + str(self.account.balance))
def transfer_money(self, other_user, amount):
self.account.balance -= amount
other_user.account.balance += amount
return self
Jack = User("<NAME>", "<EMAIL>")
Wendy = User("<NAME>", "<EMAIL>")
Betty = User("<NAME>", "<EMAIL>")
Jack.make_deposit(200).make_deposit(100).make_deposit(50).make_withdrawl(120).transfer_money(Betty,30).display_user_balance()
Wendy.make_deposit(20).make_deposit(10).make_withdrawl(2).make_withdrawl(1).display_user_balance()
Betty.make_deposit(50).make_withdrawl(1).make_withdrawl(2).make_withdrawl(3).display_user_balance()<file_sep>/fundamentals/fundamentals/bankAccount.py
class BankAccount:
all_acc = []
def __init__(self, int_rate = 0.01, balance = 0):
self.int_rate = int_rate
self.balance = balance
BankAccount.all_acc.append(self)
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print("The current balance is: " + str(self.balance))
def yield_interest(self):
self.balance = self.balance + (self.balance * self.int_rate)
return self
@classmethod
def print_acc_info(cls):
for account in cls.all_acc:
account.display_account_info()
account1 = BankAccount(0.05, 500)
account2 = BankAccount(0.025, 2000)
account1.deposit(30).deposit(120).deposit(10).withdraw(5).yield_interest().display_account_info()
account2.deposit(50).deposit(90).withdraw(52).withdraw(3).withdraw(45).withdraw(2).yield_interest().display_account_info()
BankAccount.print_acc_info()<file_sep>/flask/fundamentals/counter/counter.py
from flask import Flask, render_template, request, redirect,session
app = Flask(__name__)
app.secret_key = 'banana'
# set a secret key for security purposes
@app.route("/")
def counter():
if 'visits' in session:
session['visits'] = session.get('visits') + 1 # reading and updating session data
else:
session['visits'] = 1 # setting session data
return render_template("counter.html", visit = session['visits'])
@app.route("/destroy_session")
def clear_visit():
session.clear()
return redirect('/')
@app.route("/increase_visit")
def increa_visit():
session['visits'] = session['visits'] + 1
return render_template("counter.html", visit = session['visits'])
if __name__=="__main__": # Ensure this file is being run directly and not from a different module
app.run(debug=True) <file_sep>/flask_mysql/db_connection/dojos_ninjas/flask_app/models/ninja.py
from flask_app.config.mysqlconnection import connectToMySQL
# from flask import render_template, request, redirect
class Ninja:
def __init__( self , data ):
self.id = data['id']
self.first_name = data['first_name']
self.last_name = data['last_name']
self.age = data['age']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
@classmethod
def create(cls, data):
query = "INSERT INTO ninjas ( first_name , last_name , age, created_at , updated_at, dojo_id) VALUES (%(fname)s,%(lname)s,%(age)s, NOW(),NOW(),%(dojo_id)s);"
return connectToMySQL('dojos_ninjas').query_db(query,data)
<file_sep>/fundamentals/fundamentals/chaining_methods.py
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawl(self, amount):
self.account_balance -= amount
return self
def display_user_balance(self):
print("User: " + self.name + ", Balance: $" + str(self.account_balance))
def transfer_money(self, other_user, amount):
self.account_balance -= amount
other_user.account_balance += amount
return self
Jack = User("<NAME>", "<EMAIL>")
Wendy = User("<NAME>", "<EMAIL>")
Betty = User("<NAME>", "<EMAIL>")
Jack.make_deposit(200).make_deposit(100).make_deposit(50).make_withdrawl(120).transfer_money(Betty,30).display_user_balance()
Wendy.make_deposit(20).make_deposit(10).make_withdrawl(2).make_withdrawl(1).display_user_balance()
Betty.make_deposit(50).make_withdrawl(1).make_withdrawl(2).make_withdrawl(3).display_user_balance()<file_sep>/flask/fundamentals/adventure/server.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def poke_the_dragon():
return render_template("index.html")
@app.route("/dragon")
def run():
return render_template("index2.html")
@app.route("/dragon/run")
def horror():
return render_template("index3.html")
if __name__=="__main__": # Ensure this file is being run directly and not from a different module
app.run(debug=True) <file_sep>/fundamentals/fundamentals/dojo_ninja.py
import dojo_pets
class Ninja:
def __init__(self, first_name, last_name, treats, pet_food, pet):
self.first_name = first_name
self.last_name = last_name
self.treats = treats
self.pet_food = pet_food
self.pet = pet
def walk(self):
self.pet.play()
print(f"{self.first_name} is walking {self.pet.name}")
return self
def feed(self):
self.pet.eat(self.pet_food)
print(f"{self.first_name} is Feeding {self.pet.name} with {self.pet_food}")
return self
def bathe(self):
self.pet.noise()
print(f"{self.first_name} is bathing {self.pet.name} and it makes noise")
return self
Ninja1s_pet = Pet("Lucky", "dog", ["shake hands", "stand"])
Ninja1 = Ninja("Katelyn", "Ma", "icecream", "can foods", Ninja1s_pet)
Ninja1.feed().walk().bathe() <file_sep>/fundamentals/oop/ninjas_vs_pirates/classes/ninja.py
import random
class Character:
def __init__(self, name):
self.name = name
def show_stats( self ):
print(f"Name: {self.name}\nStrength: {self.strength}\nHealth: {self.health}\nEnergy: {self.energy}\n")
def attack(self, other_character):
self.energy_check()
energy_cost = 20
hit_chance = other_character.block()
if self.energy < energy_cost:
print(f'Not enough energy to perform this action.')
return self
if hit_chance == [1]:
return self
else:
self.energy -= energy_cost
damage_dealt = self.strength
other_character.health -= damage_dealt
print(f'{self.name} attacks {other_character.name} dealing {damage_dealt} damage. {other_character.name} loses {damage_dealt} health.')
if other_character.health <= self.strength:
print(f'---> {other_character.name} has been defeated!')
moves = [0, 1]
rng = random.choices(moves, weights=(50, 50))
if rng == [0]:
other_character.attack(other_character)
print(f'{other_character.name} attacks!')
elif rng == [1]:
if other_character == Pirate("<NAME>"):
other_character.drink_rum()
print(f'{other_character.name} drinks rum.')
elif other_character == Ninja("Michelangelo"):
other_character.meditate()
print(f'{other_character.name} meditates.')
return self
def energy_check(self):
if self.energy <= 30:
print(f"Warning! {self.name}'s energy is low!")
class Ninja(Character):
def __init__(self, name):
super().__init__(name)
self.health = 100
self.energy = 100
self.strength = 20
# self.type = "ninja"
def meditate(self):
self.energy += 20
self.health += 10
def block(self):
prob = [0, 1]
roll = random.choices(prob, weights=(30, 70))
if roll == [1]:
print(f'Attack dodged by {self.name}!')
return roll
class Pirate(Character):
def __init__(self , name):
super().__init__(name)
self.health = 150
self.energy = 75
self.strength = 25
# self.type = "pirate"
def drink_rum(self):
self.energy += 25
self.health -= 10
def block(self):
prob = [0, 1]
roll = random.choices(prob, weights=(40, 60))
if roll == [1]:
print(f'Attack blocked by {self.name}!')
return roll
<file_sep>/flask_mysql/validation/login and registration/flask_app/models/user.py
from flask_app.config.mysqlconnection import connectToMySQL
import re
from flask import flash
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
PW_REGEX = re.compile(r"^(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,}$")
class User:
def __init__( self , data ):
self.id = data['id']
self.first_name = data['first_name']
self.last_name = data['last_name']
self.email = data['email']
self.password = data['<PASSWORD>']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
@classmethod
def create(cls, data ):
query = "INSERT INTO users ( first_name , last_name , email , password, created_at, updated_at ) VALUES ( %(fname)s , %(lname)s , %(email)s ,%(password)s, NOW() , NOW() );"
return connectToMySQL('user_schema').query_db( query, data )
@classmethod
def getAll(cls):
query = "SELECT * FROM users"
result = connectToMySQL('user_schema').query_db(query)
users = []
for user in result:
users.append(cls(user))
return users
@classmethod
def get_by_email(cls,data):
query = "SELECT * FROM users WHERE email = %(email)s;"
results = connectToMySQL('user_schema').query_db(query,data)
if len(results) < 1:
return False
return cls(results[0])
@classmethod
def getOneByEmail(cls,email):
query = "SELECT * FROM users WHERE email = %(email)s"
data = {'email':email}
result = connectToMySQL('user_schema').query_db(query,data)
if not result:
return " "
return cls(result[0])
@staticmethod
def validate_user(user):
is_valid = True
if not EMAIL_REGEX.match(user['email']):
flash("Invalid email address!")
is_valid = False
if User.getOneByEmail(user["email"]):
flash('Email already in database')
is_valid = False
if len(user['fname']) < 2:
flash("First name must be at least 2 characters.")
is_valid = False
if len(user['lname']) < 2:
flash("Last name must be at least 2 characters.")
is_valid = False
if not PW_REGEX.match(user['password']):
flash("password should be at least 8 characters with one uppercase and one number no special characters!")
is_valid = False
if user['password'] != user["cp<PASSWORD>"]:
flash("Both passwords don't match")
is_valid = False
return is_valid
<file_sep>/flask_mysql/validation/login and registration/flask_app/controllers/users.py
from flask_app import app
from flask import render_template,redirect,request,session,flash
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt(app)
from flask_app.models.user import User
@app.route("/")
def index():
return render_template("form.html")
@app.route('/register', methods=['POST'])
def register():
if not User.validate_user(request.form):
return redirect('/')
pw_hash = bcrypt.generate_password_hash(request.form['password'])
print(pw_hash)
data = {
"fname": request.form['fname'],
"lname": request.form['lname'],
"email": request.form['email'],
"password" : <PASSWORD>
}
user_id = User.create(data)
session["user_id"] = user_id #store user id into session
return redirect('/success')
@app.route('/login', methods=['POST'])
def login():
data = { "email" : request.form["lemail"] }
user_in_db = User.get_by_email(data)
if not user_in_db:
flash("Invalid Email/Password")
return redirect("/")
if not bcrypt.check_password_hash(user_in_db.password, request.form['lpassword']):
flash("Invalid Email/Password")
return redirect("/")
session['user_id'] = user_in_db.id
return redirect("/success")
@app.route("/success")
def success():
return render_template("success.html")
@app.route("/logout")
def logout():
session.clear()
return redirect('/')<file_sep>/flask/fundamentals/adventure/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>home page</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='/css/style.css') }}">
</head>
<body>
<div class="flex1">
<p>
The King sat on his throne, legs swinging in the afternoon sun. The
wilderness spread out before him — a boy’s paradise of twisting dirt
tracks webbed with ancient tree roots, full of shady hollows and secret
hideaways. Behind him, the copse thinned until it met the road that
would take you back to the village, but before him was the arena of
countless battles, the base camp of every perilous expedition, a land of
untold adventure. And — for today at least — it was all his. “Halt!” he
shouted. “Who goes there?” The little girl looked up at the boy sat in
the tree. Long before either of them had been born a storm had done its
best to uproot it, but the tree was an obstinate one and it had refused
to give up its claw-like grip on the earth. Now it was a twisted and
gnarled thing, bent over like an old man. It was perfect for climbing
and the thickest branch dipped in just the right place to form a seat
directly above the path.
</p>
<p>What will you do?</p>
</div>
<div class="flex2">
<a href="/dragon">Poke the dragon</a>
<a href="/dragon/run">run away</a>
</div>
</body>
</html>
<file_sep>/flask/fundamentals/hello_flask/playground.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/play")
def start_play():
return render_template("playground.html")
@app.route("/play/<int:num>")
def multiple_box(num):
return render_template("playground.html", num = num)
@app.route("/play/<int:num>/<string:color>")
def add_color(num, color):
return render_template("playground.html", num = num, color = color)
if __name__=="__main__": # Ensure this file is being run directly and not from a different module
app.run(debug=True) <file_sep>/fundamentals/extras/store&products.py
class Store:
def __init__(self, name, list_of_products):
self.name = name
self.list_of_products = []
def add_product(self, new_product):
self.list_of_products.append(new_product)
return self
def sell_product(self, id):
self.list_of_products.pop(id)
def inflation(self, percent_increase):
for product in self.list_of_products:
product.update_price(percent_increase, True)
def set_clearance(self, category, percent_discount):
for product in self.list_of_products:
if product.category == category:
product.update_price(percent_change, False)
class Products:
def __init__(self, name, price, category):
self.name = name
self.price = price
self.category = category
def update_price(self, percent_change, is_increased):
if(is_increased):
self.price = self.price * (1 + percent_change)
else:
self.price = self.price * (1 - percent_change)
def print_info(self):
print(f"The name of the product is {self.name}.\nThe category is {self.category}. \nThe price is {self.price}")
cupcake_store = Store("NYCcupcake", ["cupcake, birthdaycake"])
cupcake = Products("cupcake", 5, "cake")
bdaycake = Products("birthdaycake",15, "cake")
cheesecake = Products("cheesecake", 25, "cake")
cupcake_store.add_product(cheesecake).add_product(bdaycake)
print(cupcake_store.list_of_products[1].name)<file_sep>/flask_mysql/crud/Users CRUD/server.py
from flask_app.controllers import users
from flask_app import app
if __name__ == "__main__":app.run(debug=True)
<file_sep>/flask_mysql/db_connection/dojos_ninjas/flask_app/models/dojo.py
from flask_app.config.mysqlconnection import connectToMySQL
from flask_app.models import ninja
class Dojo:
def __init__( self , data ):
self.id = data['id']
self.name = data['name']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
self.ninjas = []
@classmethod
def get_dojo_with_ninjas( cls , data ):
query = "SELECT * FROM dojos LEFT JOIN ninjas ON ninjas.dojo_id = dojos.id WHERE dojos.id = %(id)s;"
results = connectToMySQL('dojos_ninjas').query_db( query , data )
dojo = cls( results[0] )
for row_from_db in results:
ninja_data = {
"id" : row_from_db["ninjas.id"],
"first_name" : row_from_db["first_name"],
"last_name" : row_from_db["last_name"],
"age" : row_from_db["age"],
"created_at" : row_from_db["ninjas.created_at"],
"updated_at" : row_from_db["ninjas.updated_at"]
}
dojo.ninjas.append(ninja.Ninja( ninja_data ) )
return dojo
@classmethod
def get_all(cls):
query = "SELECT * FROM dojos"
results = connectToMySQL('dojos_ninjas').query_db( query)
return results
@classmethod
def create(cls, data ):
query = "INSERT INTO dojos (name ,created_at, updated_at ) VALUES ( %(dojoname)s , NOW() , NOW() );"
return connectToMySQL('dojos_ninjas').query_db( query, data )
<file_sep>/flask_mysql/db_connection/dojos_ninjas/flask_app/controllers/ninjas.py
from flask_app import app
from flask import render_template,redirect,request,session,Flask
from flask_app.models.ninja import Ninja
from flask_app.models.dojo import Dojo
@app.route("/add")
def root():
dojos = Dojo.get_all()
return render_template("New_Ninja.html", all_dojos = dojos)
@app.route("/create_ninja", methods=["POST"])
def create_ninja():
data = {
"fname" : request.form["fname"],
"lname" : request.form["lname"],
"age" : request.form["age"],
"dojo_id" : request.form["dojo_id"]
}
Ninja.create(data)
return redirect(f"/dojos/{request.form['dojo_id']}")
<file_sep>/flask/fundamentals/ninja_gold_flask/server.py
from flask import Flask, render_template, request, redirect, session
import random
from datetime import datetime
app = Flask(__name__)
app.secret_key = "something "
@app.route('/')
def index():
if "gold" not in session:
session["gold"] = int(0)
return render_template("index.html")
@app.route('/process_money', methods=["POST"])
def process():
if "message_list" not in session:
session["message_list"] = []
session['process'] = request.form['building']
if session['process'] == 'farm':
gold = random.randint(10, 20)
date = datetime.now()
dt_string = date.strftime("%H:%M:%S %p - %d/%m/%Y")
session['gold'] += gold
session['message_list'].append(
f"<ul><li class='green'>earned {gold} gold(s) from the farm on {dt_string} </li></ul>")
elif session['process'] == 'cave':
gold = random.randint(5, 10)
date = datetime.now()
dt_string = date.strftime("%H:%M:%S %p - %d/%m/%Y")
session['gold'] += gold
session['message_list'].append(
f"<ul><li class='green'>earned {gold} gold(s) from the cave on {dt_string} </li></ul>")
elif session['process'] == 'house':
gold = random.randint(2, 5)
date = datetime.now()
dt_string = date.strftime("%H:%M:%S %p - %d/%m/%Y")
session['gold'] += gold
session['message_list'].append(
f"<ul><li class='green'>earned {gold} gold(s) from the house on {dt_string} </li></ul>")
elif session['process'] == 'casino':
gold = random.randint(-50, 50)
date = datetime.now()
dt_string = date.strftime("%H:%M:%S %p - %d/%m/%Y")
if gold < 0:
session['gold'] += gold
session['message_list'].append(
f"<ul><li class='red'>lost {gold * (-1) } gold(s) from the casino on {dt_string} </li></ul>")
else:
session['gold'] += gold
session['message_list'].append(
f"<ul><li class='green'>earned {gold} gold(s) from the casino on {dt_string} </li></ul>")
return redirect('/')
@app.route("/reset", methods=['POST'])
def reset():
session.clear()
return redirect('/')
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/flask_mysql/db_connection/dojos_ninjas/flask_app/controllers/dojos.py
from flask_app import app
from flask import render_template,redirect,request,session
from flask_app.models.dojo import Dojo
@app.route("/")
def index():
dojos = Dojo.get_all()
return render_template("Dojos.html", all_dojos = dojos)
@app.route('/create_dojo', methods=["POST"])
def create_user():
data = {
"dojoname" : request.form["dojoname"],
}
Dojo.create(data)
return redirect('/')
@app.route("/dojos/<int:dojo_id>")
def dojo_ninjas(dojo_id):
data = {
"id":dojo_id
}
dojo = Dojo.get_dojo_with_ninjas(data)
return render_template("Dojo_show.html", dojo = dojo)<file_sep>/flask/fundamentals/hello_flask/understanding_routing.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "Hello World!"
@app.route("/dojo")
def dojo():
return "Dojo!"
@app.route("/say/<string:noun>")
def greet_person(noun):
return f"Hi {noun}!"
@app.route("/repeat/<string:ran_noun>/<int:num>")
def repeat(ran_noun, num):
return ran_noun * num
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return "Sorry! No response. Try again."
if __name__=="__main__": # Ensure this file is being run directly and not from a different module
app.run(debug=True) # Run the app in debug mode.<file_sep>/flask_mysql/crud/Users CRUD/flask_app/models/user.py
# import the function that will return an instance of a connection
from flask_app.config.mysqlconnection import connectToMySQL
from flask import Flask, render_template, request, redirect
# model the class after the friend table from our database
class User:
def __init__( self , data ):
self.id = data['id']
self.first_name = data['first_name']
self.last_name = data['last_name']
self.email = data['email']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
@classmethod
def get_all(cls):
query = "SELECT * FROM users;"
results = connectToMySQL('users').query_db(query)
users = []
for user in results:
users.append( cls(user) )
return users
@classmethod
def save(cls, data ):
query = "INSERT INTO users ( first_name , last_name , email , created_at, updated_at ) VALUES ( %(fname)s , %(lname)s , %(email)s , NOW() , NOW() );"
# data is a dictionary that will be passed into the save method from server.py
return connectToMySQL('users').query_db( query, data )
@classmethod
def delete_one(cls, id):
query = "DELETE FROM users WHERE id = %(id)s;"
data = {
"id": id
}
connectToMySQL('users').query_db(query,data)
@classmethod
def update_one(cls, id):
query = "UPDATE users SET first_name = %(new_fname)s, last_name = %(new_lname)s, email = %(new_email)s, updated_at = NOW() WHERE id = %(id)s;"
data = {
'id': id,
"new_fname" : request.form["new_fname"],
"new_lname" : request.form["new_lname"],
"new_email" : request.form["new_email"]
}
connectToMySQL("users").query_db(query,data)
@classmethod
def show_one(cls, id):
query = "SELECT * FROM users WHERE users.id = %(id)s;"
data = {
"id":id
}
results = connectToMySQL("users").query_db(query,data)
user = cls(results[0])
return user
<file_sep>/flask/fundamentals/great_num_game/great_num.py
import random
from flask import Flask, render_template, request, redirect,session
app = Flask(__name__)
app.secret_key = 'banana'
@app.route("/")
def page():
context = {
"random_num1" : random.randint(1, 100),
"random_num2" : random.randint(1, 100),
"random_num3" : random.randint(1, 100),
"random_num4" : random.randint(1, 100),
"random_num5" : random.randint(1, 100),
"random_num6" : random.randint(1, 100),
}
return render_template("index.html", **context)
@app.route("/clear_session")
def clear_visit():
session.clear()
return redirect('/')
@app.route("/guess", methods=['POST'])
def guess_random():
session['num'] = int(request.form["comp_select"])
return redirect("/show")
@app.route("/show")
def show_guess():
random_num = random.randint(1, 100)
if random_num == session['num']:
session['reply'] = 'You got it right, wanna play again?'
session['style'] = "green_style"
elif random_num > session['num']:
session['reply'] = 'Too low!'
session['style'] = "reg_style"
elif random_num < session['num']:
session['reply'] = 'Too high!'
session['style'] = "reg_style"
return redirect("/")
if __name__=="__main__": # Ensure this file is being run directly and not from a different module
app.run(debug=True)
<file_sep>/flask/fundamentals/dojo_survery/server.py
from flask import Flask, render_template, request, redirect,session
app = Flask(__name__)
app.secret_key = 'the secret is here'
@app.route("/")
def home():
return render_template("index.html")
@app.route("/process", methods=["POST"])
def process():
session['name'] = request.form['name']
session["loca_select"] = request.form["loca_select"]
session["lang_select"] = request.form["lang_select"]
session["comment"] = request.form["comment"]
session["checks"] = request.form["checks"]
session["options"] = request.form["options"]
return redirect("/result")
@app.route("/result")
def res():
return render_template("result.html", name = session['name'], loca = session["loca_select"],
lang = session["lang_select"], comment = session["comment"])
if __name__=="__main__": # Ensure this file is being run directly and not from a different module
app.run(debug=True)
<file_sep>/flask_mysql/crud/Users CRUD/flask_app/controllers/users.py
from flask_app import app
from flask import render_template,redirect,request,session,Flask
from flask_app.models.user import User
@app.route("/")
def index():
users = User.get_all()
return render_template("Read(All).html", all_users = users)
@app.route('/create_user', methods=["POST"])
def create_user():
data = {
"fname" : request.form["fname"],
"lname" : request.form["lname"],
"email" : request.form["email"]
"password" : request.form["password"]
}
User.save(data)
return redirect('/')
@app.route("/form")
def add_new():
return render_template("Create.html")
@app.route("/info/<int:user_id>")
def show_input(user_id):
user = User.show_one(user_id)
return render_template("Read(One).html", dis_user=user)
@app.route("/info/<int:user_id>/edit")
def show_user(user_id):
user = User.show_one(user_id)
return render_template("Edit.html", ed_user=user)
@app.route('/update/<int:user_id>', methods=["POST"])
def update_user(user_id):
User.update_one(user_id)
return redirect('/')
@app.route("/delete/<int:user_id>")
def delete_user(user_id):
User.delete_one(user_id)
return redirect('/')
if __name__ == "__main__":app.run(debug=True)<file_sep>/flask_mysql/validation/flash validation/flask_app/controllers/dojos.py
from flask_app import app
from flask import flash,render_template,redirect,request,session
from flask_app.models.dojo import Dojo
@app.route("/")
def home():
return render_template("index.html")
@app.route("/process", methods=["POST"])
def process():
session['name'] = request.form['name']
session["loca_select"] = request.form["loca_select"]
session["lang_select"] = request.form["lang_select"]
session["comment"] = request.form["comment"]
session["checks"] = request.form["checks"]
session["options"] = request.form["options"]
if not Dojo.validate_dojo(request.form):
return redirect("/")
return redirect("/result")
@app.route("/result")
def res():
return render_template("result.html", name = session['name'], loca = session["loca_select"],
lang = session["lang_select"], comment = session["comment"])
<file_sep>/flask_mysql/validation/flash validation/flask_app/models/dojo.py
from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
class Dojo:
def __init__( self , data ):
self.id = data['id']
self.name = data['name']
self.loca_select = data['loca_select']
self.language = data['lang_select']
self.comment = data['comment']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
@staticmethod
def validate_dojo(dojo):
is_valid = True # we assume this is true
if len(dojo['name']) < 3:
flash("Name must be at least 3 characters.")
is_valid = False
if dojo['loca_select'] == "none":
flash("Choose one location.")
is_valid = False
if dojo['lang_select'] == "none":
flash("Choose at least one language.")
is_valid = False
if len(dojo['comment']) < 3:
flash("Comment must be at least 3 characters.")
is_valid = False
return is_valid<file_sep>/fundamentals/oop/ninjas_vs_pirates/game.py
from classes.ninja import Character
from classes.ninja import Ninja
from classes.ninja import Pirate
michelangelo = Ninja("Michelanglo")
jack_sparrow = Pirate("<NAME>")
print("Welcome to Ninjas vs. Pirates!\n")
choose = input("Please choose a character: press <n> for Ninja press <p> for Pirate. press <q> to Quit\n")
is_running = True
while is_running == True:
if michelangelo.health <= 0 or jack_sparrow.health <= 0:
is_running = False
if choose == 'q':
is_running = False
elif choose == 'n':
first_move = input("Your move! press <a> to attack press <m> to meditate.\n")
elif choose =='p':
first_move = input("Your move! press <a> to attack press <r> to drink rum.\n")
if choose == "n" and first_move == "a":
michelangelo.attack(jack_sparrow)
jack_sparrow.show_stats()
michelangelo.show_stats()
elif choose == "n" and first_move == "m":
michelangelo.meditate()
jack_sparrow.show_stats()
michelangelo.show_stats()
elif choose == "p" and first_move == "a":
jack_sparrow.attack(michelangelo)
jack_sparrow.show_stats()
michelangelo.show_stats()
elif choose == "p" and first_move == "r":
jack_sparrow.drink_rum()
jack_sparrow.show_stats()
michelangelo.show_stats()
print("GAME OVER")
<file_sep>/fundamentals/fundamentals/functions_basic2.py
# Countdown - Create a function that accepts a number as an input.
# Return a new list that counts down by one, from the
# number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
# def countdown(num):
# res = []
# for x in range(num, -1, -1):
# res += [x]
# print(res)
# countdown(5)
# Print and Return - Create a function that will receive a list with two numbers.
# Print the first value and return the second.
# Example: print_and_return([1,2]) should print 1 and return 2
# def print_and_return(list):
# print(list[0])
# return list[1]
# print_and_return([1,2])
# First Plus Length - Create a function that accepts a list
# and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
# def first_plus_length(list):
# return list[0] + len(list)
# first_plus_length([1,2,3,4,5])
# Values Greater than Second - Write a function that accepts
# a list and creates a new list containing only the values from
# the original list that are greater than its 2nd value.
# Print how many values this is and then return the new list.
# If the list has less than 2 elements, have the function return False
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False
# def values_greater_than_second(list):
# if(len(list) < 2):
# return false
# res = []
# for x in list:
# if x > list[1]:
# res.append(x)
# print(len(res))
# return res
# print(values_greater_than_second([5,2,3,2,1,4]))
# This Length, That Value - Write a function that accepts two integers as parameters:
# size and value. The function should create and return a list whose length is equal to the given size,
# and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
# def length_and_value(int1,int2):
# res = []
# for x in range(0, int1):
# res.append(int2)
# print(res)
# length_and_value(4,7)
# length_and_value(6,2)<file_sep>/flask_mysql/validation/email validation/flask_app/models/email.py
from flask_app.config.mysqlconnection import connectToMySQL
from flask_app.models import email
from flask import flash,request
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class Email:
def __init__( self , data ):
self.id = data['id']
self.name = data['name']
self.created_at = data['created_at']
self.updated_at = data['updated_at']
@classmethod
def get_all(cls):
query = "SELECT * FROM emails"
results = connectToMySQL('email').query_db( query)
return results
@classmethod
def create(cls, data ):
query = "INSERT INTO emails (address ,created_at, updated_at ) VALUES ( %(address)s , NOW() , NOW() );"
return connectToMySQL('email').query_db( query, data )
@staticmethod
def validate_email(email):
is_valid = True
if not EMAIL_REGEX.match(email['address']):
flash("Invalid email address!",'error')
is_valid = False
return is_valid
@classmethod
def get_one(cls, address):
query = "SELECT * FROM emails WHERE emails.address = %(address)s;"
data = {
"address":request.form['address']
}
results = connectToMySQL("email").query_db(query,data)
return results<file_sep>/fundamentals/fundamentals/for_loop_basic1.py
for x in range(0, 151):
print(x);
for x in range(5, 1001, 5):
print(x);
for x in range(1, 101):
if(x % 5 == 0):
print("Coding")
elif(x % 10):
print("Coding Dojo")
sum = 0;
for x in range(0, 500001):
if(x % 2 == 1):
sum += x
print(sum)
for x in range(2018, 0, -4):
if(x > 0):
print(x)
lowNum = 2
highNum = 9
mult = 3
for x in range(lowNum, highNum + 1):
if(x % mult == 0):
print(x)<file_sep>/fundamentals/oop/ninjas_vs_pirates/classes/pirate.py
class Pirate(Character):
def __init__( self , name ):
super().__init__(self, name)
<file_sep>/flask/fundamentals/hello_flask/checkerb.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def display_8():
return render_template("checker.html", num = 8, num2 = 8)
@app.route("/4")
def display_4():
return render_template("checker.html", num = 8, num2 = 4, width = 12.5, height = 25)
@app.route("/<int:num>/<int:num2>")
def display_input(num, num2):
return render_template("checker.html",num = num, num2 = num2, width = 100/num, height = 100/num2)
if __name__=="__main__": # Ensure this file is being run directly and not from a different module
app.run(debug=True)
|
1e4340ca6d60c229b121b5511cff2571f7560cde
|
[
"Python",
"HTML"
] | 33 |
Python
|
Yma-Van2020/backend_work
|
333bcc23f8c7c06f5d8486a4e0ca63b3352fb3c3
|
74bd0c79d0972a274bbcda18c26cd701b6992561
|
refs/heads/master
|
<repo_name>bahmutov/test-semantic-deploy<file_sep>/src/local-action.js
module.exports = (pluginConfig, config, cb) => {
console.log('can do semantic-action')
cb()
}
<file_sep>/source/_posts/test-post.md
title: test post
date: 2017-07-25 23:00:08
tags:
category:
abstract: A test post
---
This is a test
<file_sep>/README.md
# test-semantic-deploy
[![Build status][ci-image] ][ci-url]
[](https://circleci.com/gh/bahmutov/test-semantic-deploy)
[](https://cla-assistant.io/bahmutov/test-semantic-deploy)
A small Hexo static blog site, deployed automatically if there are meaningful
commits since last deploys. Used to test
[semantic-action](https://github.com/bahmutov/semantic-action) tool.
See configuration in `release` object inside [package.json](package.json).
After deploy, check deployed build information:
```text
$ curl https://glebbahmutov.com/test-semantic-deploy/build.json
{
"id": "05f40c3ffdeb35b01adbf30d6753f3e52854e5e4",
"short": "05f40c3",
"savedAt": "2017-07-26T16:48:55.887Z",
"version": "1.0.0"
}
```
[ci-image]: https://travis-ci.org/bahmutov/test-semantic-deploy.svg?branch=master
[ci-url]: https://travis-ci.org/bahmutov/test-semantic-deploy
|
8618b71a82d12a2762c5862bfc18d36433d80869
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
bahmutov/test-semantic-deploy
|
60839bb21998cb30772c01b3a0f6efe17d1892aa
|
f17ca74c4d0725427246dbec2c35563d99c427d2
|
refs/heads/master
|
<repo_name>eristikos/Tic-Tac-Toe<file_sep>/tic-tac-toe oop.py
import pygame
pygame.init()
win = pygame.display.set_mode((600,600))
win.fill((0,0,0))
pygame.display.set_caption('Tic Tac Toe')
WHITE=(255,255,255)
run = True
draw_object = 'x'
cross = pygame.transform.smoothscale(pygame.image.load(r'C:\python_projects\my_projects\tic-tac-toe\cross.png').convert(), (180,180))
ooo = pygame.transform.smoothscale(pygame.image.load(r'C:\python_projects\my_projects\tic-tac-toe\ooo.png').convert(), (180,180))
def command1():
print("wygrales X \n"*50)
def command2():
print("wygrales O \n"*50)
class Field(object):
instancelist = []
circleFields = []
crossFields = []
def __init__(self, x, y, width, height, clicked):
self.x = x
self.y = y
self.width = width
self.height = height
self.clicked = clicked
Field.instancelist.append(self)
def drawrect(self):
pygame.draw.rect(win,WHITE,[self.x, self.y, self.width, self.height])
def test(self):
if pos[0] in range (self.x, self.width+self.x) and pos[1] in range (self.y, self.height+self.y) and self.clicked==False:
global draw_object
if draw_object == 'x':
win.blit(cross, (self.x, self.y))
Field.crossFields.append(Field.instancelist.index(self)+1)
print("pola Xowe: ", Field.crossFields)
draw_object = 'o'
elif draw_object =='o':
win.blit(ooo, (self.x, self.y))
Field.circleFields.append(Field.instancelist.index(self)+1)
print("pola kolkowe: ", Field.circleFields)
draw_object = 'x'
self.clicked=True
else:
pass
def test2(self):
if pos[0] in range (self.x, self.width+self.x) and pos[1] in range (self.y, self.height+self.y):
print("field",(Field.instancelist.index(self)+1))
field1 = Field(15,15,180,180, False,)
field2 = Field(210,15,180,180, False)
field3 = Field(405,15,180,180, False)
field4 = Field(15,210,180,180,False)
field5 = Field(210,210,180,180, False)
field6 = Field(405,210,180,180, False)
field7 = Field(15,405,180,180, False)
field8 = Field(210,405,180,180, False)
field9 = Field(405,405,180,180, False)
for instance in Field.instancelist:
instance.drawrect()
###############################################################################
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
print(pos[0], pos[1])
for instance in Field.instancelist:
instance.test()
instance.test2()
if 1 in Field.crossFields and 2 in Field.crossFields and 3 in Field.crossFields:
command1()
continue
elif 1 in Field.circleFields and 2 in Field.circleFields and 3 in Field.circleFields:
command2()
continue
elif 4 in Field.crossFields and 5 in Field.crossFields and 6 in Field.crossFields:
command1()
continue
elif 4 in Field.circleFields and 5 in Field.circleFields and 6 in Field.circleFields:
command2()
continue
elif 7 in Field.crossFields and 8 in Field.crossFields and 9 in Field.crossFields:
command1()
continue
elif 7 in Field.circleFields and 8 in Field.circleFields and 9 in Field.circleFields:
command2()
continue
elif 1 in Field.crossFields and 4 in Field.crossFields and 7 in Field.crossFields:
command1()
continue
elif 1 in Field.circleFields and 4 in Field.circleFields and 7 in Field.circleFields:
command2()
continue
elif 1 in Field.crossFields and 5 in Field.crossFields and 9 in Field.crossFields:
command1()
continue
elif 1 in Field.circleFields and 5 in Field.circleFields and 9 in Field.circleFields:
command2()
continue
elif 3 in Field.crossFields and 5 in Field.crossFields and 7 in Field.crossFields:
command1()
continue
elif 3 in Field.circleFields and 5 in Field.circleFields and 7 in Field.circleFields:
command2()
continue
elif 2 in Field.crossFields and 5 in Field.crossFields and 8 in Field.crossFields:
command1()
continue
elif 2 in Field.circleFields and 5 in Field.circleFields and 8 in Field.circleFields:
command2()
continue
elif 3 in Field.crossFields and 6 in Field.crossFields and 9 in Field.crossFields:
command1()
continue
elif 3 in Field.circleFields and 6 in Field.circleFields and 9 in Field.circleFields:
command2()
continue
else:
pass
pygame.display.update()
<file_sep>/tic-tac-toe.py
import pygame
pygame.init()
win = pygame.display.set_mode((600,600))
win.fill((0,0,0))
pygame.display.set_caption('Tic Tac Toe')
WHITE=(255,255,255)
cross = pygame.transform.smoothscale(pygame.image.load(r'C:\python_projects\my_projects\tic-tac-toe\cross.png').convert(), (180,180))
ooo = pygame.transform.smoothscale(pygame.image.load(r'C:\python_projects\my_projects\tic-tac-toe\ooo.png').convert(), (180,180))
class Field(object):
instancelist = []
def __init__(self, x, y, width, height, clicked):
self.x = x
self.y = y
self.width = width
self.height = height
self.clicked = clicked
Field.instancelist.append(self)
def drawrect(self):
pygame.draw.rect(win,WHITE,[self.x, self.y, self.width, self.height])
field1 = Field(15,15,180,180, False)
field2 = Field(210,15,180,180, False)
field3 = Field(405,15,180,180, False)
field4 = Field(15,210,180,180,False)
field5 = Field(210,210,180,180, False)
field6 = Field(405,210,180,180, False)
field7 = Field(15,405,180,180, False)
field8 = Field(210,405,180,180, False)
field9 = Field(405,405,180,180, False)
for instance in Field.instancelist:
instance.drawrect()
###############################################################################
run = True
draw_object = 'x'
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
print(pos[0], pos[1])
if pos[0] in range (field1.x, field1.width+field1.x) and pos[1] in range (field1.y, field1.height+field1.y) and field1.clicked==False:
print("field1")
if draw_object == 'x':
win.blit(cross, (field1.x, field1.y))
draw_object = 'o'
else:
win.blit(ooo, (field1.x, field1.y))
draw_object = 'x'
field1.clicked=True
elif pos[0] in range (field2.x, field2.width+field2.x) and pos[1] in range (field2.y, field2.height+field2.y) and field2.clicked==False:
print("field2")
if draw_object == 'x':
win.blit(cross, (field2.x, field2.y))
draw_object = 'o'
else:
win.blit(ooo, (field2.x, field2.y))
draw_object = 'x'
field2.clicked=True
elif pos[0] in range (field3.x, field3.width+field3.x) and pos[1] in range (field3.y, field3.height+field3.y) and field3.clicked==False:
print("field3")
if draw_object == 'x':
win.blit(cross, (field3.x, field3.y))
draw_object = 'o'
else:
win.blit(ooo, (field3.x, field3.y))
draw_object = 'x'
field3.clicked=True
elif pos[0] in range (field4.x, field4.width+field4.x) and pos[1] in range (field4.y, field4.height+field4.y) and field4.clicked==False:
print("field4")
if draw_object == 'x':
win.blit(cross, (field4.x, field4.y))
draw_object = 'o'
else:
win.blit(ooo, (field4.x, field4.y))
draw_object = 'x'
field4.clicked=True
elif pos[0] in range (field5.x, field5.width+field5.x) and pos[1] in range (field5.y, field5.height+field5.y) and field5.clicked == False:
print("field5")
if draw_object == 'x':
win.blit(cross, (field5.x, field5.y))
draw_object = 'o'
else:
win.blit(ooo, (field5.x, field5.y))
draw_object = 'x'
field5.clicked=True
elif pos[0] in range (field6.x, field6.width+field6.x) and pos[1] in range (field6.y, field6.height+field6.y) and field6.clicked == False:
print("field6")
if draw_object == 'x':
win.blit(cross, (field6.x, field6.y))
draw_object = 'o'
else:
win.blit(ooo, (field6.x, field6.y))
draw_object = 'x'
field6.clicked=True
elif pos[0] in range (field7.x, field7.width+field7.x) and pos[1] in range (field7.y, field7.height+field7.y) and field7.clicked == False:
print("field7")
if draw_object == 'x':
win.blit(cross, (field7.x, field7.y))
draw_object = 'o'
else:
win.blit(ooo, (field7.x, field7.y))
draw_object = 'x'
field7.clicked=True
elif pos[0] in range (field8.x, field8.width+field8.x) and pos[1] in range (field8.y, field8.height+field8.y) and field8.clicked == False:
print("field8")
if draw_object == 'x':
win.blit(cross, (field8.x, field8.y))
draw_object = 'o'
else:
win.blit(ooo, (field8.x, field8.y))
draw_object = 'x'
field8.clicked=True
elif pos[0] in range (field9.x, field9.width+field9.x) and pos[1] in range (field9.y, field9.height+field9.y) and field9.clicked == False:
print("field9")
if draw_object == 'x':
win.blit(cross, (field9.x, field9.y))
draw_object = 'o'
else:
win.blit(ooo, (field9.x, field9.y))
draw_object = 'x'
field9.clicked=True
else:
print("dzwig")
pygame.display.update()
|
62f733057e27b35f3bc936b95adf47ec71b25339
|
[
"Python"
] | 2 |
Python
|
eristikos/Tic-Tac-Toe
|
988b7d2244db99964d76e191528bf0c6d1b4b061
|
75aba682d5cffc0ce7dc646963a24aa08431117d
|
refs/heads/master
|
<file_sep>[run]
branch = True
source = backblast
omit = backblast/tests/*,backblast/openstack/*
[report]
ignore-errors = True<file_sep># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class TriggerEvent(object):
def __init__(self):
self.type = None
self.channel = None
self.exten = None
def __repr__(self):
ret = 'TriggerEvent %s %s to %s' % (self.type,
self.channel,
self.exten)
return ret
<file_sep>=========
Backblast
=========
An auto dialer for Asterisk written in Python.
* Free software: Apache license
* Documentation: https://backblast.readthedocs.org
Features
--------
* TODO
<file_sep>============
Installation
============
At the command line::
$ pip install backblast
Or, if you have virtualenvwrapper installed::
$ mkvirtualenv backblast
$ pip install backblast<file_sep># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import os
import Queue
import threading
class Scheduler(threading.Thread):
log = logging.getLogger('backblast.Scheduler')
def __init__(self):
self.log.debug('Preparing to initialize')
threading.Thread.__init__(self)
self.wake_event = threading.Event()
self.reconfigure_complete_event = threading.Event()
self.queue_lock = threading.Lock()
self._exit = False
self._pause = False
self._reconfigure = False
self._stopped = False
self.launcher = None
self.trigger_event_queue = Queue.Queue()
def stop(self):
self._stopped = True
self.wake_event.set()
def reconfigure(self, config):
self.log.debug('Prepare to reconfigure')
self.config = config
self._pause = True
self._reconfigure = True
self.wake_event.set()
self.log.debug('Waiting for reconfiguration')
self.reconfigure_complete_event.wait()
self.reconfigure_complete_event.clear()
self.log.debug('Reconfiguration complete')
def exit(self):
self.log.debug('Prepare to exit')
self._pause = True
self._exit = True
self.wake_event.set()
self.log.debug('Waiting for exit')
def run(self):
while True:
self.log.debug('Run handler sleeping')
self.wake_event.wait()
self.wake_event.clear()
if self._stopped:
return
self.log.debug('Run handler awake')
self.queue_lock.acquire()
try:
if not self._pause:
if not self.trigger_event_queue.empty():
self.process_event_queue()
if self._pause:
self._doPauseEvent()
if not self._pause:
if not self.trigger_event_queue.empty:
self.wake_event.set()
except Exception:
self.log.exception('Exception in run handler:')
self.queue_lock.release()
def process_event_queue(self):
self.log.debug('Fetching trigger event')
event = self.trigger_event_queue.get()
self.log.debug('Processing trigger event %s' % event)
self.addChange(event)
def resume(self):
self.log.debug('Resuming processing')
self.wake_event.set()
def _doPauseEvent(self):
if self._exit:
self.log.debug('Exiting')
os._exit(0)
if self._reconfigure:
self.log.debug('Performing reconfiguration')
self._pause = False
self._reconfigure = False
self.reconfigure_complete_event.set()
def setLauncher(self, launcher):
self.launcher = launcher
def addEvent(self, event):
if event.type is not None:
self.log.debug('Add trigger event: %s' % event)
self.queue_lock.acquire()
self.trigger_event_queue.put(event)
self.queue_lock.release()
self.wake_event.set()
def addChange(self, change):
self.launchJobs(change)
def launchJobs(self, change):
self.launcher.launch(change)
<file_sep># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import argparse
import ConfigParser
import daemon
import extras
pid_file_module = extras.try_imports(['daemon.pidlockfile', 'daemon.pidfile'])
import logging.config
import os
import signal
class Server(object):
log = logging.getLogger('backblast.Server')
def __init__(self):
self.args = None
self.config = None
def parse_arguments(self):
parser = argparse.ArgumentParser(description='Asterisk Dialer.')
parser.add_argument('-c', dest='config',
help='specify the config file')
parser.add_argument('-d', dest='nodaemon', action='store_true',
help='do not run as a daemon')
self.args = parser.parse_args()
def read_config(self):
self.config = ConfigParser.ConfigParser()
if self.args.config:
locations = [self.args.config]
else:
locations = ['/etc/backblast/backblast.conf']
for fp in locations:
if os.path.exists(os.path.expanduser(fp)):
self.config.read(os.path.expanduser(fp))
return
raise Exception('Unable to locate config file in %s' % locations)
def setup_logging(self):
if self.config.has_option('backblast', 'log_config'):
fp = os.path.expanduser(self.config.get('backblast', 'log_config'))
if not os.path.exists(fp):
raise Exception('Unable to read logging config file at %s' %
fp)
logging.config.fileConfig(fp)
else:
logging.basicConfig(level=logging.DEBUG)
def reconfigure_handler(self, signum, frame):
signal.signal(signal.SIGHUP, signal.SIG_IGN)
self.read_config()
self.setup_logging()
self.sched.reconfigure(self.config)
signal.signal(signal.SIGHUP, self.reconfigure_handler)
def exit_handler(self, signum, frame):
signal.signal(signal.SIGUSR1, signal.SIG_IGN)
self.sched.exit()
def main(self):
self.log.debug('Preparing to launch')
import backblast.scheduler
self.sched = backblast.scheduler.Scheduler()
self.sched.start()
self.sched.reconfigure(self.config)
self.sched.resume()
signal.signal(signal.SIGHUP, self.reconfigure_handler)
signal.signal(signal.SIGUSR1, self.exit_handler)
while True:
try:
signal.pause()
except KeyboardInterrupt:
print "Ctrl + C: asking scheduler to exit nicely...\n"
self.exit_handler(signal.SIGINT, None)
def main():
server = Server()
server.parse_arguments()
server.read_config()
pid_fn = '/var/run/backblast/backblast.pid'
pid = pid_file_module.TimeoutPIDLockFile(pid_fn, 10)
if server.args.nodaemon:
server.setup_logging()
server.main()
else:
with daemon.DaemonContext(pidfile=pid):
server.setup_logging()
server.main()
|
d8f62690838d388780450aace1ef221b72c91cf9
|
[
"Python",
"reStructuredText",
"INI"
] | 6 |
INI
|
kickstandproject/backblast
|
a3b251afeba5798cccfcd3766f1ea3e55f78034c
|
48c680be350ad37b44ecc83d5ae2cbb2549fa902
|
refs/heads/master
|
<repo_name>thuanpham98/thesis<file_sep>/esp_component/converttime.h
#ifndef __CONVERTTIME_H
#define __CONVERTTIME_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <stdint.h>
uint64_t date_to_timestamp(uint16_t s,uint16_t m,uint16_t h,uint16_t D,uint16_t M, uint16_t Y,uint16_t timezone);
#ifdef __cplusplus
}
#endif
#endif<file_sep>/esp_component/main.h
#ifndef __MAIN_H
#define __MAIN_H
#ifdef __cplusplus
extern "C" {
#endif
/* Basic library on C */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
/* library for Freetos API */
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
/* error library */
#include "esp_err.h"
typedef struct
{
char ID[13];
uint32_t device;
uint8_t user_wifi[33];
uint8_t pass_wifi[65];
uint16_t reg_digi;
uint16_t reg_dac;
uint16_t reg_pwm;
}esp_parameter_t;
#ifdef __cplusplus
}
#endif
#endif<file_sep>/esp_component/DIFU_I2C.h
#ifndef __DIFU_I2C_H
#define __DIFU_I2C_H
#include "driver/i2c.h"
#include "esp_err.h"
#define I2C_MASTER_FREQ_HZ_STANDARD_MODE 100000
#define I2C_MASTER_FREQ_HZ_FAST_MODE 400000
#define I2C_MASTER_TX_BUF_DISABLE 0
#define I2C_MASTER_RX_BUF_DISABLE 0
#define WRITE_BIT I2C_MASTER_WRITE
#define READ_BIT I2C_MASTER_READ
#define ACK_CHECK_EN I2C_MASTER_NACK
#define ACK_CHECK_DIS I2C_MASTER_ACK
#define ACK_VAL I2C_MASTER_ACK
#define NACK_VAL I2C_MASTER_NACK
#define I2C_MASTER_NUM_STANDARD_MODE I2C_NUM_0
#define I2C_MASTER_NUM_FAST_MODE I2C_NUM_1
#ifdef __cplusplus
extern "C" {
#endif
esp_err_t init_i2c(i2c_config_t *cf,i2c_port_t port);
esp_err_t master_write_i2c(i2c_port_t port,uint8_t *data_wr, size_t size, uint8_t address_slave);
esp_err_t master_read_i2c(i2c_port_t port,uint8_t *data_rd, size_t size, uint8_t address_slave);
#ifdef __cplusplus
}
#endif
#endif /* DIFU_I2C_h */
<file_sep>/esp_component/DIFU_NVS.h
#ifndef __DIFY_NVS_H
#define __DIFY_NVS_H
#ifdef __cplusplus
extern "C" {
#endif
/* library for Freetos API */
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
/* Library NVS memory */
#include "esp_partition.h"
#include "esp_err.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
static const char *TAG_NVS = "NVS";
void open_repository(char *repository,nvs_handle_t *nvs_handler);
void erase_all_nvs(void);
esp_err_t delete_key_value(nvs_handle_t *handle, const char *key);
esp_err_t write_nvs(char *repository,nvs_handle_t *nvs_handle, char *key , void *value,nvs_type_t type);
esp_err_t read_nvs(char *repository,nvs_handle_t *nvs_handle, char *key ,void *value ,nvs_type_t type);
#ifdef __cplusplus
}
#endif
#endif<file_sep>/esp_component/sync_rtc.h
#ifndef __SYNC_RTC_H
#define __SYNC_RTC_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "esp_sntp.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
void set_time_zone(void);
void sync_time(uint8_t type, uint8_t time_buffer[7]);
uint64_t get_timestamp(void);
void get_time_str(char time_display[64]);
#ifdef __cplusplus
}
#endif
#endif<file_sep>/README.md
# thesis
my thesis to graduate 2020 ( ver Englisking and Vietnamese)
|
34cc3d70a63a4c7aae7e582c72e931fa0f12a456
|
[
"Markdown",
"C"
] | 6 |
C
|
thuanpham98/thesis
|
785b89e2ec7ee641641889923de7ed32d9003dec
|
cf96e31a5692a7d2105477f01e9cf8508a07b005
|
refs/heads/master
|
<file_sep>//
// AppModel.swift
// Holandes
//
// Created by <NAME> on 11/04/21.
//
import Foundation
class AppEngine {
static let engine = AppEngine()
var allWords: [Word] = []
var categories: [String: [Word]] = [ : ]
var gameScores: [String: Int] = [:]
var selectedOption = ""
var selectedCategory = ""
var words: [Word] = []
var correctAnswers = 0
var totalWords = 0
var gameOver = false
var results = ""
func downloadWords() {
if let url = Bundle.main.url(forResource: "DB", withExtension: "json") {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
self.parseJSON(data: safeData)
}
}
task.resume()
}
}
func updateWords() {
if let url = URL(string: K.URLs.WordsURL) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
self.parseJSON(data: safeData)
}
}
task.resume()
}
}
func parseJSON(data: Data) {
let decoder = JSONDecoder()
do {
let decodedWords: [Word] = try decoder.decode([Word].self, from: data)
allWords = decodedWords
loadCategories()
}
catch {
print(error)
}
}
func loadCategories() {
categories.removeAll()
allWords.forEach { word in
let category = "\(word.category) (\(word.level))"
if(categories[category] == nil) {
categories[category] = []
}
categories[category]!.append(word)
}
updateCategories()
}
func updateCategories() {
let userDefaults = UserDefaults.standard
gameScores = [String : Int]()
if let savedCategories = userDefaults.dictionary(forKey: "Game Scores") {
categories.keys.forEach { category in
if(savedCategories[category] == nil) {
gameScores[category] = 0
}
else {
gameScores[category] = savedCategories[category] as? Int
}
}
}
else {
categories.keys.forEach { category in
gameScores[category] = 0
}
}
userDefaults.setValue(gameScores, forKey: "Game Scores")
}
func saveScore(category: String, score: Int) {
if let oldScore = gameScores[category] {
if(oldScore >= score) { return }
}
gameScores[category] = score
let userDefaults = UserDefaults.standard
userDefaults.setValue(gameScores, forKey: "Game Scores")
}
func getWords(withCategory category: String) -> [Word] {
if let selectedWords = categories[category] {
return selectedWords
}
return []
}
func getWords(withOption option: String) -> [Word] {
var selectedWords: [Word] = []
allWords.forEach() { word in
if word.type == option { selectedWords.append(word) }
}
return selectedWords.prefix(20).shuffled()
}
func loadNewGame(withCategory category: String) {
selectedCategory = category
if let selectedWords = categories[category] {
words = selectedWords
words.shuffle()
totalWords = words.count
print(totalWords)
}
correctAnswers = 0
gameOver = false
}
func getNextWord() -> Word? {
if(words.count == 0) {
gameOver = true
let score = Double(correctAnswers) / Double(totalWords) * 100
saveScore(category: selectedCategory, score: Int(score))
results = "Tuviste \(correctAnswers) de \(totalWords) respuestas correctas."
return nil
}
let nextWord = words.popLast()
return nextWord
}
func checkAnswer(forWord word: Word, answer: String) -> Bool{
let formattedBase = formatWord(word: word.spanishWord)
let formattedAnswer = formatWord(word: answer)
var result = (formattedBase == formattedAnswer)
if(!result) {
let variants = word.spanishVariants.split(separator: ",")
variants.forEach { variant in
let trimmed = variant.trimmingCharacters(in: .whitespacesAndNewlines)
if(trimmed == answer) {
result = true
}
}
}
if(result) {
correctAnswers += 1
}
return result
}
func formatWord(word: String) -> String {
var formattedWord = word.trimmingCharacters(in: .whitespacesAndNewlines)
formattedWord = formattedWord.folding(options: .diacriticInsensitive, locale:nil)
return formattedWord
}
}
<file_sep>//
// ResultsViewController.swift
// Holandes
//
// Created by <NAME> on 12/04/21.
//
import UIKit
class ResultsViewController: UIViewController {
var resultsText = ""
var gameViewController: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
resultsTextLabel.text = AppEngine.engine.results
}
@IBAction func exitButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func restart(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func finish(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBOutlet weak var resultsTextLabel: UILabel!
}
<file_sep>//
// HetDeViewController.swift
// Holandes
//
// Created by <NAME> on 11/04/21.
//
import UIKit
class HetDeViewController: UIViewController {
var words = [] as [Word]
var currentWord: Word?
var currentIndex = 0
var correctAnswers = 0
var restart = false
var gameOver = false
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.setNavigationBarHidden(false, animated: true)
hetAnswerButton.layer.borderColor = K.Colors.Orange!.cgColor
deAnswerButton.layer.borderColor = K.Colors.Orange!.cgColor
words = AppEngine.engine.getWords(withOption: "noun")
words.shuffle()
getNewWord()
}
func getNewWord() {
currentWord = words[currentIndex]
wordButton.setTitle(currentWord!.dutchWord, for: .normal)
nextButton.isHidden = true
hetAnswerButton.backgroundColor = UIColor.white
hetAnswerButton.setTitleColor(UIColor.label, for: .normal)
deAnswerButton.backgroundColor = UIColor.white
deAnswerButton.setTitleColor(UIColor.label, for: .normal)
}
func checkAnswer(answer: String) {
if(currentWord!.article == "het" && answer == "het") {
hetAnswerButton.backgroundColor = K.Colors.Green
hetAnswerButton.setTitleColor(UIColor.white, for: .normal)
correctAnswers += 1
}
else if (currentWord!.article == "de" && answer == "het") {
hetAnswerButton.backgroundColor = K.Colors.Red
hetAnswerButton.setTitleColor(UIColor.white, for: .normal)
}
else if (currentWord!.article == "de" && answer == "de") {
deAnswerButton.backgroundColor = K.Colors.Green
deAnswerButton.setTitleColor(UIColor.white, for: .normal)
correctAnswers += 1
}
else if (currentWord!.article == "het" && answer == "de") {
deAnswerButton.backgroundColor = K.Colors.Red
deAnswerButton.setTitleColor(UIColor.white, for: .normal)
}
nextButton.isHidden = false
}
@IBAction func sendAnswer(_ sender: Any) {
let answerButton = sender as! UIButton
checkAnswer(answer: answerButton.currentTitle!)
lockControls()
}
@IBAction func nextWord(_ sender: Any) {
if (currentIndex + 1) == words.count {
gameOver = true
performSegue(withIdentifier: K.Segues.ResultsSegue, sender: self)
}
else {
currentIndex += 1
getNewWord()
resetControls()
}
}
func lockControls () {
hetAnswerButton.isEnabled = false
deAnswerButton.isEnabled = false
}
func resetControls() {
hetAnswerButton.isEnabled = true
deAnswerButton.isEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
if gameOver {
self.navigationController?.popViewController(animated: false)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let resultsViewController = segue.destination as! ResultsViewController
resultsViewController.gameViewController = self
AppEngine.engine.results = "Tuviste \(correctAnswers) de \(words.count) respuestas correctas."
}
@IBOutlet weak var wordButton: UIButton!
@IBOutlet weak var hetAnswerButton: UIButton!
@IBOutlet weak var deAnswerButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
}
<file_sep>//
// CategoriesViewController.swift
// Holandes
//
// Created by <NAME> on 13/04/21.
//
import UIKit
class CategoriesViewController: UITableViewController {
var categories: [String: [Word]] = [:]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.setNavigationBarHidden(false, animated: true)
categories = AppEngine.engine.categories
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.ReusableCells.ReusableCell, for: indexPath)
let category = Array(categories.keys.sorted())[indexPath.row]
cell.textLabel?.text = category
if(AppEngine.engine.selectedOption == "Juego") {
if let score = AppEngine.engine.gameScores[category] {
cell.detailTextLabel?.text = "\(score)%"
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCategory = Array(categories.keys.sorted())[indexPath.row]
AppEngine.engine.loadNewGame(withCategory: selectedCategory)
if(AppEngine.engine.selectedOption == "Vocabulario") {
performSegue(withIdentifier: K.Segues.FlashcardsSegue, sender: self)
}
else if(AppEngine.engine.selectedOption == "Juego") {
performSegue(withIdentifier: K.Segues.GameSegue, sender: self)
}
}
override func viewWillAppear(_ animated: Bool) {
self.tableView.reloadData()
}
}
<file_sep>//
// Word.swift
// Holandes
//
// Created by <NAME> on 11/04/21.
//
import Foundation
struct Word: Decodable {
let category: String
let level: Int
let article: String
let type: String
let dutchWord: String
let spanishWord: String
let dutchVariants: String
let spanishVariants: String
}
<file_sep>//
// JuegoViewController.swift
// Holandes
//
// Created by <NAME> on 11/04/21.
//
import UIKit
class GameViewController: UIViewController {
var answerSent = false
var currentWord: Word?
var textLocked = false
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.setNavigationBarHidden(false, animated: true)
currentWord = AppEngine.engine.getNextWord()
wordButton.setTitle(currentWord?.dutchWord, for: .normal)
wordTextArea.becomeFirstResponder()
wordTextArea.delegate = self
}
@IBAction func sendAnswer(_ sender: Any) {
if(!answerSent) {
if(AppEngine.engine.checkAnswer(forWord: currentWord!, answer: wordTextArea.text ?? "")) {
rightAnswerImage.isHidden = false
}
else {
wrongAnswerImage.isHidden = false
}
rightAnswerLabel.text = currentWord!.spanishWord
sendAnswerButton.setTitle("Siguiente", for: .normal)
answerSent = true
lockControls()
}
else {
resetControls()
if let word = AppEngine.engine.getNextWord() {
currentWord = word
wordButton.setTitle(word.dutchWord, for: .normal)
}
else {
performSegue(withIdentifier: K.Segues.ResultsSegue, sender: self)
}
}
}
func lockControls() {
textLocked = true
}
func resetControls() {
rightAnswerImage.isHidden = true
wrongAnswerImage.isHidden = true
answerSent = false;
sendAnswerButton.setTitle("Enviar", for: .normal)
rightAnswerLabel.text = " "
textLocked = false
wordTextArea.text = ""
}
override func viewWillAppear(_ animated: Bool) {
if AppEngine.engine.gameOver {
self.navigationController?.popViewController(animated: false)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let resultsViewController = segue.destination as! ResultsViewController
resultsViewController.gameViewController = self
}
@IBOutlet weak var wordButton: UIButton!
@IBOutlet weak var wordTextArea: UITextField!
@IBOutlet weak var rightAnswerImage: UIImageView!
@IBOutlet weak var wrongAnswerImage: UIImageView!
@IBOutlet weak var rightAnswerLabel: UILabel!
@IBOutlet weak var sendAnswerButton: UIButton!
}
extension GameViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.trimmingCharacters(in: .whitespacesAndNewlines).count == 0 {
return true
}
if(textLocked) {
return false
}
if string.lowercased() == string {
textField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.lowercased())
} else {
textField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.lowercased())
}
return false
}
}
<file_sep>//
// ViewController.swift
// Holandes
//
// Created by <NAME> on 11/04/21.
//
import UIKit
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
AppEngine.engine.downloadWords()
AppEngine.engine.updateWords()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController!.setNavigationBarHidden(true, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let safeSender = sender {
let selectedButton = safeSender as! UIButton
AppEngine.engine.selectedOption = selectedButton.currentTitle ?? ""
}
}
}
<file_sep># Holandés (Swift)
Holandés (nombre temporal en lo se me ocurre algo mejor) es una app para iOS para que las personas que hablan español puedan aprender y practicar su holandés.
Este es mi primer proyecto en Swift, por lo que voy a ir aprendiendo y mejorándolo sobre la marcha.
## Versión 0.2
La app tiene tres secciones:
- Vocabulario, con tarjetas para memorizar y practicar las palabras.
- Juego, donde el usuario debe escribir el significado de la palabra.
- het / de, para identificar si el artículo de una palabra es 'het' o 'de'.
La versión actual toma las palabras de una URL con un JSON estático.
## TODO
### v1.0
- Realizar pruebas en dispositivos físicos.
- Publicar la aplicación en la App Store.
### v1.1
- Refactorizar el código para usar delegados.
- Agregar pantallas con instrucciones.
- Llevar registro de los errores del usuario.
- Mejorar el diseño gráfico de la aplicación.
- Agregar imágenes a las tarjetas.
- Agregar sonido a las palabras.
## Contribuir
Por el momento este es un proyecto personal. Apreciaría mucho cualquier comentario sobre cómo podría mejorarlo.
Acepto también ayuda en cuanto al diseño de la app. Por el momento no tiene icono y la interfaz es muy básica.
## Atribuciones
El vector de tulipán utilizado en la app es de Vecteezy.com.
La paleta de colores fue creada por <NAME> para flatuicolors.com.
<file_sep>//
// Constants.swift
// Holandes
//
// Created by <NAME> on 14/04/21.
//
import UIKit
import Foundation
struct K {
struct Colors {
static let Orange = UIColor(named: "RadiantYellow")
static let Green = UIColor(named: "AndroidGreen")
static let Red = UIColor(named: "BaraRed")
}
struct Segues {
static let ResultsSegue = "resultsSegue"
static let FlashcardsSegue = "flashcardsSegue"
static let GameSegue = "gameSegue"
}
struct ReusableCells {
static let ReusableCell = "ReusableCell"
}
struct URLs {
static let WordsURL = "http://sergio27.com/holandes/words.txt"
}
}
<file_sep>//
// VocabularioViewController.swift
// Holandes
//
// Created by <NAME> on 11/04/21.
//
import UIKit
class FlashcardsViewController: UIViewController {
var words = [] as [Word]
var category = ""
var currentWord: Word?
var cardFlipped = true
var currentIndex = -1
var correctAnswers = 0
var restart = false
var gameOver = false
var totalWords = 0
var round = 1
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.setNavigationBarHidden(false, animated: true)
correctButton.layer.borderColor = K.Colors.Orange!.cgColor
wrongButton.layer.borderColor = K.Colors.Orange!.cgColor
category = AppEngine.engine.selectedCategory
words = AppEngine.engine.getWords(withCategory: category)
words.shuffle()
totalWords = words.count
getNewWord()
}
@IBAction func cardTouched(_ sender: Any) {
flipCard()
}
func flipCard() {
if(cardFlipped) {
cardButton.setTitle(currentWord!.spanishWord, for: .normal)
cardFlipped = false;
correctButton.isHidden = false
wrongButton.isHidden = false
}
else {
cardFlipped = true;
getNewWord()
}
UIView.transition(with: cardButton, duration: 0.5, options: .transitionFlipFromRight, animations: nil, completion: nil)
}
@IBAction func correctWord(_ sender: Any) {
if round == 1 {
correctAnswers += 1
}
removeCurrentWord()
if words.count > 0 {
flipCard()
}
}
@IBAction func wrongWord(_ sender: Any) {
flipCard()
}
func getNewWord() {
if (currentIndex + 1) == words.count {
round += 1
words.shuffle()
currentIndex = -1
}
currentIndex += 1
correctButton.isHidden = true
wrongButton.isHidden = true
currentWord = words[currentIndex]
cardButton.setTitle(currentWord!.dutchWord, for: .normal)
}
func removeCurrentWord() {
words.remove(at: currentIndex)
currentIndex -= 1
if words.count == 0 {
gameOver = true
performSegue(withIdentifier: K.Segues.ResultsSegue, sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let resultsViewController = segue.destination as! ResultsViewController
AppEngine.engine.results = "Tuviste \(correctAnswers) de \(totalWords) respuestas correctas."
resultsViewController.gameViewController = self
}
override func viewWillAppear(_ animated: Bool) {
if gameOver {
self.navigationController?.popViewController(animated: false)
}
}
@IBOutlet weak var cardButton: UIButton!
@IBOutlet weak var correctButton: UIButton!
@IBOutlet weak var wrongButton: UIButton!
}
|
b1981694280eec55aef80c60a770a23ae898b20f
|
[
"Swift",
"Markdown"
] | 10 |
Swift
|
sergio27/Holandes-Swift
|
c7518fbf92738682103634f90bd02ff708272de6
|
47ebdbd005343e9019260c60a0f6d512f2633aa2
|
refs/heads/main
|
<file_sep>#include "GamePlay.h"
#include <locale>
int main()
{
setlocale(LC_ALL, "Rus");
GamePlay Obj;
Obj.Game();
system("pause");
return 0;
}<file_sep>#include "GamePlay.h"
#include <iostream>
int GamePlay::choise(std::string message)
{
int value;
bool isInvalid = true;
while (isInvalid)
{
std::cout << message;
std::cin >> value;
isInvalid = std::cin.fail() || value < 0 || value > 3 || std::cin.peek() != L'\n';
if (isInvalid)
{
if (std::cin.fail())
std::cin.clear();
std::cout << "Значение недопустимо, попробуйте еще раз:" << std::endl;
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
system("cls");
return value;
}
void GamePlay::Game()
{
int process;
std::cout << Game::_introduction;
process = choise(Game::_firstChoice);
switch (process)
{
case 1:
{
std::cout << Game::_firstChoiceAncwer1;
object.SetParty(true);
break;
}
case 2:
{
std::cout << Game::_firstChoiceAncwer2;
object.SetMax(true);
}
case 3:
{
std::cout << Game::_firstChoiceAncwer3;
object.SetMax(true);
}
default:
break;
}
std::cout << Game::_secondBlock;
if (!object.GetMax())
{
process = choise(Game::_secondChoice);
switch (process)
{
case 2:
{
object.SetArea(true);
break;
}
default:
std::cout << Game::_secondChoiceSleep;
break;
};
}
else {
process = choise(Game::_secondChoiceWithMax);
switch (process)
{
case 1:
{
std::cout << Game::_secondChoiceArea;
object.SetArea(true);
break;
}
case 2:
std::cout << Game::_secondChoiceSleep;
object.SetParty(true);
break;
default:
std::cout << Game::_secondChoiceSleep;
break;
};
}
std::cout << Game::_thirdBlock;
if (object.GetMax())
if (object.GetArea())
{
std::cout << Game::_thirdBlockWithMaxAndKnowArea;
}
else {
std::cout << Game::_thirdBlockWithMax;
}
else{
if (object.GetArea())
{
std::cout << Game::_thirdBlockWithArea;
}
else {
std::cout << Game::_thirdBlockWithoutArea;
}
}
std::cout << Game::_thirdBlockEnd;
if (!object.GetArea())
{
process = choise(Game::_thirdChoice);
switch (process)
{
case 1:
{
object.SetPasserby(true);
break;
}
case 2:
{
std::cout << Game::_coffe;
process = choise(Game::_fourChoiceCoffe);
switch (process)
{
case 1:
std::cout << Game::_answerCoffe + Game::_answerCoffeInfoPVZ +
Game::_answerCoffeGoodBye;
object.SetCoffe(true);
object.SetPvz(true);
object.SetArea(true);
object.SetPasserby(true);
break;
case 2:
std::cout << Game::_answerCoffe + Game::_answerCoffeCharge +
Game::_answerCoffeGoodBye;
object.SetArea(true);
object.SetCoffe(true);
std::cout << Game::_replicCharge;
object.SetPvz(true);
object.SetPasserby(true);
break;
case 3:
std::cout << Game::_answerCoffeNegative;
object.SetPasserby(true);
break;
}
break;
}
case 3:
{
object.SetPasserby(true);
break;
}
default:
break;
};
}
else {
process = choise(Game::_thirdChoiceWithArea);
switch (process)
{
case 1:
{
object.SetPvz(true);
object.SetPasserby(true);
break;
}
case 2:
{
std::cout << Game::_coffe;
process = choise(Game::_CoffechoiceWithArea);
switch (process)
{
case 1:
std::cout << Game::_answerCoffe + Game::_answerCoffeGoodBye;
object.SetCoffe(true);
object.SetPvz(true);
object.SetPasserby(true);
break;
case 2:
std::cout << Game::_answerCoffeGoodBye;
object.SetPvz(true);
object.SetPasserby(true);
break;
case 3:
std::cout << Game::_answerCoffeNegative;
object.SetPvz(true);
object.SetPasserby(true);
break;
}
break;
}
case 3:
{
object.SetPvz(true);
object.SetPasserby(true);
break;
}
default:
break;
};
}
if (!object.GetPVZ())
{
process = choise(Game::_mainChoice);
switch (process)
{
default:
std::cout << Game::_replicPasserby;
break;
}
}
else {
process = choise(Game::_mainChoiceArea);
switch (process)
{
case 1:
std::cout << Game::_replicPasserby2 + Game::_passerbyMoney;
break;
case 2:
std::cout << Game::_replicPasserby2;
break;
default:
std::cout << Game::_refuse;
break;
}
}
std::cout << Game::_end;
process = choise(Game::_endChoice);
switch (process)
{
case 1:
object.SetLive(false);
break;
case 2:
object.SetLive(false);
break;
case 3:
break;
}
process = choise(Game::_finalChoice);
switch (process)
{
case 1:
object.SetLive(false);
break;
case 2:
object.SetLive(true);
break;
case 3:
object.SetLive(false);
break;
}
if (object.GetLive())
{
std::cout << Game::_survaved;
if (object.GetMax())
if (object.GetArea())
if (object.GetParty())
std::cout << Game::_survavedMaks;
else
std::cout << Game::_notSurvavedMaks;
else std::cout << Game::_notSurvavedMaksArea;
else
if (object.GetPVZ())
std::cout << Game::_parselYes;
else
std::cout << Game::_parselNo;
}
else
{
std::cout << Game::_doom;
if (object.GetMax())
if (object.GetArea())
if (object.GetParty())
std::cout << Game::_survavedMaks2;
else
std::cout << Game::_notSurvavedMaks2;
else std::cout << Game::_notSurvavedMaksArea;
else
std::cout << Game::_maybe;
}
}<file_sep>#pragma once
#include <iostream>
class Game {
private:
bool _withParty = false;//это флаги, от которых зависит сюжет игры,
bool _withMaxim = false;// они проставляются в зависимости от того, что выбрал пользователь
bool _isKnowTheArea = false;
bool _withCoffe = false;
bool _withPVZ = false;
bool _isALive = true;
public:
void SetLive(bool flag); //поскольку они прайват, из другого класса мы сможем их изменить
void SetParty(bool flag);//только с помощью функций "сеттеров"
void SetPvz(bool flag);
void SetMax(bool flag);
void SetArea(bool flag);
void SetCoffe(bool flag);
void SetPasserby(bool flag);
bool GetLive();//поскольку они прайват, из другого класса - узнать их значение мы сможем
bool GetParty();//только с помощью "геттеров"
bool GetMax();
bool GetPVZ();
bool GetArea();
bool GetCoffe();
static const std::string _introduction; //в этих строках хранится весь текст игры
static const std::string _firstChoice;//я постаралась назвать их близко по смыслу, но возможно
static const std::string _firstChoiceAncwer1;// что это вышло так себе.
static const std::string _firstChoiceAncwer2;//Они статические, потому что мы знаем их на этапе написания
static const std::string _firstChoiceAncwer3;//константные, потому что они не должны изменяться.
static const std::string _secondBlock;
static const std::string _secondChoiceWithMax;
static const std::string _secondChoice;
static const std::string _secondChoiceSleep;
static const std::string _secondChoiceArea;
static const std::string _thirdBlock;
static const std::string _thirdBlockWithMaxAndKnowArea;
static const std::string _thirdBlockWithMax;
static const std::string _thirdBlockWithArea;
static const std::string _thirdBlockWithoutArea;
static const std::string _thirdBlockEnd;
static const std::string _thirdChoiceWithArea;
static const std::string _thirdChoice;
static const std::string _coffe;
static const std::string _fourChoiceCoffe;
static const std::string _CoffechoiceWithArea;
static const std::string _answerCoffe;
static const std::string _answerCoffeNegative;
static const std::string _answerCoffeCharge;
static const std::string _answerCoffeInfoPVZ;
static const std::string _answerCoffeGoodBye;
static const std::string _replicCharge;
static const std::string _mainChoice;
static const std::string _mainChoiceArea;
static const std::string _passerby;
static const std::string _pvz;
static const std::string _end;
static const std::string _endChoice;
static const std::string _finalChoice;
static const std::string _replicPasserby;
static const std::string _replicPasserby2;
static const std::string _passerbyMoney;
static const std::string _refuse;
static const std::string _survaved;
static const std::string _survavedMaks;
static const std::string _notSurvavedMaks;
static const std::string _notSurvavedMaksArea;
static const std::string _parselYes;
static const std::string _parselNo;
static const std::string _doom;
static const std::string _survavedMaks2;
static const std::string _notSurvavedMaks2;
static const std::string _maybe;
};<file_sep>#pragma once
#include "Game.h"
#include <string>
class GamePlay
{
private:
Game object;
static int choise(std::string message);
public:
void Game();
};<file_sep>#include "Game.h"
bool Game::GetArea()
{
return _isKnowTheArea;
}
bool Game::GetPVZ()
{
return _withPVZ;
}
bool Game::GetLive()
{
return _isALive;
}
bool Game::GetCoffe()
{
return _withCoffe;
}
bool Game::GetParty()
{
return _withParty;
}
bool Game::GetMax()
{
return _withMaxim;
}
void Game::SetArea(bool area)
{
_isKnowTheArea = area;
}
void Game::SetCoffe(bool coffe)
{
_withCoffe = coffe;
}
void Game::SetLive(bool flag)
{
_isALive = flag;
}
void Game::SetMax(bool Max)
{
_withMaxim = Max;
}
void Game::SetParty(bool party)
{
_withParty = party;
}
void Game::SetPvz(bool flag)
{
std::cout << Game::_pvz;
_withPVZ = flag;
}
void Game::SetPasserby(bool passerby)
{
std::cout << Game::_passerby;
}
const std::string Game::_introduction ="День начался как обычно. Дел запланировано не было. Выходной, приятная погода\n"
"и уют собственной комнаты сделали утро таким безмятежным, каким оно бывает лишь в детстве\n"
"или в редкие моменты юности.Родители уже три дня как уехали на месяц в отпуск, \n"
"так что можно будет позвать друзей на вечер.За завтраком, который начался в два часа дня,\n"
"началась ленивая проверка новостей в смартфоне.\n";
const std::string Game::_firstChoice = "1. Написать в общий чат своей компании, чтобы они приходили к 18:00.\n"
"2. Проверить, когда придет посылка из интернет магазина.\n"
"3. Написать только лучшему другу Максиму.\n";
const std::string Game::_firstChoiceAncwer1 = "Сегодня никто не сможет,"
"у всех свои планы, но предлагают перенести на завтра в 17:00.\n"
"Что же сказано сделано.Веселиться будем завтра.\n"
"Остается только смотреть любимые сериалы.Приходит оповещение,\n"
"что посылка доставлена и забрать можно уже сегодня.\n"
"удачнее дня для этого путешествия сложно придумать.\n";
const std::string Game::_firstChoiceAncwer2 ="Можно забирать, но ехать придется в другой конец города.\n"
"Благо, что удачнее дня для этого путешествия сложно придумать.\n"
"Нужно позвать с собой Максима!Он в деле, выдвигаемся.\n";
const std::string Game::_firstChoiceAncwer3 = "Максим свободен, но он хочет погулять, такая теплая погода может и не \n"
"повториться в этом году, скоро зима.Приходит оповещение,\n"
"что посылка доставлена и забрать можно уже сегодня.Идеально!\n"
"Сходим вместе за ней, все равно пункт выдачи на другом конце города.\n"
"Максим в деле, выдвигаемся.\n";
const std::string Game::_secondBlock = "К 16:00 уже на остановке, народа на ней нет вообще. Странновато,\n"
"хотя какая разница. Нужный автобус - тот, что с номером 66. Ходит редко, \n"
"если честно, вообще не припоминаю, чтобы видел его хоть раз.Ого!Всего 16:06, а он уже подъехал.\n"
"Дорога займет примерно час сорок, ехать до конечной.\n";
const std::string Game::_secondChoiceWithMax = "1. Общаться с другом.\n2. Включить аудиокнигу в наушниках.\n"
"3. Залипнуть в телефон.Позвать друзей в гости на завтра.\n";
const std::string Game::_secondChoice = "1. Включить аудиокнигу в наушниках.\n"
"2. Посмотреть район, в котором находится пункт выдачи, чтобы если что не ошибиться.\n"
"3. Залипнуть в телефон.\n";
const std::string Game::_secondChoiceSleep = "Вы уснули и проснулись только когда доехали до конечной.\n";
const std::string Game::_secondChoiceArea = "Вы замечаете, что зарядка cадится, изучаете район куда направляетесь, чтобы не потеряться.\n";
const std::string Game::_thirdBlock = "На телефоне кончилась зарядка и он вырубился - мелочь, а не приятно.\n"
"Остановка и сам район выглядят отталкивающе: обшарпанные многоэтажки еще сталинской постройки, \n"
"расбросанный мусор и опять таки отсутствие людей!\n"
"Вроде из автобуса выходила парочка плохо одетых, но и их уже не видно.\n";
const std::string Game::_thirdBlockWithMaxAndKnowArea = "Максим сказал, что обстановка неприятная и нужно побыстрее тут заканчивать,\n"
"а погуляем уже в центре.Идти недалеко - это радует.Хорошо, что Максим тут, вдвоем все равно весело.\n";
const std::string Game::_thirdBlockWithMax ="Максим сказал, что нужно найти кого-нибудь и спросить где пункт выдачи.\n"
"Но я примерно помню, как идти до него от остановки.Как же странно, вечер еще не глубокий,\n"
"а тут пустыня какая - то. Хорошо, что Максим тут, вдвоем все равно весело.\n";
const std::string Game::_thirdBlockWithArea = "Идти недалеко - это радует. Но одному, в таком месте, без телефона все равно очень неуютно.\n";
const std::string Game::_thirdBlockWithoutArea = "Хочется поддаться панике: дождаться автобуса в обратную сторону и рвануть домой.\n"
"Но с подступившей тревогой удается быстро справиться. \n"
"В конце концов, уже не маленький ребенок, примерное положение пункта выдачи в голове есть,\n"
"дня удобнее этого не будет.Просто забрать посылку и можно возвращаться.\n";
const std::string Game::_thirdBlockEnd = "Быстро стемнело, а вслед за солнцем ушло и тепло, на улице стало еще противнее. Теплый кофе сделал бы эту поездку ощутимо лучше.\n";
const std::string Game::_thirdChoiceWithArea = "1. Быстро пойти к пункту выдачи.\n"
"2. Поискать где можно купить кофе на вынос и пойти к пункту выдачи.\n"
"3. Пойти к пункту выдачи, но поразглядывать район, вряд ли вы сюда еще поедете.\n";
const std::string Game::_thirdChoice = "1. Пойти, опираясь чисто на воспоминания.\n"
"2. Поискать кофейню и там уточнить о пункте выдачи.\n"
"3. Пойти, опираясь на воспоминания, но если встретится прохожий, то уточнить дорогу.\n";
const std::string Game::_coffe = "Кофе пробралось даже в самые отдаленные части галактики! \n"
"Это первая мысль, которая появилась в голове, когда неоновая вывеска кофейни\n"
"сверкнула с повильончика перед поворотом.Девушка бариста выглядела скучающей и даже\n"
"удивилась, когда звоночек над дверью сигнализировал о прибытии посетителей.\n"
"\t- Добрый день, что желаете ? \n";
const std::string Game::_fourChoiceCoffe = "1. Латте на обычном молоке и узнать, где находится пункт выдачи магазина ***.\n"
"2. Латте на обычном молоке, а у вас можно поставить телефон на зарядку?\n"
"3.Выбор у вас так себе, конечно, ничего не нужно. Скажите лучше: как дойти до пункта выдачи магазина ***?\n";
const std::string Game::_CoffechoiceWithArea = "1. Латте на обычном молоке и узнать почему у вас тут так пусто.\n"
"2.Просто латте.\n"
"3. Выбор у вас так себе, конечно, ничего не нужно.Скажите лучше : почему на улице никого нет ?\n";
const std::string Game::_answerCoffe = "\t\t-Тут сейчас считай комендантский час, в районе орудует маньяк. \n"
"Ближе к вечеру люди стараются не выходить, так что и вам не советую гулять до поздна.\n"
"Ох, надеюсь его скоро поймают.\n";;
const std::string Game::_answerCoffeNegative = "\t\t-Понятия не имею, раз ничего не нужно то покиньте наше заведение!\n";
const std::string Game::_answerCoffeCharge = "\t\t-Да, поставьте.\n";;
const std::string Game::_answerCoffeInfoPVZ = "\t\t - Пункт выдачи через три дома, на первом этаже жилого дома."
"Там вывеска весит, идите прямо и не ошибетесь.\n";;
const std::string Game::_answerCoffeGoodBye = "\t\t-Вот ваше кофе, досвидания.\n";;
const std::string Game::_replicCharge ="С заряженным телефоном дойти не проблема, но нужно торопиться: \n"
"и пункт выдачи скоро закроется, и проводить вечер в компании маньяка не охото.\n";
const std::string Game::_mainChoice = "1. Cогласиться помочь и заодно узнать дорогу\n"
"2. Не согласиться помогать, но попробовать узнать дорогу\n"
"3. Cогласиться помочь и заодно узнать дорогу, и попросить денег\n";
const std::string Game::_mainChoiceArea = "1. Cогласиться помочь, попросить за это денег\n"
"2. Cогласиться помочь\n"
"3. Не согласиться\n";
const std::string Game::_passerby = "Минутах в 10 от остановки, ближе к жилым домам на лавочке сидит мужчина.\n"
"У него большая спортивная сумка, выглядит тяжелой и не вяжется с костюмом, в который он одет.\n"
"Он явно обрадовался увидев людей:\n"
"\t- Здравствуйте, пожалуйста, не могли бы вы мне помочь ?\n"
"\t-Здравствуйте, а что нужно ?\n"
"\t-Мне нужно дотащить эту сумку до дома, а я как назло подвернул ногу и никого вокруг. \n"
"Тут совсем рядом и я в долгу не останусь!\n";
const std::string Game::_pvz = "Вывеска магазина * **!Его было не так уж и сложно найти.Посылка в руках, можно возвращаться.\n";
const std::string Game::_end = "Что это? Начало нового дня?Тогда почему в комнате так темно? Нет, это определенно не дом.\n"
"\t\t-Ничего не помню. \n"
"Голова раскалываается. Видно деревянную дверь и больше ничего. Что делать?\n";
const std::string Game::_endChoice = "1.Кричать и звать кого-нибудь на помощь\n"
"2. Попытаться выйти самому, дверь выглядит хлюпкой.\n"
"3. Ждать\n";
const std::string Game::_finalChoice = "Дверь открылась, за ней источник яркого света из-за которого ничего не видно.\n"
"1.Резко побежать\n"
"2. Дать глазам привыкнуть к свету и побежать\n"
"3. Ждать\n";
const std::string Game::_replicPasserby = "\t\t-Пункт магазина ***?Так он как раз у моего дома, там метров 30 разницы.\n"
"\t\tБери сумку и иди за мной. У меня кошелек дома, как раз и вознагражу сразу.\n";
const std::string Game::_replicPasserby2 = "\t\tБери сумку и иди за мной.\n";
const std::string Game::_passerbyMoney = "У меня кошелек дома, как раз и вознагражу сразу.\n";
const std::string Game::_refuse= "Странный он какой-то, пусть подождет кого-нибудь еще. Пора к остановке, уже поздно.\n"
" *********\n";
const std::string Game::_survaved = "Вы выжили, буквально чудом.";
const std::string Game::_survavedMaks = " Максим тоже, его спасла вечеринка, на которой заметили, что вы\n"
"потерялись и вызвали полицию. Его найдут через 3 дня, после тебя, но все еще\n"
"живого. Маньяк до него не добрался.\n";
const std::string Game::_notSurvavedMaks = "Максима спасти не удалось, когда ты добрался до людей, ты сразу\n"
"потерял сознание, а когда очнулся,\n"
"вспомнить дорогу до места откуда сбежал - уже не смог. Полиция опаздала всего на сутки.\n";
const std::string Game::_notSurvavedMaksArea = "Стоило лучше изучить местность, это могло тебе помочь. Максим не выжил. \n";
const std::string Game::_parselYes = "Кстати, твою посылку нашли в логове маньяка.\n"
"да уж, стоило так рисковать ради коврика для мышки?\n";
const std::string Game::_parselNo = "Кстати, посылку, к сожалению, уже отправили назад в интернет магазин. \n"
"Придется заказать опять.\n";
const std::string Game::_doom = "К сожалению, вы погибли. Маньяк над вами долго издевался.";
const std::string Game::_survavedMaks2 =" А вот Максим спасся, его спасла вечеринка, на которой заметили,\n"
" что вы потерялись и вызвали полицию. Его нашли полностью измученного,\n"
"но все еще живого. Маньяк до него не добрался.\n";
const std::string Game::_notSurvavedMaks2 = "Максима спасти не удалось. Полиция опаздала всего на сутки.\n";
const std::string Game::_maybe = "Может быть, если бы вы не отправились в это путешествие один, \n"
"вас бы спасли?\n";
|
9a50be434b33adcdd014c7007c3b7efabb9df7c2
|
[
"C++"
] | 5 |
C++
|
dejze/laba1
|
9b53cd84c566e536e4ec1b76eafa7945b6b8a852
|
6ecf4090e48ccc8a1bfbbe485b1c5e5166c754c7
|
refs/heads/master
|
<repo_name>alagappan-qa/shop-poly<file_sep>/specs/indexPage.js
let autoReloadJson = require ('auto-reload-json');
const getShadowDomHtml = (shadowRoot) => {
let shadowHTML = '';
for (let el of shadowRoot.childNodes) {
shadowHTML += el.nodeValue || el.outerHTML;
}
return shadowHTML;
};
// Recursively replaces shadow DOMs with their HTML.
const replaceShadowDomsWithHtml = (rootElement) =>
{
for (let el of rootElement.querySelectorAll('*')) {
if (el.shadowRoot) {
replaceShadowDomsWithHtml(shadowRoot);
el.innerHTML += getShadowDomHtml(el.shadowRoot);
}
}
};
const EC = protractor.ExpectedConditions;
let dataJSONPageInfo = browser.params.dataConfigJSONPageStaticInfo;
let dataJSONPageInfoRead = autoReloadJson(dataJSONPageInfo);
//let PO_automationPractice = new browser.params.automationPractice_PO();
beforeEach(async () => {
await browser.waitForAngularEnabled(false);
});
describe('Testing Automation Practice site', () => {
it('Login Page', async () =>{
let homePage=await element(by.tagName('shop-app'));
let ecWaitForLoginPageToLoad = EC.and (EC.visibilityOf(homePage));
await browser.get(dataJSONPageInfoRead.indexPage.pageURL);
await browser.wait(ecWaitForLoginPageToLoad, 20000, 'Timeout: PageLoadError');
expect(await browser.getTitle()).toEqual(dataJSONPageInfoRead.indexPage.pageTitle);
});
it('After Login', async () =>{
//Working Code:
let elm1=await element(by.tagName('shop-app'));
let elm2 = await elm1.element(by.css_sr("::sr iron-pages"));
let elm3 = await elm2.element(by.tagName("shop-home"));
let elm4 = await elm3.all(by.css_sr("::sr div")).get(0);
let elm5 = await elm4.element(by.tagName('shop-button'));
await elm5.click();
/*
// Non-Working Code by siply specifying Root Element with the deep leaf element.
let elm1=await element(by.tagName('shop-app'));
let elm2 = await elm1.element(by.css_sr("::sr iron-pages"));
let elm5 = await elm2.element(by.tagName('shop-button'));
await elm5.click();
*/
/*
//When using replaceShadowDomsWithHtml function it's not working
await replaceShadowDomsWithHtml(element(by.tagName('shop-app')));
await console.log(element.all(by.tagName('shop-button')));
*/
browser.driver.sleep(30000);
},60000);
});<file_sep>/specs/indexPage_rename.js
let autoReloadJson = require ('auto-reload-json');
var querySelectorAllDeep = function querySelectorAllDeep(selector, root = document) {
return _querySelectorDeep(selector, true, root);
}
var querySelectorDeep = function querySelectorDeep(selector, root = document) {
return _querySelectorDeep(selector, false, root);
}
var getObject = function getObject(selector, root = document) {
// split on > for multilevel selector
const multiLevelSelectors = splitByCharacterUnlessQuoted(selector, '>');
if (multiLevelSelectors.length == 1) {
return querySelectorDeep(multiLevelSelectors[0], root);
} else if (multiLevelSelectors.length == 2) {
return querySelectorDeep(multiLevelSelectors[1], querySelectorDeep(multiLevelSelectors[0]).root);
} else if (multiLevelSelectors.length == 3) {
return querySelectorDeep(multiLevelSelectors[2], querySelectorDeep(multiLevelSelectors[1], querySelectorDeep(multiLevelSelectors[0]).root));
}
//can add more level if we need to
}
var getAllObject = function getAllObject(selector, root = document) {
// split on > for multilevel selector
const multiLevelSelectors = splitByCharacterUnlessQuoted(selector, '>');
if (multiLevelSelectors.length == 1) {
return querySelectorAllDeep(multiLevelSelectors[0], root);
} else if (multiLevelSelectors.length == 2) {
return querySelectorAllDeep(multiLevelSelectors[1], querySelectorDeep(multiLevelSelectors[0]).root);
} else if (multiLevelSelectors.length == 3) {
return querySelectorAllDeep(multiLevelSelectors[2], querySelectorDeep(multiLevelSelectors[1], querySelectorDeep(multiLevelSelectors[0]).root));
}
//can add more level if we need to
}
function _querySelectorDeep(selector, findMany, root) {
let lightElement = root.querySelector(selector);
if (document.head.createShadowRoot || document.head.attachShadow) {
// no need to do any special if selector matches something specific in light-dom
if (!findMany && lightElement) {
return lightElement;
}
// split on commas because those are a logical divide in the operation
const selectionsToMake = splitByCharacterUnlessQuoted(selector, ',');
return selectionsToMake.reduce((acc, minimalSelector) => {
// if not finding many just reduce the first match
if (!findMany && acc) {
return acc;
}
// do best to support complex selectors and split the query
const splitSelector = splitByCharacterUnlessQuoted(minimalSelector
//remove white space at start of selector
.replace(/^\s+/g, '')
.replace(/\s*([>+~]+)\s*/g, '$1'), ' ')
// filter out entry white selectors
.filter((entry) => !!entry);
const possibleElementsIndex = splitSelector.length - 1;
const possibleElements = collectAllElementsDeep(splitSelector[possibleElementsIndex], root);
const findElements = findMatchingElement(splitSelector, possibleElementsIndex, root);
if (findMany) {
acc = acc.concat(possibleElements.filter(findElements));
return acc;
} else {
acc = possibleElements.find(findElements);
return acc;
}
}, findMany ? [] : null);
} else {
if (!findMany) {
return lightElement;
} else {
return root.querySelectorAll(selector);
}
}
}
function findMatchingElement(splitSelector, possibleElementsIndex, root) {
return (element) => {
let position = possibleElementsIndex;
let parent = element;
let foundElement = false;
while (parent) {
const foundMatch = parent.matches(splitSelector[position]);
if (foundMatch && position === 0) {
foundElement = true;
break;
}
if (foundMatch) {
position--;
}
parent = findParentOrHost(parent, root);
}
return foundElement;
};
}
function splitByCharacterUnlessQuoted(selector, character) {
return selector.match(/\\?.|^$/g).reduce((p, c) => {
if (c === '"' && !p.sQuote) {
p.quote ^= 1;
p.a[p.a.length - 1] += c;
} else if (c === '\'' && !p.quote) {
p.sQuote ^= 1;
p.a[p.a.length - 1] += c;
} else if (!p.quote && !p.sQuote && c === character) {
p.a.push('');
} else {
p.a[p.a.length - 1] += c;
}
return p;
}, { a: [''] }).a;
}
function findParentOrHost(element, root) {
const parentNode = element.parentNode;
return (parentNode && parentNode.host && parentNode.nodeType === 11) ? parentNode.host : parentNode === root ? null : parentNode;
}
function collectAllElementsDeep(selector = null, root) {
const allElements = [];
const findAllElements = function(nodes) {
for (let i = 0, el; el = nodes[i]; ++i) {
allElements.push(el);
// If the element has a shadow root, dig deeper.
if (el.shadowRoot) {
findAllElements(el.shadowRoot.querySelectorAll('*'));
}
}
};
findAllElements(root.querySelectorAll('*'));
return selector ? allElements.filter(el => el.matches(selector)) : allElements;
}
const getShadowDomHtml = (shadowRoot) => {
let shadowHTML = '';
for (let el of shadowRoot.childNodes) {
shadowHTML += el.nodeValue || el.outerHTML;
}
return shadowHTML;
};
// Recursively replaces shadow DOMs with their HTML.
const replaceShadowDomsWithHtml = (rootElement) =>
{
for (let el of rootElement.querySelectorAll('*')) {
if (el.shadowRoot) {
replaceShadowDomsWithHtml(shadowRoot);
el.innerHTML += getShadowDomHtml(el.shadowRoot);
}
}
};
const EC = protractor.ExpectedConditions;
let dataJSONPageInfo = browser.params.dataConfigJSONPageStaticInfo;
let dataJSONPageInfoRead = autoReloadJson(dataJSONPageInfo);
//let PO_automationPractice = new browser.params.automationPractice_PO();
beforeEach(async () => {
await browser.waitForAngularEnabled(false);
});
describe('Testing Automation Practice site', () => {
it('Login Page', async () =>{
let homePage=await element(by.tagName('shop-app'));
let ecWaitForLoginPageToLoad = EC.and (EC.visibilityOf(homePage));
await browser.get(dataJSONPageInfoRead.indexPage.pageURL);
await browser.wait(ecWaitForLoginPageToLoad, 20000, 'Timeout: PageLoadError');
expect(await browser.getTitle()).toEqual(dataJSONPageInfoRead.indexPage.pageTitle);
});
it('After Login', async () =>{
/*
//Working Code:
let elm1=await element(by.tagName('shop-app'));
let elm2 = await elm1.element(by.css_sr("::sr iron-pages"));
let elm3 = await elm2.element(by.tagName("shop-home"));
let elm4 = await elm3.all(by.css_sr("::sr div")).get(0);
let elm5 = await elm4.element(by.tagName('shop-button'));
await elm5.click();
*/
/*
// Non-Working Code by siply specifying Root Element with the deep leaf element.
let elm1=await element(by.tagName('shop-app'));
let elm2 = await elm1.element(by.css_sr("::sr iron-pages"));
let elm5 = await elm2.element(by.tagName('shop-button'));
await elm5.click();
*/
/*
//When using replaceShadowDomsWithHtml function it's not working
await replaceShadowDomsWithHtml(element(by.tagName('shop-app')));
await console.log(element.all(by.tagName('shop-button')));
*/
// While trying to use a different function
querySelectorAllDeep(element.all(by.tagName('shop-button')).get(2),document.body);
browser.driver.sleep(30000);
},60000);
});
|
a3a5ef5b04cfec0fedd0b5aa11a5a3289d3c0627
|
[
"JavaScript"
] | 2 |
JavaScript
|
alagappan-qa/shop-poly
|
9772af582f84a5ab6c49f3a2cfd1c84f4227e4b3
|
37fa97fec06755a7c94daba6e79886395517885d
|
refs/heads/master
|
<repo_name>mapkyca/KnownIRC<file_sep>/IRC/IRC.php
<?php
namespace IdnoPlugins\IRC {
class IRC {
private $socket;
protected function send($string) {
if (!$this->socket) {
throw new \Exception("Not connected to IRC Server");
}
error_log("IRC > $string");
$written = fwrite($this->socket, $string."\r\n");
if ($written===false)
throw new \Exception("There was a problem writing '$string' to IRC");
// Give server a chance
sleep(3);
return $written;
}
/**
* Read a line from the IRC server, stripping the :server.domain.com portion
*/
protected function readline() {
if (!$this->socket) {
throw new \Exception("Not connected to IRC Server");
}
$string = fgets($this->socket);
error_log("IRC < $string");
//$result = explode(' ', $string, 2);
//return trim($result[1]);
return $string;
}
function privmesg($target, $message) {
return $this->send("PRIVMSG $target :$message");
}
function connect($server, $port = 6697) {
$prefix = '';
if ($port == 6697)
$prefix = 'tls://';
error_log("IRC > Connecting to {$prefix}$server:$port");
$this->socket = fsockopen($prefix.$server, $port, $errno, $errstr);
if (!$this->socket) {
throw new \Exception("IRC Socket - $errstr");
}
}
/**
* Do a PING/PONG
* @param string $string If null, this method will read from the socket until it gets a PING message.
*/
function pingpong($string = null) {
if (!$string) {
do {
$string = $this->readline();
} while (strpos($string, 'PING')!==0);
}
$components = explode(':', $string, 2);
return $this->send("PONG :{$components[1]}");
}
function join($channel) {
$this->send("JOIN $channel");
}
function setUsername($username, $password = false) {
$this->send("USER $username $username bla :$username");
$this->send("NICK $username");
if ($password)
$this->send("PRIVMSG NickServ :IDENTIFY $username $password");
}
function disconnect() {
$this->send('QUIT');
$return = fclose($this->socket);
$this->socket = null;
return $return;
}
}
}<file_sep>/README.md
IRC Support for Known
=====================
This plugin provides the ability to syndicate short messages, and share posts and images to IRC channels
Installation
------------
* Drop the IRC folder into the IdnoPlugins folder of your Known installation.
* Log into Known and navigate to Site configuration > Plugins.
* Enable the IRC plugin on the Plugins page.
Usage:
------
Once activated, go to your user settings -> IRC page, where you'll have the ability to add
channels on various servers/networks.
Configure your channel and you'll be able to post short messages straight into the channel.
Limitations:
------------
* Only one username per network, so if you sit on IRC, use a different nickname.
* Apache PHP mod generally has threads disabled, therefor this plugin doesn't have a daemon/bot. This means that it'll join -> post -> leave your channel. Try to avoid spamming :)
See
---
* Author: <NAME> <http://www.marcus-povey.co.uk>
<file_sep>/IRC/Pages/Account.php
<?php
/**
* IRC pages
*/
namespace IdnoPlugins\IRC\Pages {
/**
* Default class to serve IRC-related account settings
*/
class Account extends \Idno\Common\Page
{
function getContent()
{
$this->gatekeeper(); // Logged-in users only
$t = \Idno\Core\site()->template();
$body = $t->draw('account/irc');
$t->__(['title' => 'IRC', 'body' => $body])->drawPage();
}
function postContent() {
$this->gatekeeper(); // Logged-in users only
if (($id = $this->getInput('remove'))) {
$user = \Idno\Core\site()->session()->currentUser();
if (array_key_exists($id, $user->irc)) {
unset($user->irc[$id]);
} else {
$user->irc = [];
}
$user->save();
\Idno\Core\site()->session()->addMessage('Your IRC settings have been removed from your account.');
} else {
$server = trim($this->getInput('server'));
$channel = trim($this->getInput('channel'));
$username = trim($this->getInput('username'));
$password = trim($this->getInput('<PASSWORD>'));
$port = 6697;
// Extract port
$channelport = explode(':', $channel);
$channel = $channelport[0];
if (isset($channelport[1]))
$port = $channelport[1];
$id = sha1($server.$port.$channel.$username);
$user = \Idno\Core\site()->session()->currentUser();
if (!isset($user->irc) || !is_array($user->irc)) {
$user->irc = [];
}
$user->irc[$id] = [
'id' => $id,
'server' => $server,
'channel' => $channel,
'username' => $username,
'password' => <PASSWORD>,
'port' => $port
];
$user->save();
}
$this->forward('/account/irc/');
}
}
}<file_sep>/IRC/templates/default/irc/forms/remove.tpl.php
<?php
$account = $vars['account'];
?>
<form
action="<?= \Idno\Core\site()->config()->getDisplayURL() ?>account/irc/"
class="form-horizontal" method="post">
<p>
<input type="hidden" name="remove"
value="<?= $account['id'] ?>"/>
<button type="submit"
class="connect lkin connected"><i class="fa fa-irc"></i>
<?= $account['username'] ?> in <?= $account['server'] ?><?= $account['channel'] ?>
(Disconnect)
</button>
<?= \Idno\Core\site()->actions()->signForm('/account/irc/') ?>
</p>
</form><file_sep>/IRC/Main.php
<?php
namespace IdnoPlugins\IRC {
class Main extends \Idno\Common\Plugin {
function send(array $userdetails, $message) {
$irc = new IRC();
$irc->connect($userdetails['server'], $userdetails['port']);
$irc->setUsername($userdetails['username'], $userdetails['password'] ? $userdetails['password'] : false);
//$irc->pingpong();
$irc->join($userdetails['channel']);
$written = $irc->privmesg($userdetails['channel'], $message);
$irc->disconnect();
return $written;
}
function registerPages() {
// Register settings page
\Idno\Core\site()->addPageHandler('account/irc', '\IdnoPlugins\IRC\Pages\Account');
/** Template extensions */
// Add menu items to account & administration screens
\Idno\Core\site()->template()->extendTemplate('account/menu/items', 'account/irc/menu');
}
function registerEventHooks() {
// Register syndication services
\Idno\Core\site()->syndication()->registerService('irc', function () {
return $this->hasIRC();
}, ['note', 'article', 'image']);
if ($this->hasIRC()) {
if (is_array(\Idno\Core\site()->session()->currentUser()->irc)) {
foreach (\Idno\Core\site()->session()->currentUser()->irc as $id => $details) {
if ($details['channel'] && $details['username'] && $details['server'] && $details['port'])
\Idno\Core\site()->syndication()->registerServiceAccount('irc', $id, $details['channel']);
}
}
}
// Push "notes" to IRC
\Idno\Core\site()->addEventHook('post/note/irc', function (\Idno\Core\Event $event) {
$eventdata = $event->data();
$object = $eventdata['object'];
if ($this->hasIRC()) {
if (!empty(\Idno\Core\site()->session()->currentUser()->irc[$eventdata['syndication_account']])) {
$message = strip_tags($object->getDescription());
if (!empty($message) && substr($message, 0, 1) != '@') {
try {
$userdetails = \Idno\Core\site()->session()->currentUser()->irc[$eventdata['syndication_account']];
$written = $this->send($userdetails, $message);
if (!$written)
throw new \Exception('No data written to IRC channel ' . $userdetails['channel']);
$link='#';
if (strpos($userdetails['server'], '.freenode.')!==false) {
// We deduce we're on freenode, so use their webchat interface
$link = "https://webchat.freenode.net/?channels=" . trim($userdetails['channel'], ' #');
}
$object->setPosseLink('irc', $link, $userdetails['channel']);
$object->save();
} catch (\Exception $e) {
\Idno\Core\site()->session()->addErrorMessage('There was a problem posting to IRC: ' . $e->getMessage());
}
}
}
}
});
// Push "articles" to IRC
\Idno\Core\site()->addEventHook('post/article/irc', function (\Idno\Core\Event $event) {
$eventdata = $event->data();
$object = $eventdata['object'];
if ($this->hasIRC()) {
if (!empty(\Idno\Core\site()->session()->currentUser()->irc[$eventdata['syndication_account']])) {
$message = htmlentities(strip_tags($object->getTitle())) . ': ' .htmlentities($object->getUrl());
try {
$userdetails = \Idno\Core\site()->session()->currentUser()->irc[$eventdata['syndication_account']];
$written = $this->send($userdetails, $message);
if (!$written)
throw new \Exception('No data written to IRC channel ' . $userdetails['channel']);
$link='#';
if (strpos($userdetails['server'], '.freenode.')!==false) {
// We deduce we're on freenode, so use their webchat interface
$link = "https://webchat.freenode.net/?channels=" . trim($userdetails['channel'], ' #');
}
$object->setPosseLink('irc', $link, $userdetails['channel']);
$object->save();
} catch (\Exception $e) {
\Idno\Core\site()->session()->addErrorMessage('There was a problem posting to IRC: ' . $e->getMessage());
}
}
}
});
// Push "images" to IRC
\Idno\Core\site()->addEventHook('post/image/irc', function (\Idno\Core\Event $event) {
$eventdata = $event->data();
$object = $eventdata['object'];
if ($attachments = $object->getAttachments()) {
foreach ($attachments as $attachment) {
if ($this->hasIRC()) {
if (!empty(\Idno\Core\site()->session()->currentUser()->irc[$eventdata['syndication_account']])) {
$message = htmlentities(strip_tags($object->getTitle())) . ': ' .htmlentities($object->getUrl());
try {
$userdetails = \Idno\Core\site()->session()->currentUser()->irc[$eventdata['syndication_account']];
$written = $this->send($userdetails, $message);
if (!$written)
throw new \Exception('No data written to IRC channel ' . $userdetails['channel']);
$link='#';
if (strpos($userdetails['server'], '.freenode.')!==false) {
// We deduce we're on freenode, so use their webchat interface
$link = "https://webchat.freenode.net/?channels=" . trim($userdetails['channel'], ' #');
}
$object->setPosseLink('irc', $link, $userdetails['channel']);
$object->save();
} catch (\Exception $e) {
\Idno\Core\site()->session()->addErrorMessage('There was a problem posting to IRC: ' . $e->getMessage());
}
}
}
}
}
});
}
/**
* Can the current user use IRC?
* @return bool
*/
function hasIRC() {
if (!(\Idno\Core\site()->session()->currentUser())) {
return false;
}
if (\Idno\Core\site()->session()->currentUser()->irc) {
return true;
}
return false;
}
}
}
<file_sep>/IRC/templates/default/account/irc.tpl.php
<div class="row">
<div class="col-md-10 col-md-offset-1">
<?= $this->draw('account/menu') ?>
<h1>IRC</h1>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<?php
if (empty(\Idno\Core\site()->session()->currentUser()->irc)) {
?>
<div class="control-group">
<div class="controls-config">
<div class="row">
<div class="col-md-7">
<p>
Easily share updates to IRC.</p>
<p>
With IRC connected, you can cross-post updates, pictures, and posts that you
publish publicly on your site.
</p>
</div>
</div>
</div>
</div>
<?php
} else if (!\Idno\Core\site()->config()->multipleSyndicationAccounts()) {
?>
<div class="control-group">
<div class="controls-config">
<div class="row">
<div class="col-md-7">
<p>
Your account is currently connected to IRC. Public updates, pictures, and posts
that you publish here
can be cross-posted to IRC.
</p>
<div class="social">
<?php
if ($accounts = \Idno\Core\site()->session()->currentUser()->irc) {
foreach ($accounts as $account) {
echo $this->__(['account' => $account])->draw('irc/forms/remove');
}
}
?>
</div>
</div>
</div>
</div>
</div>
<?php
} else {
?>
<div class="control-group">
<div class="controls-config">
<div class="row">
<div class="col-md-7">
<p>
Your account is currently connected to IRC. Public updates, pictures, and posts
that you publish here
can be cross-posted to IRC.
</p>
<div class="social">
<?php
if ($accounts = \Idno\Core\site()->session()->currentUser()->irc) {
foreach ($accounts as $account) {
echo $this->__(['account' => $account])->draw('irc/forms/remove');
}
}
?>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
<div class="control-group">
<div class="controls-config">
<div class="row">
<div class="col-md-7">
<div class="social">
<h2>Add a new channel:</h2>
<p>
<form
action="<?= \Idno\Core\site()->config()->getDisplayURL() ?>account/irc/"
class="form-horizontal" method="post">
<input type="text" name="server" placeholder="Network & port, e.g. irc.freenode.net:6697" required />
<input type="text" name="channel" placeholder="Channel, e.g. #knownchat" required />
<input type="text" name="username" placeholder="Username to use" required />
<input type="password" name="password" placeholder="nick<PASSWORD> (optional)" />
<input type="submit" value="Add channel..." class="btn btn-default" />
<?= \Idno\Core\site()->actions()->signForm('/account/irc/') ?>
</form>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
|
87769807a3c2d4ebe7c6d8fe71492ea435b5d924
|
[
"Markdown",
"PHP"
] | 6 |
PHP
|
mapkyca/KnownIRC
|
e908e3e43d43cb8967869a88788d143bbced41e2
|
86b3da704dca6e24f515f4f4a022b870dad2b809
|
refs/heads/master
|
<repo_name>ErlinaCahyani/tes<file_sep>/app.php
<?php
class app{
function cek($n){
$count=0;
$string1="Marlin";
$string2="Booking";
if($n>0){
for ($i=1; $i <=$n ; $i++) {
if($i%3==0 && $i%5==0){
if($count<5){
echo "<b>".$string1." ".$string2."</b></br>";
$count++;
}else{
break;
}
}elseif($i%3==0){
if($count<2){
echo $i." - ".$string1."</br>";
}else{
echo $i." - ".$string2."</br>";
}
}elseif($i%5==0){
if($count<2){
echo $i." - ".$string2."</br>";
}else{
echo $i." - ".$string1."</br>";
}
}
}
}else{
echo "Masukan Salah. <a href='tes1.php'>Kembali</a>";
}
}
}
if($_SERVER['REQUEST_METHOD']=='POST'){
$app = new app;
$app->cek($_POST['n']);
}
?><file_sep>/README.md
<NAME>,
Nama saya <NAME>, saya mahasiswa Komsi SV UGM. Saya berharap Bapak/Ibu dapat menerima saya bergabung dalam tim.
Sebelumnya saya minta maaf karena saya sangat jarang menggunakan bahasa PHP, saya lebih suka menggunakan Java. sehingga saya tidak familiar dengan bahasa PHP. Berikut ini adalah hasil pekerjaan saya dalam tes yang diadakan Marlin Booking pada 31 Agustus 2018.
saya akan sangat berterimakasih jika Bapak/Ibu mau menerima saya sebagai bagian dari tim Bapak/Ibu.
Terima Kasih<file_sep>/tes1.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="app.php" method="post">
<input type="type" name="n">
<button type="submit">enter</button>
</form>
<?
if($_SERVER['REQUEST_METHOD']=='POST')
{
cek($_POST['n']);
}
?>
</body>
</html>
|
d81ed1efa468508c17f63bdeeabd54a8a599e978
|
[
"Markdown",
"PHP"
] | 3 |
PHP
|
ErlinaCahyani/tes
|
f71a94ba7c4c2867a0477570249196e83eaf0b13
|
c109b56c75e68b8808ff3dc57fa9e987760fd936
|
refs/heads/master
|
<repo_name>zsd971218/management<file_sep>/src/common/filter.js
import Vue from 'vue'
Vue.filter('dateFormat', function (date) {
const time = new Date(date)
const y = time.getFullYear()
const m = (time.getMonth() + 1 + '').padStart(2, '0')
const d = (time.getDate() + '').padStart(2, '0')
const hh = (time.getHours() + '').padStart(2, '0')
const mm = (time.getMinutes() + '').padStart(2, '0')
const ss = (time.getSeconds() + '').padStart(2, '0')
return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
})<file_sep>/src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
//导入相关插件
import 'plugins/util.js'
//导入全局过滤器
import 'common/filter.js'
//导入elemtntui组件
import './plugins/element.js'
//导入全局css和字体图标
import 'assets/css/global.css'
import 'assets/fonts/iconfont.css'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
<file_sep>/src/plugins/util.js
import Vue from 'vue'
//导入富文本编辑器
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css' // import styles
import 'quill/dist/quill.snow.css' // for snow theme
import 'quill/dist/quill.bubble.css' // for bubble theme
// 导入树形选择器
import ZKTable from 'vue-table-with-tree-grid'
Vue.use(VueQuillEditor, /* { default global options } */)
Vue.use(ZKTable)<file_sep>/src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//导入组件
const Login = () => import('views/login/Login');
const Home = () => import('views/home/Home');
const Users = () => import('views/home/child/users/Users.vue');
const Rights = () => import('views/home/child/rights/Rights.vue')
const Roles = () => import('views/home/child/rights/Roles.vue')
const Cate = () => import('views/home/child/goods/Cate.vue')
const Params = () => import('views/home/child/goods/Params.vue')
const GoodsList = () => import('views/home/child/goods/GoodsList.vue')
const AddGoods = () => import('views/home/child/goods/AddGoods.vue')
const Orders = () => import('views/home/child/orders/Orders.vue')
const Reports = () => import('views/home/child/reports/Reports.vue')
const routes = [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
component: Login
}, {
path: '/home',
component: Home,
redirect: '/users',
children: [{
path: '/users',
component: Users
}, {
path: '/rights',
component: Rights
}, {
path: '/roles',
component: Roles
}, {
path: '/categories',
component: Cate
},
{
path: '/params',
component: Params
}, {
path: '/goods',
component: GoodsList
}, {
path: '/addgoods',
component: AddGoods
}, {
path: '/orders',
component: Orders
}, {
path: '/reports',
component: Reports
}
],
},
]
const router = new VueRouter({
mode: 'hash',
routes
})
router.beforeEach((to, from, next) => {
//console.log(to.path);
if (to.path === '/login') {
next()
} else {
const tokenStr = window.sessionStorage.getItem('token');
//console.log(!tokenStr);
if (!tokenStr) {
next('/login')
return
} else {
next()
}
}
})
export default router
|
918de0cd48b93e1df8db43905643bf9e4e62b7f9
|
[
"JavaScript"
] | 4 |
JavaScript
|
zsd971218/management
|
75f4ea93105557e09895349ca60e05f5ec3e7321
|
76371cded4d9c9c14484eab6338e3de79dc86991
|
refs/heads/master
|
<repo_name>gbarrs-at-em/MappingGenerator<file_sep>/MappingGenerator/MappingGenerator/MappingGenerator/Mappings/CloneMappingEngine.cs
using System;
using System.Linq;
using MappingGenerator.RoslynHelpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
namespace MappingGenerator.Mappings
{
public class CloneMappingEngine: MappingEngine
{
public CloneMappingEngine(SemanticModel semanticModel, SyntaxGenerator syntaxGenerator, IAssemblySymbol contextAssembly)
: base(semanticModel, syntaxGenerator, contextAssembly)
{
}
protected override bool ShouldCreateConversionBetweenTypes(ITypeSymbol targetType, ITypeSymbol sourceType)
{
if (targetType.Equals(sourceType) && SymbolHelper.IsNullable(targetType, out _))
{
return false;
}
return ObjectHelper.IsSimpleType(targetType) == false && ObjectHelper.IsSimpleType(sourceType) == false;
}
protected override MappingElement TryToCreateMappingExpression(MappingElement source, ITypeSymbol targetType, MappingPath mappingPath)
{
//TODO: check if source is not null (conditional member access)
if (mappingPath.Length > 1 && source.ExpressionType.AllInterfaces.Any(x => x.Name == "ICloneable") && source.ExpressionType.SpecialType!=SpecialType.System_Array)
{
var invokeClone = syntaxGenerator.InvocationExpression(syntaxGenerator.MemberAccessExpression(source.Expression, "Clone"));
var cloneMethods = targetType.GetMembers("Clone");
if (cloneMethods.Any(IsGenericCloneMethod))
{
return new MappingElement()
{
ExpressionType = targetType,
Expression = invokeClone as ExpressionSyntax
};
}
var objectClone = cloneMethods.FirstOrDefault(x => x is IMethodSymbol md && md.Parameters.Length == 0);
if (objectClone != null)
{
var objectCLoneMethod = (IMethodSymbol) objectClone;
if(CanBeAccessedInCurrentContext(objectCLoneMethod) )
{
return new MappingElement()
{
ExpressionType = targetType,
Expression = syntaxGenerator.TryCastExpression(invokeClone, targetType) as ExpressionSyntax
};
}
}
var implicitClone = targetType.GetMembers("System.ICloneable.Clone").FirstOrDefault();
if (implicitClone!=null)
{
var castedOnICloneable = syntaxGenerator.CastExpression(SyntaxFactory.ParseTypeName("ICloneable"), source.Expression);
return new MappingElement()
{
ExpressionType = targetType,
Expression = syntaxGenerator.TryCastExpression(syntaxGenerator.InvocationExpression(syntaxGenerator.MemberAccessExpression(castedOnICloneable, "Clone")), targetType) as ExpressionSyntax
};
}
}
return base.TryToCreateMappingExpression(source, targetType, mappingPath);
}
private bool IsGenericCloneMethod(ISymbol x)
{
return x is IMethodSymbol md &&
md.ReturnType.ToString().Equals("object", StringComparison.OrdinalIgnoreCase) == false &&
md.Parameters.Length == 0 &&
CanBeAccessedInCurrentContext(md);
}
private bool CanBeAccessedInCurrentContext(IMethodSymbol objectCLoneMethod)
{
return objectCLoneMethod.DeclaredAccessibility == Accessibility.Public ||
(objectCLoneMethod.DeclaredAccessibility == Accessibility.Internal && objectCLoneMethod.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(contextAssembly));
}
}
}<file_sep>/MappingGenerator/MappingGenerator/MappingGenerator/Mappings/MappingMatchers/BestPossibleMatcher.cs
using System;
using System.Collections.Generic;
using System.Linq;
using MappingGenerator.Mappings.SourceFinders;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
namespace MappingGenerator.Mappings.MappingMatchers
{
class BestPossibleMatcher : IMappingMatcher
{
private readonly IReadOnlyList<SingleSourceMatcher> matchers;
public BestPossibleMatcher(IReadOnlyList<IMappingSourceFinder> sourceFinders)
{
matchers = sourceFinders.Select(x => new SingleSourceMatcher(x)).ToList();
}
public IReadOnlyList<MappingMatch> MatchAll(IEnumerable<IPropertySymbol> targets, SyntaxGenerator syntaxGenerator, SyntaxNode globalTargetAccessor = null)
{
return matchers.Select(x => x.MatchAll(targets, syntaxGenerator, globalTargetAccessor))
.OrderByDescending(x => x.Count).FirstOrDefault() ?? Array.Empty<MappingMatch>();
}
}
}<file_sep>/MappingGenerator/OnBuildGenerator/MappingInterface.cs
using System;
using System.Diagnostics;
namespace MappingGenerator.OnBuildGenerator
{
[AttributeUsage(AttributeTargets.Interface)]
[Conditional("CodeGeneration")]
public class MappingInterface:Attribute
{
}
}
<file_sep>/MappingGenerator/MappingGenerator/MappingGenerator/Mappings/MappingImplementors/MultiParameterMappingConstructorImplementor.cs
using System.Collections.Generic;
using MappingGenerator.Mappings.MappingMatchers;
using MappingGenerator.Mappings.SourceFinders;
using MappingGenerator.RoslynHelpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
namespace MappingGenerator.Mappings.MappingImplementors
{
class MultiParameterMappingConstructorImplementor:IMappingMethodImplementor
{
public bool CanImplement(IMethodSymbol methodSymbol)
{
return methodSymbol.Parameters.Length > 1 && SymbolHelper.IsConstructor(methodSymbol);
}
public IEnumerable<SyntaxNode> GenerateImplementation(IMethodSymbol methodSymbol, SyntaxGenerator generator, SemanticModel semanticModel)
{
var mappingEngine = new MappingEngine(semanticModel, generator, methodSymbol.ContainingAssembly);
var sourceFinder = new LocalScopeMappingSourceFinder(semanticModel, methodSymbol.Parameters);
var targets = ObjectHelper.GetFieldsThaCanBeSetFromConstructor(methodSymbol.ContainingType);
return mappingEngine.MapUsingSimpleAssignment(targets, new SingleSourceMatcher(sourceFinder));
}
}
}<file_sep>/MappingGenerator/MappingGenerator/MappingGenerator/Features/Refactorings/MappingGeneratorRefactoring.cs
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using MappingGenerator.Mappings;
using MappingGenerator.MethodHelpers;
using MappingGenerator.RoslynHelpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
namespace MappingGenerator.Features.Refactorings
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = nameof(MappingGeneratorRefactoring)), Shared]
public class MappingGeneratorRefactoring : CodeRefactoringProvider
{
private const string title = "Generate mapping code";
private static readonly MappingImplementorEngine MappingImplementorEngine = new MappingImplementorEngine();
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span);
await TryToRegisterRefactoring(context, node);
}
private async Task TryToRegisterRefactoring(CodeRefactoringContext context, SyntaxNode node)
{
switch (node)
{
case BaseMethodDeclarationSyntax methodDeclaration when IsMappingMethodCandidate(methodDeclaration):
if (methodDeclaration.Parent.Kind() != SyntaxKind.InterfaceDeclaration )
{
var semanticModel = await context.Document.GetSemanticModelAsync();
var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration);
if (MappingImplementorEngine.CanProvideMappingImplementationFor(methodSymbol))
{
var generateMappingAction = CodeAction.Create(title: title, createChangedDocument: async (c) => await GenerateMappingMethodBody(context.Document, methodDeclaration, c), equivalenceKey: title);
context.RegisterRefactoring(generateMappingAction);
}
}
break;
case IdentifierNameSyntax _:
case ParameterListSyntax _:
await TryToRegisterRefactoring(context, node.Parent);
break;
}
}
private static bool IsMappingMethodCandidate(BaseMethodDeclarationSyntax methodDeclaration)
{
if (methodDeclaration is MethodDeclarationSyntax)
{
return true;
}
if (methodDeclaration is ConstructorDeclarationSyntax constructorDeclaration && constructorDeclaration.ParameterList.Parameters.Count >= 1)
{
return true;
}
return false;
}
private async Task<Document> GenerateMappingMethodBody(Document document, BaseMethodDeclarationSyntax methodSyntax, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
var methodSymbol = semanticModel.GetDeclaredSymbol(methodSyntax);
var generator = SyntaxGenerator.GetGenerator(document);
var blockSyntax = MappingImplementorEngine.GenerateMappingBlock(methodSymbol, generator, semanticModel);
return await document.ReplaceNodes(methodSyntax, methodSyntax.WithOnlyBody(blockSyntax), cancellationToken);
}
}
}
<file_sep>/MappingGenerator/MappingGenerator/MappingGenerator/Mappings/MappingEngine.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MappingGenerator.Mappings.MappingMatchers;
using MappingGenerator.Mappings.SourceFinders;
using MappingGenerator.MethodHelpers;
using MappingGenerator.RoslynHelpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
namespace MappingGenerator.Mappings
{
public class MappingEngine
{
protected readonly SemanticModel semanticModel;
protected readonly SyntaxGenerator syntaxGenerator;
protected readonly IAssemblySymbol contextAssembly;
public MappingEngine(SemanticModel semanticModel, SyntaxGenerator syntaxGenerator, IAssemblySymbol contextAssembly)
{
this.semanticModel = semanticModel;
this.syntaxGenerator = syntaxGenerator;
this.contextAssembly = contextAssembly;
}
public TypeInfo GetExpressionTypeInfo(SyntaxNode expression)
{
return semanticModel.GetTypeInfo(expression);
}
public static async Task<MappingEngine> Create(Document document, CancellationToken cancellationToken, IAssemblySymbol contextAssembly)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
var syntaxGenerator = SyntaxGenerator.GetGenerator(document);
return new MappingEngine(semanticModel, syntaxGenerator, contextAssembly);
}
public ExpressionSyntax MapExpression(ExpressionSyntax sourceExpression, ITypeSymbol sourceType, ITypeSymbol destinationType)
{
var mappingSource = new MappingElement
{
Expression = sourceExpression,
ExpressionType = sourceType
};
return MapExpression(mappingSource, destinationType).Expression;
}
public MappingElement MapExpression(MappingElement element, ITypeSymbol targetType, MappingPath mappingPath = null)
{
if (element == null)
{
return null;
}
if (mappingPath == null)
{
mappingPath = new MappingPath();
}
var sourceType = element.ExpressionType;
if (mappingPath.AddToMapped(sourceType) == false)
{
return new MappingElement()
{
ExpressionType = sourceType,
Expression = element.Expression.WithTrailingTrivia(SyntaxFactory.Comment(" /* Stop recursive mapping */"))
};
}
if (ObjectHelper.IsSimpleType(targetType) && SymbolHelper.IsNullable(sourceType, out var underlyingType) )
{
element = new MappingElement()
{
Expression = (ExpressionSyntax)syntaxGenerator.MemberAccessExpression(element.Expression, "Value"),
ExpressionType = underlyingType
};
}
if (IsUnwrappingNeeded(targetType, element))
{
return TryToUnwrap(targetType, element);
}
if (ShouldCreateConversionBetweenTypes(targetType, sourceType))
{
return TryToCreateMappingExpression(element, targetType, mappingPath);
}
return element;
}
protected virtual bool ShouldCreateConversionBetweenTypes(ITypeSymbol targetType, ITypeSymbol sourceType)
{
return sourceType.CanBeAssignedTo(targetType) == false && ObjectHelper.IsSimpleType(targetType)==false && ObjectHelper.IsSimpleType(sourceType)==false;
}
protected virtual MappingElement TryToCreateMappingExpression(MappingElement source, ITypeSymbol targetType, MappingPath mappingPath)
{
//TODO: If source expression is method or constructor invocation then we should extract local variable and use it im mappings as a reference
var namedTargetType = targetType as INamedTypeSymbol;
if (namedTargetType != null)
{
var directlyMappingConstructor = namedTargetType.Constructors.FirstOrDefault(c => c.Parameters.Length == 1 && c.Parameters[0].Type.Equals(source.ExpressionType));
if (directlyMappingConstructor != null)
{
var constructorParameters = SyntaxFactory.ArgumentList().AddArguments(SyntaxFactory.Argument(source.Expression));
var creationExpression = syntaxGenerator.ObjectCreationExpression(targetType, constructorParameters.Arguments);
return new MappingElement()
{
ExpressionType = targetType,
Expression = (ExpressionSyntax) creationExpression
};
}
}
if (MappingHelper.IsMappingBetweenCollections(targetType, source.ExpressionType))
{
return new MappingElement()
{
ExpressionType = targetType,
Expression = MapCollections(source.Expression, source.ExpressionType, targetType, mappingPath.Clone()) as ExpressionSyntax
};
}
var subMappingSourceFinder = new ObjectMembersMappingSourceFinder(source.ExpressionType, source.Expression, syntaxGenerator);
if (namedTargetType != null)
{
//maybe there is constructor that accepts parameter matching source properties
var constructorOverloadParameterSets = namedTargetType.Constructors.Select(x => x.Parameters);
var matchedOverload = MethodHelper.FindBestParametersMatch(subMappingSourceFinder, constructorOverloadParameterSets);
if (matchedOverload != null)
{
var creationExpression = ((ObjectCreationExpressionSyntax)syntaxGenerator.ObjectCreationExpression(targetType, matchedOverload.ToArgumentListSyntax(this).Arguments));
var matchedSources = matchedOverload.GetMatchedSources();
var restSourceFinder = new IgnorableMappingSourceFinder(subMappingSourceFinder, foundElement =>
{
return matchedSources.Any(x => x.Expression.IsEquivalentTo(foundElement.Expression));
});
var mappingMatcher = new SingleSourceMatcher(restSourceFinder);
return new MappingElement()
{
ExpressionType = targetType,
Expression = AddInitializerWithMapping(creationExpression, mappingMatcher, targetType, mappingPath)
};
}
}
var objectCreationExpressionSyntax = ((ObjectCreationExpressionSyntax) syntaxGenerator.ObjectCreationExpression(targetType));
var subMappingMatcher = new SingleSourceMatcher(subMappingSourceFinder);
return new MappingElement()
{
ExpressionType = targetType,
Expression = AddInitializerWithMapping(objectCreationExpressionSyntax, subMappingMatcher, targetType, mappingPath)
};
}
public ObjectCreationExpressionSyntax AddInitializerWithMapping(
ObjectCreationExpressionSyntax objectCreationExpression, IMappingMatcher mappingMatcher,
ITypeSymbol createdObjectTyp,
MappingPath mappingPath = null)
{
var propertiesToSet = ObjectHelper.GetFieldsThaCanBeSetPublicly(createdObjectTyp, contextAssembly);
var assignments = MapUsingSimpleAssignment(propertiesToSet, mappingMatcher, mappingPath).ToList();
if (assignments.Count == 0)
{
return objectCreationExpression;
}
var initializerExpressionSyntax = SyntaxFactory.InitializerExpression(SyntaxKind.ObjectInitializerExpression, new SeparatedSyntaxList<ExpressionSyntax>().AddRange(assignments)).FixInitializerExpressionFormatting(objectCreationExpression);
return objectCreationExpression.WithInitializer(initializerExpressionSyntax);
}
public IEnumerable<ExpressionSyntax> MapUsingSimpleAssignment(IEnumerable<IPropertySymbol> targets, IMappingMatcher mappingMatcher,
MappingPath mappingPath = null, SyntaxNode globalTargetAccessor = null)
{
if (mappingPath == null)
{
mappingPath = new MappingPath();
}
return mappingMatcher.MatchAll(targets, syntaxGenerator, globalTargetAccessor)
.Select(match =>
{
var sourceExpression = this.MapExpression(match.Source, match.Target.ExpressionType, mappingPath.Clone()).Expression;
return (ExpressionSyntax)syntaxGenerator.AssignmentStatement(match.Target.Expression, sourceExpression);
}).ToList();
}
private bool IsUnwrappingNeeded(ITypeSymbol targetType, MappingElement element)
{
return targetType.Equals(element.ExpressionType) == false && (ObjectHelper.IsSimpleType(targetType) || SymbolHelper.IsNullable(targetType, out _));
}
private MappingElement TryToUnwrap(ITypeSymbol targetType, MappingElement element)
{
var sourceAccess = element.Expression as SyntaxNode;
var conversion = semanticModel.Compilation.ClassifyConversion(element.ExpressionType, targetType);
if (conversion.Exists == false)
{
var wrapper = GetWrappingInfo(element.ExpressionType, targetType);
if (wrapper.Type == WrapperInfoType.Property)
{
return new MappingElement()
{
Expression = (ExpressionSyntax) syntaxGenerator.MemberAccessExpression(sourceAccess, wrapper.UnwrappingProperty.Name),
ExpressionType = wrapper.UnwrappingProperty.Type
};
}
if (wrapper.Type == WrapperInfoType.Method)
{
var unwrappingMethodAccess = syntaxGenerator.MemberAccessExpression(sourceAccess, wrapper.UnwrappingMethod.Name);
return new MappingElement()
{
Expression = (InvocationExpressionSyntax) syntaxGenerator.InvocationExpression(unwrappingMethodAccess),
ExpressionType = wrapper.UnwrappingMethod.ReturnType
};
}
if (targetType.SpecialType == SpecialType.System_String && element.ExpressionType.TypeKind == TypeKind.Enum)
{
var toStringAccess = syntaxGenerator.MemberAccessExpression(element.Expression, "ToString");
return new MappingElement()
{
Expression = (InvocationExpressionSyntax)syntaxGenerator.InvocationExpression(toStringAccess),
ExpressionType = targetType
};
}
if (element.ExpressionType.SpecialType == SpecialType.System_String && targetType.TypeKind == TypeKind.Enum)
{
var parseEnumAccess = syntaxGenerator.MemberAccessExpression(SyntaxFactory.ParseTypeName("System.Enum"), "Parse");
var enumType = SyntaxFactory.ParseTypeName(targetType.Name);
var parseInvocation = (InvocationExpressionSyntax)syntaxGenerator.InvocationExpression(parseEnumAccess, new[]
{
syntaxGenerator.TypeOfExpression(enumType),
element.Expression,
syntaxGenerator.TrueLiteralExpression()
});
return new MappingElement()
{
Expression = (ExpressionSyntax) syntaxGenerator.CastExpression(enumType, parseInvocation),
ExpressionType = targetType
};
}
}
else if(conversion.IsExplicit)
{
return new MappingElement()
{
Expression = (ExpressionSyntax) syntaxGenerator.CastExpression(targetType, sourceAccess),
ExpressionType = targetType
};
}
return element;
}
private static WrapperInfo GetWrappingInfo(ITypeSymbol wrapperType, ITypeSymbol wrappedType)
{
var unwrappingProperties = ObjectHelper.GetUnwrappingProperties(wrapperType, wrappedType).ToList();
var unwrappingMethods = ObjectHelper.GetUnwrappingMethods(wrapperType, wrappedType).ToList();
if (unwrappingMethods.Count + unwrappingProperties.Count == 1)
{
if (unwrappingMethods.Count == 1)
{
return new WrapperInfo(unwrappingMethods.First());
}
return new WrapperInfo(unwrappingProperties.First());
}
return new WrapperInfo();
}
private SyntaxNode MapCollections(SyntaxNode sourceAccess, ITypeSymbol sourceListType, ITypeSymbol targetListType, MappingPath mappingPath)
{
var isReadonlyCollection = ObjectHelper.IsReadonlyCollection(targetListType);
var sourceListElementType = MappingHelper.GetElementType(sourceListType);
var targetListElementType = MappingHelper.GetElementType(targetListType);
if (ShouldCreateConversionBetweenTypes(targetListElementType, sourceListElementType))
{
var useConvert = CanUseConvert(sourceListType);
var selectAccess = useConvert ? syntaxGenerator.MemberAccessExpression(sourceAccess, "ConvertAll"): syntaxGenerator.MemberAccessExpression(sourceAccess, "Select");
var lambdaParameterName = NameHelper.CreateLambdaParameterName(sourceAccess);
var mappingLambda = CreateMappingLambda(lambdaParameterName, sourceListElementType, targetListElementType, mappingPath);
var selectInvocation = syntaxGenerator.InvocationExpression(selectAccess, mappingLambda);
var toList = useConvert? selectInvocation: AddMaterializeCollectionInvocation(syntaxGenerator, selectInvocation, targetListType);
return MappingHelper.WrapInReadonlyCollectionIfNecessary(toList, isReadonlyCollection, syntaxGenerator);
}
var toListInvocation = AddMaterializeCollectionInvocation(syntaxGenerator, sourceAccess, targetListType);
return MappingHelper.WrapInReadonlyCollectionIfNecessary(toListInvocation, isReadonlyCollection, syntaxGenerator);
}
private bool CanUseConvert(ITypeSymbol sourceListType)
{
return sourceListType.Name == "List" && sourceListType.GetMembers("ConvertAll").Length != 0;
}
public SyntaxNode CreateMappingLambda(string lambdaParameterName, ITypeSymbol sourceListElementType, ITypeSymbol targetListElementType, MappingPath mappingPath)
{
var listElementMappingStm = MapExpression(new MappingElement()
{
ExpressionType = sourceListElementType,
Expression = syntaxGenerator.IdentifierName(lambdaParameterName) as ExpressionSyntax
},
targetListElementType, mappingPath);
return syntaxGenerator.ValueReturningLambdaExpression(lambdaParameterName, listElementMappingStm.Expression);
}
private static SyntaxNode AddMaterializeCollectionInvocation(SyntaxGenerator generator, SyntaxNode sourceAccess, ITypeSymbol targetListType)
{
var materializeFunction = targetListType.Kind == SymbolKind.ArrayType? "ToArray": "ToList";
var toListAccess = generator.MemberAccessExpression(sourceAccess, materializeFunction );
return generator.InvocationExpression(toListAccess);
}
public ExpressionSyntax CreateDefaultExpression(ITypeSymbol typeSymbol)
{
return (ExpressionSyntax) syntaxGenerator.DefaultExpression(typeSymbol);
}
}
public class MappingPath
{
private List<ITypeSymbol> mapped;
public int Length => mapped.Count;
private MappingPath(List<ITypeSymbol> mapped)
{
this.mapped = mapped;
}
public MappingPath()
{
this.mapped = new List<ITypeSymbol>();
}
public bool AddToMapped(ITypeSymbol newType)
{
if (mapped.Contains(newType))
{
return false;
}
mapped.Add(newType);
return true;
}
public MappingPath Clone()
{
return new MappingPath(this.mapped.ToList());
}
}
}<file_sep>/MappingGenerator/MappingGenerator/MappingGenerator/Mappings/MappingMatchers/IMappingMatcher.cs
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
namespace MappingGenerator.Mappings.MappingMatchers
{
public interface IMappingMatcher
{
IReadOnlyList<MappingMatch> MatchAll(IEnumerable<IPropertySymbol> targets, SyntaxGenerator syntaxGenerator, SyntaxNode globalTargetAccessor = null);
}
}<file_sep>/MappingGenerator/MappingGenerator/MappingGenerator/RoslynHelpers/ObjectHelper.cs
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace MappingGenerator.RoslynHelpers
{
public static class ObjectHelper
{
private static bool IsPublicGetMethod(ISymbol x)
{
return x is IMethodSymbol mSymbol
&& mSymbol.ReturnsVoid == false
&& mSymbol.Parameters.Length == 0
&& x.DeclaredAccessibility == Accessibility.Public
&& x.IsImplicitlyDeclared == false
&& mSymbol.MethodKind == MethodKind.Ordinary
;
}
private static bool IsPublicPropertySymbol(ISymbol x)
{
if (x.Kind != SymbolKind.Property)
{
return false;
}
if (x is IPropertySymbol mSymbol)
{
if (mSymbol.IsStatic || mSymbol.IsIndexer || mSymbol.DeclaredAccessibility != Accessibility.Public)
{
return false;
}
return true;
}
return false;
}
public static IEnumerable<IPropertySymbol> GetUnwrappingProperties(ITypeSymbol wrapperType, ITypeSymbol wrappedType)
{
return GetPublicPropertySymbols(wrapperType).Where(x => x.GetMethod.DeclaredAccessibility == Accessibility.Public && x.Type == wrappedType);
}
public static IEnumerable<IMethodSymbol> GetUnwrappingMethods(ITypeSymbol wrapperType, ITypeSymbol wrappedType)
{
return GetPublicGetMethods(wrapperType).Where(x => x.DeclaredAccessibility == Accessibility.Public && x.ReturnType == wrappedType);
}
public static IEnumerable<IPropertySymbol> GetPublicPropertySymbols(ITypeSymbol source)
{
return GetBaseTypesAndThis(source).SelectMany(x=> x.GetMembers()).Where(IsPublicPropertySymbol).OfType<IPropertySymbol>();
}
public static IEnumerable<IMethodSymbol> GetPublicGetMethods(ITypeSymbol source)
{
return GetBaseTypesAndThis(source).SelectMany(x=> x.GetMembers()).Where(IsPublicGetMethod).OfType<IMethodSymbol>();
}
public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol type)
{
foreach (var unwrapped in type.UnwrapGeneric())
{
var current = unwrapped;
while (current != null && IsSystemObject(current) == false)
{
yield return current;
current = current.BaseType;
}
}
}
public static bool IsSystemObject(ITypeSymbol current)
{
return current.Name == "Object" && current.ContainingNamespace.Name =="System";
}
public static bool IsReadonlyCollection(ITypeSymbol current)
{
return current.Name == "ReadOnlyCollection";
}
public static bool IsSimpleType(ITypeSymbol type)
{
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
case SpecialType.System_SByte:
case SpecialType.System_Int16:
case SpecialType.System_Int32:
case SpecialType.System_Int64:
case SpecialType.System_Byte:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Char:
case SpecialType.System_String:
case SpecialType.System_Object:
case SpecialType.System_Decimal:
case SpecialType.System_DateTime:
case SpecialType.System_Enum:
return true;
}
switch (type.TypeKind)
{
case TypeKind.Enum:
return true;
}
return false;
}
public static bool HasInterface(ITypeSymbol xt, string interfaceName)
{
return xt.OriginalDefinition.AllInterfaces.Any(x => x.ToDisplayString() == interfaceName);
}
public static IEnumerable<IPropertySymbol> GetFieldsThaCanBeSetFromConstructor(ITypeSymbol type)
{
return ObjectHelper.GetPublicPropertySymbols(type)
.Where(property => property.SetMethod != null || property.CanBeSetOnlyFromConstructor());
}
public static IEnumerable<IPropertySymbol> GetFieldsThaCanBeSetPublicly(ITypeSymbol type,
IAssemblySymbol contextAssembly)
{
var canSetInternalFields =contextAssembly.IsSameAssemblyOrHasFriendAccessTo(type.ContainingAssembly);
return GetPublicPropertySymbols(type).Where(property => property.SetMethod != null && property.CanBeSetPublicly(canSetInternalFields));
}
public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly)
{
var areEquals = assembly.Equals(toAssembly);
if (areEquals == false && toAssembly == null)
{
return false;
}
return
areEquals ||
(assembly.IsInteractive && toAssembly.IsInteractive) ||
toAssembly.GivesAccessTo(assembly);
}
public static IEnumerable<IPropertySymbol> GetFieldsThaCanBeSetPrivately(ITypeSymbol type)
{
return ObjectHelper.GetPublicPropertySymbols(type)
.Where(property => property.SetMethod != null && property.CanBeSetPrivately());
}
public static IAssemblySymbol FindContextAssembly(this SemanticModel semanticModel, SyntaxNode node )
{
var type = node.FindNearestContainer<ClassDeclarationSyntax, StructDeclarationSyntax>();
var symbol = semanticModel.GetDeclaredSymbol(type);
return symbol.ContainingAssembly;
}
}
}<file_sep>/MappingGenerator/OnBuildGenerator/OnBuildMappingGenerator.cs
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MappingGenerator.Mappings;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using SmartCodeGenerator.Sdk;
namespace MappingGenerator.OnBuildGenerator
{
[CodeGenerator(typeof(MappingInterface))]
public class OnBuildMappingGenerator : ICodeGenerator
{
private const string GeneratorName = "MappingGenerator.OnBuildMappingGenerator";
private readonly MappingImplementorEngine ImplementorEngine = new MappingImplementorEngine();
public Task<GenerationResult> GenerateAsync(CSharpSyntaxNode processedNode, AttributeData markerAttribute, TransformationContext context, CancellationToken cancellationToken)
{
var syntaxGenerator = SyntaxGenerator.GetGenerator(context.Document);
var mappingDeclaration = (InterfaceDeclarationSyntax)processedNode;
var interfaceSymbol = context.SemanticModel.GetDeclaredSymbol(mappingDeclaration);
var mappingClass = (ClassDeclarationSyntax)syntaxGenerator.ClassDeclaration(
mappingDeclaration.Identifier.Text.Substring(1),
accessibility: Accessibility.Public,
modifiers: DeclarationModifiers.Partial,
interfaceTypes: new List<SyntaxNode>()
{
syntaxGenerator.TypeExpression(interfaceSymbol)
},
members: mappingDeclaration.Members.Select(x =>
{
if (x is MethodDeclarationSyntax methodDeclaration)
{
var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclaration);
var statements = ImplementorEngine.CanProvideMappingImplementationFor(methodSymbol) ? ImplementorEngine.GenerateMappingStatements(methodSymbol, syntaxGenerator, context.SemanticModel) :
new List<StatementSyntax>()
{
GenerateThrowNotSupportedException(context, syntaxGenerator, methodSymbol.Name)
};
var methodDeclarationSyntax = ((MethodDeclarationSyntax)syntaxGenerator.MethodDeclaration(
methodDeclaration.Identifier.Text,
parameters: methodDeclaration.ParameterList.Parameters,
accessibility: Accessibility.Public,
modifiers: DeclarationModifiers.Virtual,
typeParameters: methodDeclaration.TypeParameterList?.Parameters.Select(xx => xx.Identifier.Text),
returnType: methodDeclaration.ReturnType
)).WithBody(SyntaxFactory.Block(statements));
return methodDeclarationSyntax;
}
return x;
}));
var newRoot = WrapInTheSameNamespace(mappingClass, processedNode);
return Task.FromResult(new GenerationResult()
{
Members = SyntaxFactory.SingletonList(newRoot),
Usings = new SyntaxList<UsingDirectiveSyntax>(new[]
{
SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")),
SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Linq")),
SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(interfaceSymbol.ContainingNamespace.ToDisplayString())),
})
});
}
private static StatementSyntax GenerateThrowNotSupportedException(TransformationContext context, SyntaxGenerator syntaxGenerator, string methodName)
{
var notImplementedExceptionType = context.SemanticModel.Compilation.GetTypeByMetadataName("System.NotSupportedException");
var createNotImplementedException = syntaxGenerator.ObjectCreationExpression(notImplementedExceptionType,
syntaxGenerator.LiteralExpression($"'{methodName}' method signature is not supported by {GeneratorName}"));
return (StatementSyntax)syntaxGenerator.ThrowStatement(createNotImplementedException);
}
private static MemberDeclarationSyntax WrapInTheSameNamespace(ClassDeclarationSyntax generatedClass, SyntaxNode ancestor)
{
if (ancestor is NamespaceDeclarationSyntax namespaceDeclaration)
{
return SyntaxFactory.NamespaceDeclaration(namespaceDeclaration.Name.WithoutTrivia())
.AddMembers(generatedClass);
}
if (ancestor.Parent != null)
{
return WrapInTheSameNamespace(generatedClass, ancestor.Parent);
}
return generatedClass;
}
}
}<file_sep>/MappingGenerator/MappingGenerator/MappingGenerator/RoslynHelpers/SymbolHelper.cs
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace MappingGenerator.RoslynHelpers
{
internal static class SymbolHelper
{
public static bool IsConstructor(IMethodSymbol methodSymbol)
{
return methodSymbol.MethodKind == MethodKind.Constructor;
}
public static IEnumerable<ITypeSymbol> UnwrapGeneric(this ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.TypeParameter && typeSymbol is ITypeParameterSymbol namedType && namedType.Kind != SymbolKind.ErrorType)
{
return namedType.ConstraintTypes;
}
return new []{typeSymbol};
}
public static bool CanBeSetPrivately(this IPropertySymbol property)
{
var propertyDeclaration = property.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).OfType<PropertyDeclarationSyntax>().FirstOrDefault();
if (propertyDeclaration?.AccessorList == null)
{
return false;
}
return HasPrivateSetter(propertyDeclaration) || HasPublicSetter(propertyDeclaration, isInternalAccessible:true);
}
public static bool CanBeSetPublicly(this IPropertySymbol property, bool isInternalAccessible)
{
if (IsDeclaredOutsideTheSourcecode(property))
{
return property.IsReadOnly == false &&
property.SetMethod != null &&
property.SetMethod.DeclaredAccessibility == Accessibility.Public;
}
var propertyDeclaration = property.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).OfType<PropertyDeclarationSyntax>().FirstOrDefault();
if (propertyDeclaration?.AccessorList == null)
{
return false;
}
return HasPublicSetter(propertyDeclaration, isInternalAccessible);
}
public static bool CanBeSetOnlyFromConstructor(this IPropertySymbol property)
{
if (IsDeclaredOutsideTheSourcecode(property))
{
return property.IsReadOnly ||
(property.SetMethod != null &&
new[] {Accessibility.Public, Accessibility.Protected}.Contains(property.SetMethod.DeclaredAccessibility)
);
}
var propertyDeclaration = property.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).OfType<PropertyDeclarationSyntax>().FirstOrDefault();
if (propertyDeclaration?.AccessorList == null)
{
return false;
}
if (HasPrivateSetter(propertyDeclaration))
{
return false;
}
return propertyDeclaration.AccessorList.Accessors.Count == 1 && propertyDeclaration.AccessorList.Accessors.SingleOrDefault(IsAutoGetter) != null;
}
private static bool IsDeclaredOutsideTheSourcecode(IPropertySymbol property)
{
return property.DeclaringSyntaxReferences.Length == 0;
}
private static bool HasPrivateSetter(PropertyDeclarationSyntax propertyDeclaration)
{
return propertyDeclaration.AccessorList.Accessors.Any(x =>x.Keyword.Kind() == SyntaxKind.SetKeyword && x.Modifiers.Any(m => m.Kind() == SyntaxKind.PrivateKeyword));
}
private static bool HasPublicSetter(PropertyDeclarationSyntax propertyDeclaration, bool isInternalAccessible)
{
return propertyDeclaration.AccessorList.Accessors.Any(x =>
{
if (x.Keyword.Kind() == SyntaxKind.SetKeyword)
{
return x.Modifiers.Count == 0 || x.Modifiers.Any(m => AllowsForPublic(m, isInternalAccessible));
}
return false;
});
}
private static bool AllowsForPublic(SyntaxToken accessor, bool isInternalAccessible)
{
switch (accessor.Kind())
{
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
return false;
case SyntaxKind.InternalKeyword when isInternalAccessible:
return true;
case SyntaxKind.PublicKeyword:
return true;
default:
return false;
}
}
private static bool IsAutoGetter(AccessorDeclarationSyntax x)
{
return x.IsKind(SyntaxKind.GetAccessorDeclaration) && x.Body ==null && x.ExpressionBody == null;
}
public static bool IsNullable(ITypeSymbol type, out ITypeSymbol underlyingType)
{
if (type.TypeKind == TypeKind.Struct && type.Name == "Nullable")
{
underlyingType = GetUnderlyingNullableType(type);
return true;
}
underlyingType = null;
return false;
}
public static ITypeSymbol GetUnderlyingNullableType(ITypeSymbol type)
{
return ((INamedTypeSymbol) type).TypeArguments.First();
}
}
}
|
d3292e6d6b5ee7838ea241b7337f1f0aea999611
|
[
"C#"
] | 10 |
C#
|
gbarrs-at-em/MappingGenerator
|
250b4c965f2267fa0973ab585fd751ca28f30c98
|
9ea32e55caa153f282455ef592ba7793a45ea5e3
|
refs/heads/master
|
<file_sep>var tool = require('./tool.js');
console.log(tool);
<file_sep>function add(anh , em){
return anh+em;
}
module.exports = 888
|
eed32fe5cb44c4d4f496926408ddd4d9137728d5
|
[
"JavaScript"
] | 2 |
JavaScript
|
tohung99/mau
|
15cf6787e1afd217e9d41590a779b3e95a0dc338
|
65a735b36d0293021dd08590a80679f001833829
|
refs/heads/master
|
<repo_name>maheshkafle/OrangeHRM-MyInfo-E2ETest<file_sep>/src/main/java/com/orangehrm/qa/pages/MembershipsPage.java
package com.orangehrm.qa.pages;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.utils.TestUtil;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class MembershipsPage extends TestBase {
@FindBy(id = "btnAddMembershipDetail")
WebElement BtnAddMembershipDetail;
@FindBy(id = "membership_membership")
WebElement Membership;
@FindBy(id = "membership_subscriptionPaidBy")
WebElement SubscriptionPaidBy;
@FindBy(id = "membership_subscriptionAmount")
WebElement SubscriptionAmount;
@FindBy(id = "membership_currency")
WebElement MembershipCurrency;
@FindBy(id = "membership_subscriptionCommenceDate")
WebElement SubscriptionCommenceDate;
@FindBy(id = "membership_subscriptionRenewalDate")
WebElement SubscriptionRenewalDate;
@FindBy(id = "btnSaveMembership")
WebElement BtnSaveMembership;
@FindBy(className = "message")
WebElement CheckStatusDiv;
@FindBy(id = "btnAddAttachment")
WebElement BtnAddAttachment;
@FindBy(id = "ufile")
WebElement BtnUpload;
@FindBy(id = "btnSaveAttachment")
WebElement BtnSaveAttachment;
//Hard coded xpath which contains text British Computer Society (BCS): So pass accordingly
@FindBy(xpath = "//a[contains(text(), \"British Computer Society (BCS)\")]/parent::td//preceding-sibling::td//input[@class='checkboxMem']")
WebElement MembershipCheckbox;
@FindBy(id = "delMemsBtn")
WebElement BtnDelMembership;
// Initializing Page Objects using constructor
public MembershipsPage(){
PageFactory.initElements(driver, this);
}
public void ClickBtnAddMembershipDetail(){
TestUtil.doClick(BtnAddMembershipDetail);
}
public void AddMembership(String valueMembership) throws InterruptedException {
TestUtil.selectDropdownValue(Membership, valueMembership);
}
public void AddSubscriptionPaidBy(String valueSubscriptionPaidBy) throws InterruptedException {
TestUtil.selectDropdownValue(SubscriptionPaidBy, valueSubscriptionPaidBy);
}
public void AddSubscriptionAmount(String valueSubscriptionAmount) throws InterruptedException {
TestUtil.doSendKeys(SubscriptionAmount, valueSubscriptionAmount);
}
public void AddMembershipCurrency(String valueMembershipCurrency) throws InterruptedException {
TestUtil.selectDropdownValue(MembershipCurrency, valueMembershipCurrency);
}
public void AddSubscriptionCommenceDate(String valueSubscriptionCommenceDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, SubscriptionCommenceDate, valueSubscriptionCommenceDate);
}
public void AddSubscriptionRenewalDate(String valueSubscriptionRenewalDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, SubscriptionRenewalDate, valueSubscriptionRenewalDate);
}
public void ClickOnBtnSaveMembership(){
TestUtil.doClick(BtnSaveMembership);
}
public boolean IsMembershipsAdded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void uploadMembershipAttach(){
TestUtil.uploadAttachment(BtnAddAttachment, BtnUpload, BtnSaveAttachment, prop.getProperty("pathToMembershipAttachment"));
}
public boolean IsMembershipAttachUploaded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void DeleteMembershipDetails() {
TestUtil.doClick(MembershipCheckbox);
TestUtil.doClick(BtnDelMembership);
}
public boolean IsMembershipDetailsDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
}
<file_sep>/src/test/java/com/orangehrm/qa/testcases/DashboardPageTest.java
package com.orangehrm.qa.testcases;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.pages.DashboardPage;
import com.orangehrm.qa.pages.LoginPage;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DashboardPageTest extends TestBase {
DashboardPage dashboardPage;
LoginPage loginPage;
public DashboardPageTest(){
super();
}
@BeforeMethod
public void setUp(){
initialization();
loginPage = new LoginPage();
dashboardPage = new DashboardPage();
dashboardPage = loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
}
@Test(priority = 1)
public void testValidateDashboardLogo(){
Boolean flag = dashboardPage.validateDashboardLogo();
Assert.assertTrue(flag);
}
@AfterMethod
public void tearDown(){
driver.quit();
}
}
<file_sep>/src/main/java/com/orangehrm/qa/pages/ImmigrationPage.java
package com.orangehrm.qa.pages;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.utils.TestUtil;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class ImmigrationPage extends TestBase {
// Object Repo
@FindBy(id = "btnAdd")
WebElement BtnAddImmigrants;
@FindBy(id = "btnSave")
WebElement BtnSaveImmigrants;
@FindBy(id = "immigration_type_flag_2")
WebElement Visa;
@FindBy(id = "immigration_number")
WebElement ImmigrationNumber;
@FindBy(id = "immigration_passport_issue_date")
WebElement PassportIssueDate;
@FindBy(id = "immigration_passport_expire_date")
WebElement PassportExpireDate;
@FindBy(id = "immigration_i9_status")
WebElement ImmigrationStatus;
@FindBy(id = "immigration_country")
WebElement IssuedBy;
@FindBy(id = "immigration_i9_review_date")
WebElement ReviewDate;
@FindBy(id = "immigration_comments")
WebElement Comments;
@FindBy(className = "message")
WebElement CheckStatusDiv;
//Hard coded xpath which contains text Visa: So pass accordingly
@FindBy(xpath = "//a[contains(text(), 'Visa')]/parent::td//preceding-sibling::td//input[@class='checkbox']")
WebElement VisaCheckbox;
//Hard coded xpath which contains text png.png: So pass accordingly
@FindBy(xpath = "//a[contains(text(), 'png.png')]/parent::td//preceding-sibling::td//input[@class='checkboxAtch']")
WebElement AttachmentCheckbox;
@FindBy(id = "btnDelete")
WebElement DelImmigrantBtn;
@FindBy(id = "btnAddAttachment")
WebElement BtnAddAttachment;
@FindBy(id = "ufile")
WebElement BtnUploadAttachment;
@FindBy(id = "btnSaveAttachment")
WebElement BtnSaveAttachment;
@FindBy(id = "btnDeleteAttachment")
WebElement BtnDeleteAttachment;
// Initializing Page Objects using constructor
public ImmigrationPage(){
PageFactory.initElements(driver, this);
}
public void clickAddImmigrantBtn(){
TestUtil.doClick(BtnAddImmigrants);
}
public void clickDocumentCheckbox(){
TestUtil.doClick(Visa);
}
public void AddImmigrationNumber(String immigrationNumber){
TestUtil.doSendKeys(ImmigrationNumber, immigrationNumber);
}
public void AddPassportIssueDate(String passportIssueDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, PassportIssueDate, passportIssueDate);
}
public void AddPassportExpireDate(String passportExpireDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, PassportExpireDate, passportExpireDate);
}
public void AddImmigrationStatus(String immigrationStatus){
TestUtil.doSendKeys(ImmigrationStatus, immigrationStatus);
}
public void AddIssuedBy(String issuedBy) throws InterruptedException {
TestUtil.selectDropdownValue(IssuedBy, issuedBy);
}
public void AddPassportReviewDate(String reviewDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, ReviewDate, reviewDate);
}
public void AddComments(String comments){
TestUtil.doSendKeys(Comments, comments);
}
public void clickSaveImmigrantBtn(){
TestUtil.doClick(BtnSaveImmigrants);
}
public boolean isImmigrantsAdded() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void deleteImmigrants() {
TestUtil.doClick(VisaCheckbox);
TestUtil.doClick(DelImmigrantBtn);
}
public boolean isImmigrantsDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void attachImmigrantRecord() {
TestUtil.uploadAttachment(BtnAddAttachment, BtnUploadAttachment, BtnSaveAttachment, prop.getProperty("pathToImmigrantRecordAttachment"));
}
public Boolean isImmigrantRecordAttached(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void DeleteImmigrantAttachmentRecord() {
TestUtil.doClick(AttachmentCheckbox);
TestUtil.doClick(BtnDeleteAttachment);
}
public boolean isImmigrantAttachmentRecordDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
}
<file_sep>/src/main/java/com/orangehrm/qa/pages/PersonalDetailsPage.java
package com.orangehrm.qa.pages;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.utils.TestUtil;
import org.bson.assertions.Assertions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import java.util.ArrayList;
public class PersonalDetailsPage extends TestBase {
@FindBy(xpath = "//a[contains(text(), 'Contact Details')]")
WebElement ContactDetailsPageLink;
@FindBy(xpath = "//a[contains(text(), 'Emergency Contacts')]")
WebElement EmergencyContactsPageLink;
@FindBy(xpath = "//a[contains(text(), 'Dependents')]")
WebElement DependentsPageLink;
@FindBy(xpath = "//a[contains(text(), 'Immigration')]")
WebElement ImmigrationPageLink;
@FindBy(xpath = "//a[contains(text(), 'Salary')]")
WebElement SalaryPageLink;
@FindBy(xpath = "//a[contains(text(), 'Report-to')]")
WebElement ReportToPageLink;
@FindBy(id = "btnSave")
WebElement editSaveBtn;
@FindBy(id = "personal_txtEmpFirstName")
WebElement FirstName;
@FindBy(id = "personal_txtEmpMiddleName")
WebElement MiddleName;
@FindBy(id = "personal_txtEmpLastName")
WebElement LastName;
@FindBy(id = "personal_optGender_2")
WebElement FemaleRadioBtn;
@FindBy(id = "personal_txtLicExpDate")
WebElement LicenseExpiryDate;
@FindBy(id = "personal_cmbMarital")
WebElement MaritalStatus;
@FindBy(className = "message")
WebElement CheckStatusDiv;
@FindBy(id = "empPic")
WebElement EmployeePic;
@FindBy(id = "photofile")
WebElement browse;
@FindBy(xpath = "//input[contains(@value,'Upload')]")
WebElement uploadBtn;
// Initializing Page Objects using constructor
public PersonalDetailsPage(){
PageFactory.initElements(driver, this);
}
// Action
public ContactDetailsPage clickOnContactDetailsPageLink(){
ContactDetailsPageLink.click();
return new ContactDetailsPage();
}
public EmergencyContactsPage clickOnEmergencyContactsPageLink(){
EmergencyContactsPageLink.click();
return new EmergencyContactsPage();
}
public DependentsPage clickOnDependentsPageLink(){
DependentsPageLink.click();
return new DependentsPage();
}
public ImmigrationPage clickOnImmigrationPageLink(){
ImmigrationPageLink.click();
return new ImmigrationPage();
}
public JobPage clickOnJobPageLink(){
ArrayList<WebElement> JobLinks = (ArrayList<WebElement>) driver.findElements(By.xpath("//a[contains(text(), 'Job')]"));
for(int j=0; j<JobLinks.size(); j++){
System.out.println(JobLinks.get(j).getText());
String JobText = JobLinks.get(j).getText();
if(JobText.equals("Job")){
JobLinks.get(j).click();
break;
}
}
return new JobPage();
}
public SalaryPage clickOnSalaryPageLink(){
SalaryPageLink.click();
return new SalaryPage();
}
public ReportsToPage clickOnReportToPageLink(){
ReportToPageLink.click();
return new ReportsToPage();
}
public QualificationsPage clickOnQualificationsPageLink(){
ArrayList<WebElement> QualificationsLinks = (ArrayList<WebElement>) driver.findElements(By.xpath("//a[contains(text(), 'Qualifications')]"));
for(int j=0; j<QualificationsLinks.size(); j++){
System.out.println(QualificationsLinks.get(j).getText());
String JobText = QualificationsLinks.get(j).getText();
if(JobText.equals("Qualifications")){
QualificationsLinks.get(j).click();
break;
}
}
return new QualificationsPage();
}
public MembershipsPage clickOnMembershipsPageLink(){
ArrayList<WebElement> MembershipsLinks = (ArrayList<WebElement>) driver.findElements(By.xpath("//a[contains(text(), 'Memberships')]"));
for(int j=0; j<MembershipsLinks.size(); j++){
System.out.println(MembershipsLinks.get(j).getText());
String JobText = MembershipsLinks.get(j).getText();
if(JobText.equals("Memberships")){
MembershipsLinks.get(j).click();
break;
}
}
return new MembershipsPage();
}
public void clickOnEditBtn(){
editSaveBtn.click();
}
public void editFirstName(String firstName){
TestUtil.doSendKeys(FirstName, firstName);
}
public void editMiddleName(String middleName){
TestUtil.doSendKeys(MiddleName, middleName);
}
public void editLastName(String lastName){
TestUtil.doSendKeys(LastName, lastName);
}
public void clickGenderRadioBtn(){
TestUtil.doClick(FemaleRadioBtn);
}
public void selectLicenseExpiryDate() throws InterruptedException {
String licenseExpiryDate = prop.getProperty("licenseExpiryDate");
TestUtil.SelectDateFromCalenderCustom(driver, LicenseExpiryDate, licenseExpiryDate);
}
public void selectMaritalStatus() throws InterruptedException {
String maritalStatus = prop.getProperty("maritalStatus");
TestUtil.selectDropdownValue(MaritalStatus, maritalStatus);
}
public boolean isPersonalDetailsEdited(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void uploadEmployeeProfilePic(){
EmployeePic.click();
String path = prop.getProperty("pathToEmployeePic");
browse.sendKeys(path);
uploadBtn.click();
}
public boolean isEmployeePicUploaded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
}
<file_sep>/src/test/java/com/orangehrm/qa/testcases/ContactDetailsPageTest.java
package com.orangehrm.qa.testcases;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.pages.ContactDetailsPage;
import com.orangehrm.qa.pages.DashboardPage;
import com.orangehrm.qa.pages.LoginPage;
import com.orangehrm.qa.pages.PersonalDetailsPage;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ContactDetailsPageTest extends TestBase {
PersonalDetailsPage personalDetailsPage;
DashboardPage dashboardPage;
LoginPage loginPage;
ContactDetailsPage contactDetailsPage;
public ContactDetailsPageTest(){
super();
}
@BeforeMethod
public void setUp(){
initialization();
loginPage = new LoginPage();
dashboardPage = new DashboardPage();
personalDetailsPage = new PersonalDetailsPage();
contactDetailsPage = new ContactDetailsPage();
dashboardPage = loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
personalDetailsPage = dashboardPage.clickOnPersonalDetailsPageLink();
contactDetailsPage = personalDetailsPage.clickOnContactDetailsPageLink();
}
@Test(priority = 1)
public void verifyEditContactDetails() throws InterruptedException {
contactDetailsPage.clickOnEditBtn();
contactDetailsPage.editStreet1(prop.getProperty("street1"));
contactDetailsPage.editStreet2(prop.getProperty("street2"));
contactDetailsPage.editCity(prop.getProperty("city"));
contactDetailsPage.editProvince(prop.getProperty("province"));
contactDetailsPage.editPostalCode(prop.getProperty("postalcode"));
contactDetailsPage.editHomeTelephone(prop.getProperty("hometelephone"));
contactDetailsPage.editEmployeeMobileNo(prop.getProperty("employeemobileno"));
contactDetailsPage.editEmployeeWorkTelephoneNo(prop.getProperty("employeeworktelephoneno"));
contactDetailsPage.editEmployeeWorkEmail(prop.getProperty("employeeworkemail"));
contactDetailsPage.editEmployeeOtherEmail(prop.getProperty("employeeotheremail"));
contactDetailsPage.clickOnEditBtn();
Boolean flag = contactDetailsPage.isContactDetailsEdited();
Assert.assertTrue(flag);
Thread.sleep(2000);
}
@AfterMethod
public void tearDown(){
driver.quit();
}
}
<file_sep>/src/main/java/com/orangehrm/qa/pages/JobPage.java
package com.orangehrm.qa.pages;
public class JobPage {
}
<file_sep>/src/main/java/com/orangehrm/qa/pages/ReportsToPage.java
package com.orangehrm.qa.pages;
public class ReportsToPage {
}
<file_sep>/src/main/java/com/orangehrm/qa/pages/QualificationsPage.java
package com.orangehrm.qa.pages;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.utils.TestUtil;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class QualificationsPage extends TestBase {
// Object Repo
@FindBy(id = "addWorkExperience")
WebElement BtnAddWorkExperience;
@FindBy(id = "addEducation")
WebElement BtnAddEducation;
@FindBy(id = "addSkill")
WebElement BtnAddSkill;
@FindBy(id = "btnWorkExpSave")
WebElement BtnSaveWorkExperience;
@FindBy(id = "addLanguage")
WebElement BtnAddLanguage;
@FindBy(id = "addLicense")
WebElement BtnAddLicense;
@FindBy(id = "experience_employer")
WebElement Company;
@FindBy(id = "experience_jobtitle")
WebElement JobTitle;
@FindBy(id = "experience_from_date")
WebElement JobStartDate;
@FindBy(id = "experience_to_date")
WebElement JobEndDate;
@FindBy(id = "experience_comments")
WebElement Comments;
@FindBy(className = "message")
WebElement CheckStatusDiv;
//Hard coded xpath which contains text shi:dolutions: So pass accordingly
@FindBy(xpath = "//a[contains(text(), 'shi:dolutions')]/parent::td//preceding-sibling::td//input[@name='delWorkExp[]']")
WebElement WorkExpCheckbox;
@FindBy(id = "delWorkExperience")
WebElement BtndelWorkExperience;
@FindBy(id = "education_code")
WebElement EducationLevel;
@FindBy(id = "education_institute")
WebElement EducationInstitute;
@FindBy(id = "education_major")
WebElement EducationSpecialization;
@FindBy(id = "education_year")
WebElement EducationYear;
@FindBy(id = "education_gpa")
WebElement EducationGPA;
@FindBy(id = "education_start_date")
WebElement EducationStartDate;
@FindBy(id = "education_end_date")
WebElement EducationEndDate;
@FindBy(id = "btnEducationSave")
WebElement BtnEducationSave;
//Hard coded xpath which contains text Bachelor's Degree: So pass accordingly
@FindBy(xpath = "//a[contains(text(), \"Bachelor's Degree\")]/parent::td//preceding-sibling::td//input[@class='chkbox']")
WebElement EducationCheckbox;
@FindBy(id = "delEducation")
WebElement BtnDelEducation;
@FindBy(id = "skill_code")
WebElement Skill;
@FindBy(id = "skill_years_of_exp")
WebElement YearsOfExperience;
@FindBy(id = "skill_comments")
WebElement SkillComments;
@FindBy(id = "btnSkillSave")
WebElement BtnSkillSave;
//Hard coded xpath which contains text Java: So pass accordingly
@FindBy(xpath = "//a[contains(text(), 'Java')]/parent::td//preceding-sibling::td//input[@class='chkbox']")
WebElement SkillsCheckbox;
@FindBy(id = "delSkill")
WebElement BtnDelSkill;
@FindBy(id = "language_code")
WebElement Language;
@FindBy(id = "language_lang_type")
WebElement LanguageType;
@FindBy(id = "language_competency")
WebElement LanguageCompetency;
@FindBy(id = "language_comments")
WebElement LanguageComments;
@FindBy(id = "btnLanguageSave")
WebElement BtnLanguageSave;
//Hard coded xpath which contains text English: So pass accordingly
@FindBy(xpath = "//a[contains(text(), 'English')]/parent::td//preceding-sibling::td//input[@class='chkbox']")
WebElement LanguageCheckbox;
@FindBy(id = "delLanguage")
WebElement BtnDelLanguage;
@FindBy(id = "license_code")
WebElement LicenseType;
@FindBy(id = "license_license_no")
WebElement LicenseNum;
@FindBy(id = "license_date")
WebElement LicenseIssueDate;
@FindBy(id = "license_renewal_date")
WebElement LicenseRenewalDate;
@FindBy(id = "btnLicenseSave")
WebElement BtnLicenseSave;
//Hard coded xpath which contains text PMI Agile Certified Practitioner (PMI-ACP): So pass accordingly
@FindBy(xpath = "//a[contains(text(), \"PMI Agile Certified Practitioner (PMI-ACP)\")]/parent::td//preceding-sibling::td//input[@class='chkbox']")
WebElement LicenseCheckbox;
@FindBy(id = "delLicense")
WebElement BtnDelLicense;
@FindBy(id = "btnAddAttachment")
WebElement BtnAddAttachment;
@FindBy(id = "ufile")
WebElement BtnUpload;
@FindBy(id = "btnSaveAttachment")
WebElement BtnSaveAttachment;
//Hard coded xpath which contains text jpg.jpg: So pass accordingly
@FindBy(xpath = "//a[contains(text(), \"jpg.jpg\")]/parent::td//preceding-sibling::td//input[@class='checkboxAtch']")
WebElement QualificationAttachCheckbox;
@FindBy(id = "btnDeleteAttachment")
WebElement BtnDeleteAttachment;
// Initializing Page Objects using constructor
public QualificationsPage(){
PageFactory.initElements(driver, this);
}
public void clickAddWorkExperienceBtn(){
TestUtil.doClick(BtnAddWorkExperience);
}
public void AddCompany(String company){
TestUtil.doSendKeys(Company, company);
}
public void AddJobTitle(String jobTitle) throws InterruptedException {
TestUtil.doSendKeys(JobTitle, jobTitle);
}
public void AddJobStartDate(String jobStartDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, JobStartDate, jobStartDate);
}
public void AddJobEndDate(String jobEndDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, JobEndDate, jobEndDate);
}
public void AddComments(String comments){
TestUtil.doSendKeys(Comments, comments);
}
public void clickSaveWorkExperienceBtn(){
TestUtil.doClick(BtnSaveWorkExperience);
}
public boolean isWorkExperienceAdded() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void deleteWorkExperience() {
TestUtil.doClick(WorkExpCheckbox);
TestUtil.doClick(BtndelWorkExperience);
}
public boolean isWorkExperienceDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void clickAddEducationBtn(){
TestUtil.doClick(BtnAddEducation);
}
public void selectEducationLevel(String valueEducationLevel) throws InterruptedException {
TestUtil.selectDropdownValue(EducationLevel, valueEducationLevel);
}
public void AddEducationInstitute(String valueEducationInstitute) throws InterruptedException {
TestUtil.doSendKeys(EducationInstitute, valueEducationInstitute);
}
public void AddEducationSpecialization(String valueEducationSpecialization) throws InterruptedException {
TestUtil.doSendKeys(EducationSpecialization, valueEducationSpecialization);
}
public void AddEducationYear(String valueEducationYear) throws InterruptedException {
TestUtil.doSendKeys(EducationYear, valueEducationYear);
}
public void AddEducationGPA(String valueEducationGPA) throws InterruptedException {
TestUtil.doSendKeys(EducationGPA, valueEducationGPA);
}
public void AddEducationStartDate(String valueEducationStartDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, EducationStartDate, valueEducationStartDate);
}
public void AddEducationEndDate(String valueEducationEndDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, EducationEndDate, valueEducationEndDate);
}
public void clickSaveEducationBtn(){
TestUtil.doClick(BtnEducationSave);
}
public boolean isEducationAdded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void DeleteEducation() {
TestUtil.doClick(EducationCheckbox);
TestUtil.doClick(BtnDelEducation);
}
public boolean IsEducationDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void clickAddSkillBtn(){
TestUtil.doClick(BtnAddSkill);
}
public void selectSkill(String valueSkill) throws InterruptedException {
TestUtil.selectDropdownValue(Skill, valueSkill);
}
public void AddYearsOfExperience(String valueYearsOfExperience) throws InterruptedException {
TestUtil.doSendKeys(YearsOfExperience, valueYearsOfExperience);
}
public void AddSkillComments(String valueSkillComments) throws InterruptedException {
TestUtil.doSendKeys(SkillComments, valueSkillComments);
}
public void clickBtnSkillSave(){
TestUtil.doClick(BtnSkillSave);
}
public boolean isSkillAdded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void DeleteSkills() {
TestUtil.doClick(SkillsCheckbox);
TestUtil.doClick(BtnDelSkill);
}
public boolean IsSkillsDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void clickAddLanguageBtn(){
TestUtil.doClick(BtnAddLanguage);
}
public void selectLanguage(String valueLanguage) throws InterruptedException {
TestUtil.selectDropdownValue(Language, valueLanguage);
}
public void selectLanguageType(String valueLanguageType) throws InterruptedException {
TestUtil.selectDropdownValue(LanguageType, valueLanguageType);
}
public void selectLanguageCompetency(String valueLanguageCompetency) throws InterruptedException {
TestUtil.selectDropdownValue(LanguageCompetency, valueLanguageCompetency);
}
public void AddLanguageComments(String valueLanguageComments) throws InterruptedException {
TestUtil.doSendKeys(LanguageComments, valueLanguageComments);
}
public void clickBtnLanguageSave(){
TestUtil.doClick(BtnLanguageSave);
}
public boolean isLanguageAdded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void DeleteLanguages() {
TestUtil.doClick(LanguageCheckbox);
TestUtil.doClick(BtnDelLanguage);
}
public boolean IsLanguagesDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void ClickBtnAddLicense(){
TestUtil.doClick(BtnAddLicense);
}
public void AddLicenseType(String valueLicenseType) throws InterruptedException {
TestUtil.selectDropdownValue(LicenseType, valueLicenseType);
}
public void AddLicenseNumber(String valueLicenseNumber){
TestUtil.doSendKeys(LicenseNum, valueLicenseNumber);
}
public void AddLicenseIssueDate(String valueLicenseIssueDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, LicenseIssueDate, valueLicenseIssueDate);
}
public void AddLicenseRenewalDate(String valueLicenseRenewalDate) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, LicenseRenewalDate, valueLicenseRenewalDate);
}
public void ClickBtnLicenseSave(){
TestUtil.doClick(BtnLicenseSave);
}
public boolean IsLicenseAdded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void DeleteLicense() {
TestUtil.doClick(LicenseCheckbox);
TestUtil.doClick(BtnDelLicense);
}
public boolean IsLicenseDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void uploadQualificationAttach(){
TestUtil.uploadAttachment(BtnAddAttachment, BtnUpload, BtnSaveAttachment, prop.getProperty("pathToQualificationAttachment"));
}
public boolean isQualificationAttachUploaded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void DeleteQualificationAttachment() {
TestUtil.doClick(QualificationAttachCheckbox);
TestUtil.doClick(BtnDeleteAttachment);
}
public boolean IsQualificationAttachmentDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
}
<file_sep>/src/main/java/com/orangehrm/qa/pages/DependentsPage.java
package com.orangehrm.qa.pages;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.utils.TestUtil;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class DependentsPage extends TestBase {
// Object Repo
@FindBy(id = "btnAddDependent")
WebElement BtnAddDependent;
@FindBy(id = "btnSaveDependent")
WebElement BtnSaveDependent;
@FindBy(id = "dependent_name")
WebElement DependentName;
@FindBy(id = "dependent_relationshipType")
WebElement DependentRelationshipType;
@FindBy(id = "dependent_dateOfBirth")
WebElement DependentDateOfBirth;
// Note: This div becomes visible if you select other in DependentRelationshipType.
@FindBy(id = "dependent_relationship")
WebElement DependentRelationship;
@FindBy(className = "message")
WebElement CheckStatusDiv;
//Hard coded xpath which contains text fd: So pass accordingly
@FindBy(xpath = "//a[contains(text(), '<NAME>')]/parent::td//preceding-sibling::td//input[@class='checkbox']")
WebElement Checkbox;
@FindBy(id = "delDependentBtn")
WebElement DelDependentBtn;
// Initializing Page Objects using constructor
public DependentsPage(){
PageFactory.initElements(driver, this);
}
public void clickOnAddDependentBtn(){
TestUtil.doClick(BtnAddDependent);
}
public void AddDependentName(String dependentName){
TestUtil.doSendKeys(DependentName, dependentName);
}
public void AddDependentRelationshipType(String dependentRelationshipType, String dependentRelationship) throws InterruptedException {
TestUtil.selectDropdownValue(DependentRelationshipType, dependentRelationshipType);
TestUtil.doSendKeys(DependentRelationship, dependentRelationship);
}
public void AddDependentDateOfBirth(String dependentDateOfBirth) throws InterruptedException {
TestUtil.SelectDateFromCalenderCustom(driver, DependentDateOfBirth, dependentDateOfBirth);
}
public void clickOnSaveDependentBtn(){
TestUtil.doClick(BtnSaveDependent);
}
public boolean isDependentsAdded(){
System.out.println(CheckStatusDiv.getText());
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
public void deleteDependents() {
TestUtil.doClick(Checkbox);
TestUtil.doClick(DelDependentBtn);
}
public boolean isDependentsDeleted() {
Boolean flag = TestUtil.checkStatus(CheckStatusDiv);
return flag;
}
}
<file_sep>/src/test/java/com/orangehrm/qa/testcases/MembershipsPageTest.java
package com.orangehrm.qa.testcases;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.pages.DashboardPage;
import com.orangehrm.qa.pages.LoginPage;
import com.orangehrm.qa.pages.MembershipsPage;
import com.orangehrm.qa.pages.PersonalDetailsPage;
import org.openqa.selenium.JavascriptExecutor;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class MembershipsPageTest extends TestBase {
PersonalDetailsPage personalDetailsPage;
DashboardPage dashboardPage;
LoginPage loginPage;
MembershipsPage membershipsPage;
public MembershipsPageTest(){
super();
}
@BeforeMethod
public void setUp(){
initialization();
loginPage = new LoginPage();
dashboardPage = new DashboardPage();
personalDetailsPage = new PersonalDetailsPage();
membershipsPage = new MembershipsPage();
dashboardPage = loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
personalDetailsPage = dashboardPage.clickOnPersonalDetailsPageLink();
JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
membershipsPage = personalDetailsPage.clickOnMembershipsPageLink();
}
@Test(priority = 1)
public void verifyAddMembershipDetails() throws InterruptedException {
membershipsPage.ClickBtnAddMembershipDetail();
membershipsPage.AddMembership(prop.getProperty("valueMembership"));
membershipsPage.AddSubscriptionPaidBy(prop.getProperty("valueSubscriptionPaidBy"));
membershipsPage.AddSubscriptionAmount(prop.getProperty("valueSubscriptionAmount"));
membershipsPage.AddMembershipCurrency(prop.getProperty("valueMembershipCurrency"));
membershipsPage.AddSubscriptionCommenceDate(prop.getProperty("valueSubscriptionCommenceDate"));
membershipsPage.AddSubscriptionRenewalDate(prop.getProperty("valueSubscriptionRenewalDate"));
membershipsPage.ClickOnBtnSaveMembership();
boolean flag = membershipsPage.IsMembershipsAdded();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 2)
public void verifyDeleteMembershipDetails() throws InterruptedException {
membershipsPage.DeleteMembershipDetails();
Boolean flag = membershipsPage.IsMembershipDetailsDeleted();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 3)
public void verifyUploadMembershipAttach(){
membershipsPage.uploadMembershipAttach();
Boolean flag = membershipsPage.IsMembershipAttachUploaded();
Assert.assertTrue(flag);
}
@AfterMethod
public void tearDown(){
driver.quit();
}
}
<file_sep>/src/test/java/com/orangehrm/qa/testcases/QualificationsPageTest.java
package com.orangehrm.qa.testcases;
import com.orangehrm.qa.base.TestBase;
import com.orangehrm.qa.pages.DashboardPage;
import com.orangehrm.qa.pages.LoginPage;
import com.orangehrm.qa.pages.PersonalDetailsPage;
import com.orangehrm.qa.pages.QualificationsPage;
import org.openqa.selenium.JavascriptExecutor;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class QualificationsPageTest extends TestBase {
PersonalDetailsPage personalDetailsPage;
DashboardPage dashboardPage;
LoginPage loginPage;
QualificationsPage qualificationsPage;
public QualificationsPageTest(){
super();
}
@BeforeMethod
public void setUp(){
initialization();
loginPage = new LoginPage();
dashboardPage = new DashboardPage();
personalDetailsPage = new PersonalDetailsPage();
qualificationsPage = new QualificationsPage();
dashboardPage = loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
personalDetailsPage = dashboardPage.clickOnPersonalDetailsPageLink();
JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
qualificationsPage = personalDetailsPage.clickOnQualificationsPageLink();
}
@Test(priority = 1)
public void verifyAddWorkExperience() throws InterruptedException {
qualificationsPage.clickAddWorkExperienceBtn();
qualificationsPage.AddCompany(prop.getProperty("company"));
qualificationsPage.AddJobTitle(prop.getProperty("jobTitle"));
qualificationsPage.AddJobStartDate(prop.getProperty("jobStartDate"));
qualificationsPage.AddJobEndDate(prop.getProperty("JobEndDate"));
qualificationsPage.AddComments(prop.getProperty("workExpComments"));
qualificationsPage.clickSaveWorkExperienceBtn();
Boolean flag = qualificationsPage.isWorkExperienceAdded();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 2)
public void verifyDeleteWorkExperience() throws InterruptedException {
qualificationsPage.deleteWorkExperience();
Boolean flag = qualificationsPage.isWorkExperienceDeleted();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 3)
public void verifyAddEducation() throws InterruptedException {
qualificationsPage.clickAddEducationBtn();
qualificationsPage.selectEducationLevel(prop.getProperty("valueEducationLevel"));
qualificationsPage.AddEducationInstitute(prop.getProperty("valueEducationInstitute"));
qualificationsPage.AddEducationSpecialization(prop.getProperty("valueEducationSpecialization"));
qualificationsPage.AddEducationYear(prop.getProperty("valueEducationYear"));
qualificationsPage.AddEducationGPA(prop.getProperty("valueEducationGPA"));
qualificationsPage.AddEducationStartDate(prop.getProperty("valueEducationStartDate"));
qualificationsPage.AddEducationEndDate(prop.getProperty("valueEducationEndDate"));
qualificationsPage.clickSaveEducationBtn();
Boolean flag = qualificationsPage.isEducationAdded();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 4)
public void verifyDeleteEducation() throws InterruptedException {
qualificationsPage.DeleteEducation();
Boolean flag = qualificationsPage.IsEducationDeleted();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 5)
public void verifyAddSkills() throws InterruptedException {
qualificationsPage.clickAddSkillBtn();
qualificationsPage.selectSkill(prop.getProperty("valueSkill"));
qualificationsPage.AddYearsOfExperience(prop.getProperty("valueYearsOfExperience"));
qualificationsPage.AddSkillComments(prop.getProperty("valueSkillComments"));
qualificationsPage.clickBtnSkillSave();
Boolean flag = qualificationsPage.isSkillAdded();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 6)
public void verifyDeleteSkills() throws InterruptedException {
qualificationsPage.DeleteSkills();
Boolean flag = qualificationsPage.IsSkillsDeleted();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 7)
public void verifyAddLanguages() throws InterruptedException {
qualificationsPage.clickAddLanguageBtn();
qualificationsPage.selectLanguage(prop.getProperty("valueLanguage"));
qualificationsPage.selectLanguageType(prop.getProperty("valueLanguageType"));
qualificationsPage.selectLanguageCompetency(prop.getProperty("valueLanguageCompetency"));
qualificationsPage.AddLanguageComments(prop.getProperty("valueLanguageComments"));
qualificationsPage.clickBtnLanguageSave();
Boolean flag = qualificationsPage.isLanguageAdded();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 8)
public void verifyDeleteLanguages() throws InterruptedException {
qualificationsPage.DeleteLanguages();
Boolean flag = qualificationsPage.IsLanguagesDeleted();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 9)
public void verifyAddLicense() throws InterruptedException {
qualificationsPage.ClickBtnAddLicense();
qualificationsPage.AddLicenseType(prop.getProperty("valueLicenseType"));
qualificationsPage.AddLicenseNumber(prop.getProperty("valueLicenseNumber"));
qualificationsPage.AddLicenseIssueDate(prop.getProperty("valueLicenseIssueDate"));
qualificationsPage.AddLicenseRenewalDate(prop.getProperty("valueLicenseRenewalDate"));
qualificationsPage.ClickBtnLicenseSave();
Boolean flag = qualificationsPage.IsLicenseAdded();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 10)
public void verifyDeleteLicense() throws InterruptedException {
qualificationsPage.DeleteLicense();
Boolean flag = qualificationsPage.IsLicenseDeleted();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@Test(priority = 11)
public void verifyUploadQualificationAttach(){
qualificationsPage.uploadQualificationAttach();
Boolean flag = qualificationsPage.isQualificationAttachUploaded();
Assert.assertTrue(flag);
}
@Test(priority = 12)
public void verifyDeleteQualificationAttachment() throws InterruptedException {
qualificationsPage.DeleteQualificationAttachment();
Boolean flag = qualificationsPage.IsQualificationAttachmentDeleted();
Assert.assertTrue(flag);
Thread.sleep(3000);
}
@AfterMethod
public void tearDown(){
driver.quit();
}
}
<file_sep>/src/main/java/com/orangehrm/qa/pages/LoginPage.java
package com.orangehrm.qa.pages;
import com.orangehrm.qa.base.TestBase;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage extends TestBase {
// Page Library / Object Repo
@FindBy(name="txtUsername")
WebElement username;
@FindBy(name = "txtPassword")
WebElement password;
@FindBy(id= "logInPanelHeading")
WebElement loginPanel;
@FindBy(id="btnLogin")
WebElement loginBtn;
// Initializing Page Objects using constructor
public LoginPage(){
PageFactory.initElements(driver, this);
}
// Page Actions
public String validateLoginPageTitle(){
return driver.getTitle();
}
public boolean validateLoginPanel(){
return loginPanel.isDisplayed();
}
public DashboardPage login(String uname, String pwd){
username.sendKeys(uname);
password.sendKeys(pwd);
loginBtn.click();
return new DashboardPage();
}
}
<file_sep>/src/main/java/com/orangehrm/qa/utils/TestUtil.java
package com.orangehrm.qa.utils;
import com.orangehrm.qa.base.TestBase;
import org.apache.commons.compress.archivers.dump.InvalidFormatException;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestUtil extends TestBase {
static Workbook book;
static Sheet sheet;
public static String TESTDATA_SHEET_PATH = "C:\\Projects\\OrangeHRM-MyInfo-E2ETest\\src\\main\\java\\com\\orangehrm\\qa\\testdata\\credentials.xlsx";
public static void doSendKeys(WebElement locator, String text){
locator.clear();
locator.sendKeys(text);
}
public static void doClick(WebElement locator){
locator.click();
}
public static void uploadAttachment(WebElement btnAdd, WebElement btnUpload, WebElement btnSave, String attachmentPath){
btnAdd.click();
btnUpload.sendKeys(attachmentPath);
btnSave.click();
}
public static void selectDropdownValue( WebElement locator, String value) throws InterruptedException {
Select dropdown_option = new Select(locator);
dropdown_option.selectByValue(value);
Thread.sleep(1000);
}
public static boolean checkStatus(WebElement locator){
System.out.println(locator.getText());
Boolean flag = locator.isDisplayed();
return flag;
}
public static void SelectDateFromCalenderCustom(WebDriver driver, WebElement locator, String dateVal) throws InterruptedException {
String dateArr[] = dateVal.split("-"); //{30, September, 2021}
String year = dateArr[0];
String month = dateArr[1];
String day = dateArr[2];
//WebElement input = driver.findElement(By.id("personal_txtLicExpDate"));
locator.click();
Select select1 = new Select(driver.findElement(By.className("ui-datepicker-month")));
select1.selectByVisibleText(month);
Thread.sleep(2000);
Select select2 = new Select(driver.findElement(By.className("ui-datepicker-year")));
select2.selectByVisibleText(year);
Thread.sleep(2000);
/*
/html/body/div[3]/table/tbody/tr[1]/td[3]
/html/body/div[3]/table/tbody/tr[1]/td[4]
/html/body/div[3]/table/tbody/tr[1]/td[5]
/html/body/div[3]/table/tbody/tr[1]/td[6]
/html/body/div[3]/table/tbody/tr[1]/td[7]
*/
String beforeXpath = "/html/body/div[3]/table/tbody/tr[";
String afterXpath = "]/td[";
final int totalWeekDays = 7;
boolean flag = false;
String dayVal = null;
for (int rowNum = 1; rowNum <= 5 ; rowNum++) {
for (int colNum = 1; colNum <= totalWeekDays; colNum++) {
try {
dayVal = driver.findElement(By.xpath(beforeXpath + rowNum + afterXpath + colNum + "]")).getText();
} catch (NoSuchElementException e) {
System.out.println("Please enter a correct value");
flag = false;
break;
}
System.out.println(dayVal);
if (dayVal.equals(day)) {
WebElement ele = driver.findElement(By.xpath(beforeXpath + rowNum + afterXpath + colNum + "]"));
ele.click();
Thread.sleep(500);
flag = true;
break;
}
}
if (flag) {
break;
}
}
}
// Method to take screenshot if an exception occurs under screenshots folder and gets called from WebEventListener class
public static void takeScreenshotOnException() throws IOException {
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String currentDir = System.getProperty("user.dir");
FileUtils.copyFile(srcFile, new File(currentDir + "/screenshots/" + System.currentTimeMillis() + ".png"));
}
public static Object[][] getTestData(String sheetName){
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
}
catch (FileNotFoundException e){
e.printStackTrace();
}
try {
//XSSFWorkbook book = new XSSFWorkbook(file);
//book = WorkbookFactory.create(file);
book = new XSSFWorkbook(file);
}
catch (InvalidFormatException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
sheet = book.getSheet(sheetName);
Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
//System.out.println(sheet.getLastRowNum() + "-------" + sheet.getRow(0).getLastCellNum());
for (int i=0; i < sheet.getLastRowNum(); i++){
for (int k=0; k < sheet.getRow(0).getLastCellNum(); k++){
data[i][k] = sheet.getRow(i + 1).getCell(k).toString();
//System.out.println(data[i][k]);
}
}
return data;
}
}
<file_sep>/src/main/java/com/orangehrm/qa/config/config.properties
browser = chrome
url = https://opensource-demo.orangehrmlive.com
username = Admin
password = <PASSWORD>
firstName = George
middleName = Kumar
lastName = Clooney
licenseExpiryDate = 2018-Dec-5
maritalStatus = Married
pathToEmployeePic = C:\\Projects\\OrangeHRM-MyInfo-E2ETest\\src\\main\\resources\\Attachments\\jepg.jpeg
street1 = Gathaghar Chowk
street2 = CVM Road
city = Bhaktapur
province = Bagmati
postalcode = 44600
country = Nepal
hometelephone = 011234567
employeemobileno = 9825412121
employeeworktelephoneno = 017654321
employeeworkemail = <EMAIL>
employeeotheremail = <EMAIL>
emgContactsName = <NAME>
emgContactsRelationship = Mentor
emgContactsHomePhone = 011234567
emgContactsMobilePhone = 9825412345
emgContactsWorkPhone = 017654321
dependentName = <NAME>
dependentRelationshipType = other
dependentDateOfBirth = 1985-Dec-5
dependentRelationship = Partner
immigrationNumber = 123456789
passportIssueDate = 2015-Jan-25
passportExpireDate = 2025-Jan-24
immigrationStatus = Progress
issuedBy = NP
reviewDate = 2025-Jan-24
comments = Bhutanese Refugee
pathToImmigrantRecordAttachment = C:\\Projects\\OrangeHRM-MyInfo-E2ETest\\src\\main\\resources\\Attachments\\png.png
company = shi:dolutions
jobTitle = QE Engineer
jobStartDate = 2018-Apr-15
JobEndDate = 2021-Mar-30
workExpComments = Nice Learning Exp
valueEducationLevel = 2
valueEducationInstitute = KU
valueEducationSpecialization = Computer Engineering
valueEducationYear = 2014 - 2018
valueEducationGPA = 3.9
valueEducationStartDate = 2018-Apr-15
valueEducationEndDate = 2021-Mar-30
valueSkill = 7
valueYearsOfExperience = 6
valueSkillComments = Excellent Skills
valueLanguage = 3
valueLanguageType = 2
valueLanguageCompetency = 3
valueLanguageComments = Excellent Language SKills
valueLicenseType = 6
valueLicenseNumber = 1234567890
valueLicenseIssueDate = 2014-Apr-13
valueLicenseRenewalDate = 2024-Mar-26
pathToQualificationAttachment = src\\main\\resources\\Attachments\\jpg.jpg
valueMembership = 1
valueSubscriptionPaidBy = Individual
valueSubscriptionAmount = 750
valueMembershipCurrency = AED
valueSubscriptionCommenceDate = 2020-Nov-29
valueSubscriptionRenewalDate = 2021-Oct-29
pathToMembershipAttachment = C:\\Projects\\OrangeHRM-MyInfo-E2ETest\\src\\main\\resources\\Attachments\\jpg.jpg
|
752840861a58722b9b6dbc2f88deb70d70c9242a
|
[
"Java",
"INI"
] | 14 |
Java
|
maheshkafle/OrangeHRM-MyInfo-E2ETest
|
8a8f82f130c32c015e024e97fbac3cf5a624b374
|
2576ecf78a837cf00d2712e997744c32f18d049f
|
refs/heads/master
|
<repo_name>fzilic/gd32v-basics<file_sep>/src/main.cpp
#include "Configuration.h"
#ifdef BOOT_COUNTER_DEMO
#include "GPIO_pins.hpp"
#include "GPIO.hpp"
#endif // BOOT_COUNTER_DEMO
#ifdef LED_DEMO
#include "LED.hpp"
#endif //LED_DEMO
#ifdef LCD_BUILTIN_DEMO
#include "LCDBuiltin.hpp"
#endif //LCD_BUILTIN_DEMO
#if defined(BOOT_COUNTER_DEMO) || defined(LED_DEMO) || defined(LCD_BUILTIN_DEMO)
#include "Timer.hpp"
#include <stdio.h>
uint64_t micros, deltaMicros;
uint64_t lcdMillis, lcdDeltaMillis;
uint64_t ledMillis, ledDeltaMillis;
char dispBuffer[15];
#endif // ANY
#ifdef BOOT_COUNTER_DEMO
volatile uint8_t cnt = 0;
volatile uint64_t lastBootDebounce;
#endif // BOOT_COUNTER_DEMO
#ifdef LED_DEMO
LED::LEDColor ledColor;
LED::LED led;
#endif
#ifdef LCD_BUILTIN_DEMO
LCDBuiltin::LCDBuiltin lcd(LCDBuiltin::BLACK, LCDBuiltin::HORIZONTAL_FLIPPED);
#endif
#ifdef BOOT_COUNTER_DEMO
GPIO::GPIO boot = GPIO::GPIO(PA8, GPIO::MODE_IPU);
void key_exti_init(void);
extern "C" void EXTI5_9_IRQHandler(void);
#endif
int main(void)
{
// initialize devices
#ifdef LED_DEMO
led.init();
#endif
#ifdef LCD_BUILTIN_DEMO
lcd.init();
#endif
#ifdef BOOT_COUNTER_DEMO
boot.init();
key_exti_init();
#endif
#ifdef LED_DEMO
led.set(LED::RED);
#endif
#ifdef LCD_BUILTIN_DEMO
lcd.clear();
lcd.writeString(24, 0, (char *)"Booting...", LCDBuiltin::YELLOW);
#endif
#if defined(LCD_BUILTIN_DEMO) || defined(LED_DEMO)
Timer::delay(500);
#endif
#ifdef LED_DEMO
led.set(LED::GREEN);
#endif
#if defined(LCD_BUILTIN_DEMO) || defined(LED_DEMO)
Timer::delay(500);
#endif
#ifdef LCD_BUILTIN_DEMO
lcd.writeString(24, 0, (char *)"Running...", LCDBuiltin::GREEN);
#endif
#ifdef LED_DEMO
ledColor = LED::BLACK;
#endif
// test delay / millis
#if defined(BOOT_COUNTER_DEMO) || defined(LED_DEMO) || defined(LCD_BUILTIN_DEMO)
micros = Timer::micros();
// update intervals
lcdMillis = Timer::millis();
ledMillis = Timer::millis();
#endif
while (1)
{
#if defined(BOOT_COUNTER_DEMO) || defined(LED_DEMO) || defined(LCD_BUILTIN_DEMO)
deltaMicros = Timer::micros() - micros;
lcdDeltaMillis = Timer::millis() - lcdMillis;
ledDeltaMillis = Timer::millis() - ledMillis;
// lcd every 50ms
if (lcdDeltaMillis >= 50)
{
micros = Timer::micros();
lcdMillis = Timer::millis();
#ifdef LCD_BUILTIN_DEMO
#ifdef BOOT_COUNTER_DEMO
sprintf(dispBuffer, "Cnt: %03d", cnt);
lcd.writeString(24, 16, dispBuffer, LCDBuiltin::YELLOW);
#endif // BOOT_COUNTER_DEMO
sprintf(dispBuffer, "us: %07lu", deltaMicros);
lcd.writeString(24, 32, dispBuffer, LCDBuiltin::DARKBLUE);
sprintf(dispBuffer, "ms: %07lu", lcdDeltaMillis);
lcd.writeString(24, 48, dispBuffer, LCDBuiltin::BLUE);
sprintf(dispBuffer, "xxxxxxxxxxxxxx");
lcd.writeString(24, 64, dispBuffer, LCDBuiltin::MAGENTA);
#endif // LCD_BUILTIN_DEMO
}
#ifdef LED_DEMO
if (ledDeltaMillis >= 500)
{
ledMillis = Timer::millis();
// toggle LED
if (ledColor == LED::BLACK)
ledColor = LED::MAGENTA;
else
ledColor = LED::BLACK;
led.set(ledColor);
}
#endif // LED_DEMO
#endif
}
}
#ifdef BOOT_COUNTER_DEMO
void key_exti_init(void)
{
/* enable the AF clock */
rcu_periph_clock_enable(RCU_AF);
/* enable and set key EXTI interrupt to the specified priority */
eclic_global_interrupt_enable();
eclic_priority_group_set(ECLIC_PRIGROUP_LEVEL3_PRIO1);
eclic_irq_enable(EXTI5_9_IRQn, 1, 1);
/* connect key EXTI line to key GPIO pin */
gpio_exti_source_select(GPIO_PORT_SOURCE_GPIOA, GPIO_PIN_SOURCE_8);
/* configure key EXTI line */
exti_init(EXTI_8, EXTI_INTERRUPT, EXTI_TRIG_FALLING);
exti_interrupt_flag_clear(EXTI_8);
}
extern "C" void EXTI5_9_IRQHandler(void)
{
if (RESET != exti_interrupt_flag_get(EXTI_8))
{
if (!boot.read() && (Timer::millis() - lastBootDebounce) > 40)
{
cnt++;
}
lastBootDebounce = Timer::millis();
exti_interrupt_flag_clear(EXTI_8);
}
}
#endif // BOOT_COUNTER_DEMO<file_sep>/lib/LCDBuiltin/LCDBuiltin.hpp
#ifndef __OLED_BUILTIN_H
#define __OLED_BUILTIN_H
#include "SPI.hpp"
#include "GPIO.hpp"
#include "GPIO_pins.hpp"
namespace LCDBuiltin
{
enum LCDBuiltinOrientation
{
VERTICAL,
VERTICAL_FLIPPED,
HORIZONTAL,
HORIZONTAL_FLIPPED
};
enum LCDBuiltinMode : uint8_t
{
NON_OVERLAPPING = 0,
OVERLAPPING = 1
};
enum LCDBuiltinColor : uint16_t
{
WHITE = 0xFFFF,
BLACK = 0x0000,
BLUE = 0x001F,
BRED = 0XF81F,
GRED = 0XFFE0,
GBLUE = 0X07FF,
RED = 0xF800,
MAGENTA = 0xF81F,
GREEN = 0x07E0,
CYAN = 0x7FFF,
YELLOW = 0xFFE0,
BROWN = 0XBC40,
BRRED = 0XFC07,
GRAY = 0X8430,
DARKBLUE = 0X01CF,
LIGHTBLUE = 0X7D7C,
GRAYBLUE = 0X5458,
LIGHTGREEN = 0X841F,
LGRAY = 0XC618,
LGRAYBLUE = 0XA651,
LBBLUE = 0X2B12
};
class LCDBuiltin
{
private:
SPI::SPI _spi;
GPIO::GPIO _rst;
GPIO::GPIO _cs;
GPIO::GPIO _dc;
LCDBuiltinOrientation _orientation;
LCDBuiltinColor _backColor;
uint16_t _dispHeight;
uint16_t _dispWidth;
void writeCommandRaw(uint8_t data);
void write(uint8_t data);
void writeChar(uint16_t x, uint16_t y, uint8_t value, LCDBuiltinColor color, LCDBuiltinMode mode = NON_OVERLAPPING);
public:
public:
LCDBuiltin()
: LCDBuiltin(WHITE, HORIZONTAL) {}
LCDBuiltin(LCDBuiltinColor backColor,
LCDBuiltinOrientation orientation)
: LCDBuiltin(backColor,
orientation,
SPI::SPIPrescale::PSC_2) {}
LCDBuiltin(LCDBuiltinColor backColor,
LCDBuiltinOrientation orientation,
SPI::SPIPrescale prescale)
: _spi(
SPI::SPI(
SPI::SPIPort(SPI0, RCU_GPIOA, RCU_SPI0, GPIOA, GPIO_PIN_5 | GPIO_PIN_7, GPIO_PIN_6),
SPI::SPISettings(SPI::SPIEndianess::MSB, SPI::SPIMode::MODE3, prescale))),
_rst(GPIO::GPIO(PB1, GPIO::MODE_OUT_PP)),
_cs(GPIO::GPIO(PB2, GPIO::MODE_OUT_PP)),
_dc(GPIO::GPIO(PB0, GPIO::MODE_OUT_PP)),
_orientation(orientation),
_backColor(backColor),
_dispHeight(orientation == VERTICAL || orientation == VERTICAL_FLIPPED ? 160 : 80),
_dispWidth(orientation == VERTICAL || orientation == VERTICAL_FLIPPED ? 80 : 160) {}
void init();
void writeData8(uint8_t data);
void writeData16(uint16_t data);
void clear();
void clear(LCDBuiltinColor color);
void writeString(uint16_t x, uint16_t y, const char *data, LCDBuiltinColor color);
void setAddress(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2);
};
}; // namespace LCDBuiltin
#endif<file_sep>/lib/ST7920/ST7920.cpp
#include "ST7920.hpp"
#include "Timer.hpp"
void ST7920::init()
{
// initialize devices
_spi.init();
_cs.init();
// initialize display
_cs.clear();
send(LCD_BASIC);
send(LCD_BASIC);
send(LCD_CLS);
Timer::delay(5);
send(LCD_ADDRINC);
send(LCD_DISPLAYON);
}
void ST7920::send(uint8_t prefix, uint8_t data)
{
_spi.begin();
_cs.set();
_spi.transfer(prefix);
_spi.transfer(data & 0xF0);
_spi.transfer(data << 4);
_cs.clear();
_spi.end();
}
void ST7920::send(ST7920Command command)
{
send(0xF8, command);
}
void ST7920::send(uint8_t data)
{
send(0xFA, data);
}
void ST7920::writeText(uint8_t position, char *str)
{
send(LCD_BASIC);
send(position);
while (*str != '\0')
send(*str++);
}<file_sep>/lib/Timer/Timer.cpp
#ifndef __TIMER_H
#define __TIMER_H
#include "Timer.hpp"
extern "C"
{
#include "gd32vf103.h"
}
void Timer::delay(uint32_t count)
{
uint64_t start_mtime, delta_mtime;
// Don't start measuruing until we see an mtime tick
uint64_t tmp = get_timer_value();
do
{
start_mtime = get_timer_value();
} while (start_mtime == tmp);
do
{
delta_mtime = get_timer_value() - start_mtime;
} while (delta_mtime < (SystemCoreClock / 4000.0 * count));
}
void Timer::delayMicroseconds(uint32_t count)
{
uint64_t start_mtime, delta_mtime;
// Don't start measuruing until we see an mtime tick
uint64_t tmp = get_timer_value();
do
{
start_mtime = get_timer_value();
} while (start_mtime == tmp);
do
{
delta_mtime = get_timer_value() - start_mtime;
} while (delta_mtime < (SystemCoreClock / 4000000.0 * count));
}
uint64_t Timer::millis()
{
return get_timer_value() * 4000 / SystemCoreClock;
}
uint64_t Timer::micros()
{
return get_timer_value() * 4000000 / SystemCoreClock;
}
#endif<file_sep>/lib/LCDBuiltin/LCDBuiltin.cpp
#include "LCDBuiltin.hpp"
#include "LCDBuiltin_font.hpp"
#include "Timer.hpp"
namespace LCDBuiltin
{
void LCDBuiltin::init()
{
// initialize devices
_spi.init();
_rst.init();
_cs.init();
_dc.init();
// initialize display
_spi.begin();
_rst.clear();
Timer::delay(200);
_rst.set();
Timer::delay(20);
// optional BLK?
writeCommandRaw(0x11); // turn off sleep mode
Timer::delay(100);
writeCommandRaw(0x21); // display inversion mode
writeCommandRaw(0xB1); // Set the frame frequency of the full colors normal mode
// Frame rate=fosc/((RTNA x 2 + 40) x (LINE + FPA + BPA +2))
// fosc = 850kHz
writeData8(0x05); // RTNA
writeData8(0x3A); // FPA
writeData8(0x3A); // BPA
writeCommandRaw(0xB2); // Set the frame frequency of the Idle mode
// Frame rate=fosc/((RTNB x 2 + 40) x (LINE + FPB + BPB +2))
// fosc = 850kHz
writeData8(0x05); // RTNB
writeData8(0x3A); // FPB
writeData8(0x3A); // BPB
writeCommandRaw(0xB3); // Set the frame frequency of the Partial mode/ full colors
writeData8(0x05);
writeData8(0x3A);
writeData8(0x3A);
writeData8(0x05);
writeData8(0x3A);
writeData8(0x3A);
writeCommandRaw(0xB4);
writeData8(0x03);
writeCommandRaw(0xC0);
writeData8(0x62);
writeData8(0x02);
writeData8(0x04);
writeCommandRaw(0xC1);
writeData8(0xC0);
writeCommandRaw(0xC2);
writeData8(0x0D);
writeData8(0x00);
writeCommandRaw(0xC3);
writeData8(0x8D);
writeData8(0x6A);
writeCommandRaw(0xC4);
writeData8(0x8D);
writeData8(0xEE);
writeCommandRaw(0xC5); /*VCOM*/
writeData8(0x0E);
writeCommandRaw(0xE0);
writeData8(0x10);
writeData8(0x0E);
writeData8(0x02);
writeData8(0x03);
writeData8(0x0E);
writeData8(0x07);
writeData8(0x02);
writeData8(0x07);
writeData8(0x0A);
writeData8(0x12);
writeData8(0x27);
writeData8(0x37);
writeData8(0x00);
writeData8(0x0D);
writeData8(0x0E);
writeData8(0x10);
writeCommandRaw(0xE1);
writeData8(0x10);
writeData8(0x0E);
writeData8(0x03);
writeData8(0x03);
writeData8(0x0F);
writeData8(0x06);
writeData8(0x02);
writeData8(0x08);
writeData8(0x0A);
writeData8(0x13);
writeData8(0x26);
writeData8(0x36);
writeData8(0x00);
writeData8(0x0D);
writeData8(0x0E);
writeData8(0x10);
writeCommandRaw(0x3A); // define the format of RGB picture data
writeData8(0x05); // 16-bit/pixel
writeCommandRaw(0x36);
// Orientation
switch (_orientation)
{
case VERTICAL:
writeData8(0x08);
break;
case VERTICAL_FLIPPED:
writeData8(0xC8);
break;
case HORIZONTAL:
writeData8(0x78);
break;
default:
writeData8(0xA8);
break;
}
writeCommandRaw(0x29); // Display On
}
void LCDBuiltin::writeCommandRaw(uint8_t data)
{
_dc.clear();
write(data);
}
void LCDBuiltin::write(uint8_t data)
{
_cs.clear();
_spi.transfer(data);
_cs.set();
}
void LCDBuiltin::writeData8(uint8_t data)
{
_dc.set();
write(data);
}
void LCDBuiltin::writeData16(uint16_t data)
{
_dc.set();
write(data >> 8);
write(data);
}
void LCDBuiltin::clear()
{
clear(_backColor);
}
void LCDBuiltin::clear(LCDBuiltinColor color)
{
uint16_t i, j;
setAddress(0, 0, _dispWidth - 1, _dispHeight - 1);
for (i = 0; i < _dispWidth; i++)
{
for (j = 0; j < _dispHeight; j++)
{
writeData16(color);
}
}
}
void LCDBuiltin::writeString(uint16_t x, uint16_t y, const char *data, LCDBuiltinColor color)
{
while (*data != '\0')
{
if (x > _dispWidth - 16)
{
x = 0;
y += 16;
}
if (y > _dispHeight - 16)
{
y = x = 0;
clear(RED);
}
writeChar(x, y, *data, color);
x += 8;
data++;
}
}
void LCDBuiltin::writeChar(uint16_t x, uint16_t y, uint8_t value, LCDBuiltinColor color, LCDBuiltinMode mode)
{
uint8_t temp;
uint8_t pos, t;
uint16_t x0 = x;
if (x > _dispWidth - 16 || y > _dispHeight - 16)
return; //Settings window
value = value - ' '; //Get offset value
setAddress(x, y, x + 8 - 1, y + 16 - 1); //Set cursor position
if (!mode) //Non-overlapping
{
for (pos = 0; pos < 16; pos++)
{
temp = asc2_1608[(uint16_t)value * 16 + pos]; //Call 1608 font
for (t = 0; t < 8; t++)
{
if (temp & 0x01)
writeData16(color);
else
writeData16(_backColor);
temp >>= 1;
x++;
}
x = x0;
y++;
}
}
else //overlapping mode
{
for (pos = 0; pos < 16; pos++)
{
temp = asc2_1608[(uint16_t)value * 16 + pos]; //Call 1608 font
for (t = 0; t < 8; t++)
{
if (temp & 0x01)
// LCD_DrawPoint(x + t, y + pos, color); //Draw a dot
temp >>= 1;
}
}
}
}
void LCDBuiltin::setAddress(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2)
{
switch (_orientation)
{
case VERTICAL:
writeCommandRaw(0x2a); //Column address settings
writeData16(x1 + 26);
writeData16(x2 + 26);
writeCommandRaw(0x2b); //Row address setting
writeData16(y1 + 1);
writeData16(y2 + 1);
writeCommandRaw(0x2c); //Memory write
break;
case VERTICAL_FLIPPED:
writeCommandRaw(0x2a); //Column address settings
writeData16(x1 + 26);
writeData16(x2 + 26);
writeCommandRaw(0x2b); //Row address setting
writeData16(y1 + 1);
writeData16(y2 + 1);
writeCommandRaw(0x2c); //Memory write
break;
case HORIZONTAL:
writeCommandRaw(0x2a); //Column address settings
writeData16(x1 + 1);
writeData16(x2 + 1);
writeCommandRaw(0x2b); //Row address setting
writeData16(y1 + 26);
writeData16(y2 + 26);
writeCommandRaw(0x2c); //Memory write
break;
default:
writeCommandRaw(0x2a); //Column address settings
writeData16(x1 + 1);
writeData16(x2 + 1);
writeCommandRaw(0x2b); //Row address setting
writeData16(y1 + 26);
writeData16(y2 + 26);
writeCommandRaw(0x2c); //Memory write
break;
}
}
} // namespace LCDBuiltin
<file_sep>/lib/LED/LED.cpp
#include "LED.hpp"
namespace LED
{
void LED::init()
{
for (uint8_t i = 0; i < 3; i++)
{
// initialize device
_pins[i].init();
_pins[i].set();
}
}
void LED::set(const LEDColor color)
{
for (uint8_t i = 0; i < 3; i++)
{
_pins[i].write(
!((color & (0x01 << i))));
}
}
} // namespace LED<file_sep>/lib/SSD1306/SSD1306.hpp
#ifndef __SSD1306_H
#define __SSD1306_H
#define WIRE_MAX 32 // if needed at all
#include "I2C.hpp"
#include "GPIO.hpp"
namespace SSD1306
{
enum SSD1306Command : uint8_t
{
MEMORY_MODE = 0x20,
DEACTIVATE_SCROLL = 0x2E,
SET_START_LINE = 0x40,
SETCONTRAST = 0x81,
CHARGE_PUMP = 0x8D,
SEGREMAP = 0xA0,
DISPLAYALLON_RESUME = 0xA4,
NORMALDISPLAY = 0xA6,
SET_MULTIPLEX = 0xA8,
DISPLAY_OFF = 0xAE,
DISPLAYON = 0xAF,
COMSCANDEC = 0xC8,
SET_DISPLAY_OFFSET = 0xD3,
SET_DISPLAYCLOCK_DIV = 0xD5,
SETPRECHARGE = 0xD9,
SETCOMPINS = 0xDA,
SETVCOMDETECT = 0xDB
};
class SSD1306
{
private:
I2C::I2C _i2c;
GPIO::GPIO _reset;
uint8_t _width;
uint8_t _height;
uint32_t _address;
uint32_t _clockDuring; //400000UL
uint32_t _clockAfter; //100000UL
uint8_t *_buffer;
void command(const uint8_t command);
void commands(const uint8_t *commands, uint8_t count);
public:
bool init();
void clearDisplay();
void display();
// void setTextSize(uint8_t size);
// void setTextColor(uint16_t color);
// void setCursor(int16_t x, int16_t y);
// void cp437();
// void write();
};
}; // namespace SSD1306
#endif<file_sep>/lib/SSD1306/SSD1306.cpp
#include "SSD1306.hpp"
#include "Timer.hpp"
#include <cstdlib>
#include <cstring>
namespace SSD1306
{
void SSD1306::command(const uint8_t command)
{
uint8_t *data = (uint8_t *)std::malloc(2);
*data = 0x00;
*(data + 1) = command;
_i2c.transmit(_address, data, 2);
std::free(data);
}
void SSD1306::commands(const uint8_t *commands, uint8_t count)
{
uint8_t *data = (uint8_t *)std::malloc(count + 1);
*data = 0x00;
std::memcpy(data + 1, commands, count);
_i2c.transmit(_address, data, count + 1);
std::free(data);
}
bool SSD1306::init()
{
_i2c.init();
if (&_reset)
{
_reset.init();
// reset display
_reset.set();
Timer::delay(1);
_reset.clear();
Timer::delay(10);
_reset.set();
}
if (!_buffer)
{
_buffer = (uint8_t *)std::malloc(_width * ((_height + 7) / 8));
return !_buffer;
}
clearDisplay();
// TODO this might be too verbose, after getting display working, try by just sending one big array
const uint8_t init1[] = {
DISPLAY_OFF,
SET_DISPLAYCLOCK_DIV,
0x80, // suggested ratio
SET_MULTIPLEX};
commands(init1, sizeof(init1));
command(_height - 1);
const uint8_t init2[] = {
SET_DISPLAY_OFFSET,
0x00,
SET_START_LINE | 0x00,
CHARGE_PUMP};
commands(init2, sizeof(init2));
command(0x14); // TODO (vccstate == SSD1306_EXTERNALVCC) ? 0x10 : 0x14
const uint8_t init3[] = {
MEMORY_MODE,
0x00,
SEGREMAP | 0x1,
COMSCANDEC};
commands(init3, sizeof(init3));
// TODO
// uint8_t comPins = 0x02;
// contrast = 0x8F;
// if ((WIDTH == 128) && (HEIGHT == 32)) {
// comPins = 0x02;
// contrast = 0x8F;
// } else if ((WIDTH == 128) && (HEIGHT == 64)) {
// comPins = 0x12;
// contrast = (vccstate == SSD1306_EXTERNALVCC) ? 0x9F : 0xCF;
// } else if ((WIDTH == 96) && (HEIGHT == 16)) {
// comPins = 0x2; // ada x12
// contrast = (vccstate == SSD1306_EXTERNALVCC) ? 0x10 : 0xAF;
// } else {
// // Other screen varieties -- TBD
// }
command(SETCOMPINS);
command(0x12);
command(SETCONTRAST);
command(0xCF);
command(SETPRECHARGE);
command(0xF1); // todo ssd1306_command1((vccstate == SSD1306_EXTERNALVCC) ? 0x22 : 0xF1);
const uint8_t init5[] = {
SETVCOMDETECT,
0x40,
DISPLAYALLON_RESUME,
NORMALDISPLAY,
DEACTIVATE_SCROLL,
DISPLAYON};
commands(init5, sizeof(init5));
return true;
}
void SSD1306::clearDisplay()
{
std::memset(_buffer, 0, _width * ((_height + 7) / 8));
}
void SSD1306::display()
{
}
} // namespace SSD1306<file_sep>/lib/I2C/I2C.hpp
#ifndef __I2C_H
#define __I2C_H
extern "C"
{
#include "gd32vf103_i2c.h"
}
#include <stdint.h>
namespace I2C
{
#define I2C_0 I2C::I2CPort(I2C0, RCU_I2C0, GPIO_PIN_6 | GPIO_PIN_7)
#define I2C_1 I2C::I2CPort(I2C1, RCU_I2C1, GPIO_PIN_10 | GPIO_PIN_11)
enum I2CDutyCycle : uint32_t
{
DUTY_1_2 = I2C_DTCY_2,
DUTY_9_16 = I2C_DTCY_16_9
};
enum I2CAddressFormat : uint32_t
{
ADDR_7 = I2C_ADDFORMAT_7BITS,
ADDR_10 = I2C_ADDFORMAT_10BITS
};
class I2CPort
{
private:
uint32_t _i2c_periph;
rcu_periph_enum _rcu_periph;
uint32_t _pin;
public:
I2CPort(uint32_t i2c_periph,
rcu_periph_enum rcu_periph,
uint32_t pin)
: _i2c_periph(i2c_periph),
_rcu_periph(rcu_periph),
_pin(pin) {}
uint32_t i2c_periph() { return _i2c_periph; }
rcu_periph_enum rcu_periph() { return _rcu_periph; }
uint32_t pin() { return _pin; }
};
class I2CSettings
{
private:
uint32_t _clock;
I2CDutyCycle _duty_cycle;
I2CAddressFormat _addr_mode;
public:
I2CSettings()
: I2CSettings(100000UL, DUTY_1_2, ADDR_7) {}
I2CSettings(uint32_t clock,
I2CDutyCycle duty_cycle,
I2CAddressFormat addr_mode)
: _clock(clock),
_duty_cycle(duty_cycle),
_addr_mode(addr_mode) {}
uint32_t clock() { return _clock; }
I2CDutyCycle duty_cycle() { return _duty_cycle; }
I2CAddressFormat addr_mode() { return _addr_mode; }
};
class I2C
{
private:
I2CPort _port;
I2CSettings _settings;
void startBus(uint32_t address);
void stopBus();
public:
I2C(I2CPort port)
: I2C(port, I2CSettings()) {}
I2C(I2CPort port,
I2CSettings settings)
: _port(port),
_settings(settings) {}
void init();
void begin();
void end();
void transmit(uint32_t address, uint8_t data);
void transmit(uint32_t address, uint8_t *data, uint32_t size);
};
} // namespace I2C
#endif
<file_sep>/lib/GPIO/GPIO.cpp
#include "GPIO.hpp"
namespace GPIO
{
void GPIO::init()
{
rcu_periph_clock_enable(_pin.rcu_periph());
gpio_init(_pin.gpio_periph(), _mode, _speed, _pin.pin());
}
void GPIO::set()
{
gpio_bit_set(_pin.gpio_periph(), _pin.pin());
}
void GPIO::clear()
{
gpio_bit_reset(_pin.gpio_periph(), _pin.pin());
}
void GPIO::write(const uint8_t value)
{
gpio_bit_write(_pin.gpio_periph(), _pin.pin(), status(value));
}
bool GPIO::read()
{
switch (_mode)
{
case MODE_IN_FLOATING:
case MODE_IPD:
case MODE_IPU:
return FlagStatus::SET == gpio_input_bit_get(_pin.gpio_periph(), _pin.pin()) ? true : false;
case MODE_OUT_OD:
case MODE_OUT_PP:
return FlagStatus::SET == gpio_output_bit_get(_pin.gpio_periph(), _pin.pin()) ? true : false;
default:
return false;
}
}
constexpr FlagStatus GPIO::status(const uint8_t value)
{
return value > 0 ? FlagStatus::SET : FlagStatus::RESET;
}
} // namespace GPIO<file_sep>/README.md
# gd32v-basics
A simple project used as a playground to build up some OO C++ apstraction layer around base C GD32V SKD.
Starting up with simple things like GPIO, SPI, some rudimentary APIs for working with screens I have around.
Hoping to have a working higher level abstraction for common use cases.
## Why do work myself?
Simple answer.
GD32V is a recent MCU and there is poor support from existing libraries for common frameworks.
I am not looking to implement stuff for Arduino or other libraries, but I am looking to have some fun, learn new language, find ways to optimize memory footprint.
There are some plans to use this, not just for fun.
Might look into porting some existing libraries to this base abstraction, as needed for whatever I build. Who know what will happen from there.
<file_sep>/lib/LED/LED.hpp
#ifndef __LED_H
#define __LED_H
#include "GPIO_pins.hpp"
namespace LED
{
enum LEDColor : uint8_t
{
BLACK = 0x00,
RED = 0x04,
YELLOW = 0x06,
GREEN = 0x02,
CYAN = 0x03,
BLUE = 0x01,
MAGENTA = 0x05,
WHITE = 0x07
};
class LED
{
private:
GPIO::GPIO _pins[3] = {
GPIO::GPIO(PA2, GPIO::MODE_OUT_PP),
GPIO::GPIO(PA1, GPIO::MODE_OUT_PP),
GPIO::GPIO(PC13, GPIO::MODE_OUT_PP)};
public:
LED(){
};
void init();
void set(const LEDColor color);
};
}; // namespace LED
#endif<file_sep>/lib/Timer/Timer.hpp
#ifndef __SYS_TICK_H
#define __SYS_TICK_H
#include <stdint.h>
class Timer
{
public:
static void delay(uint32_t count);
static void delayMicroseconds(uint32_t count);
static uint64_t millis();
static uint64_t micros();
};
#endif<file_sep>/lib/GPIO/GPIO_pins.hpp
#ifndef __GPIO_PINS_H
#define __GPIO_PINS_H
#include "GPIO.hpp"
#define PA0 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_0)
#define PA1 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_1)
#define PA2 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_2)
#define PA3 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_3)
#define PA4 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_4)
#define PA5 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_5)
#define PA6 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_6)
#define PA7 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_7)
#define PA8 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_8)
#define PA9 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_9)
#define PA10 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_10)
#define PA11 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_11)
#define PA12 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_12)
#define PA13 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_13)
#define PA14 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_14)
#define PA15 GPIO::GPIOPin(RCU_GPIOA, GPIOA, GPIO_PIN_15)
#define PB0 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_0)
#define PB1 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_1)
#define PB2 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_2)
#define PB3 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_3)
#define PB4 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_4)
#define PB5 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_5)
#define PB6 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_6)
#define PB7 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_7)
#define PB8 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_8)
#define PB9 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_9)
#define PB10 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_10)
#define PB11 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_11)
#define PB12 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_12)
#define PB13 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_13)
#define PB14 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_14)
#define PB15 GPIO::GPIOPin(RCU_GPIOB, GPIOB, GPIO_PIN_15)
#define PC0 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_0)
#define PC1 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_1)
#define PC2 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_2)
#define PC3 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_3)
#define PC4 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_4)
#define PC5 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_5)
#define PC6 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_6)
#define PC7 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_7)
#define PC8 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_8)
#define PC9 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_9)
#define PC10 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_10)
#define PC11 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_11)
#define PC12 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_12)
#define PC13 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_13)
#define PC14 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_14)
#define PC15 GPIO::GPIOPin(RCU_GPIOC, GPIOC, GPIO_PIN_15)
#define PD0 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_0)
#define PD1 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_1)
#define PD2 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_2)
#define PD3 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_3)
#define PD4 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_4)
#define PD5 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_5)
#define PD6 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_6)
#define PD7 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_7)
#define PD8 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_8)
#define PD9 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_9)
#define PD10 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_10)
#define PD11 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_11)
#define PD12 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_12)
#define PD13 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_13)
#define PD14 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_14)
#define PD15 GPIO::GPIOPin(RCU_GPIOD, GPIOD, GPIO_PIN_15)
#define PE0 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_0)
#define PE1 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_1)
#define PE2 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_2)
#define PE3 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_3)
#define PE4 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_4)
#define PE5 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_5)
#define PE6 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_6)
#define PE7 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_7)
#define PE8 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_8)
#define PE9 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_9)
#define PE10 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_10)
#define PE11 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_11)
#define PE12 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_12)
#define PE13 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_13)
#define PE14 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_14)
#define PE15 GPIO::GPIOPin(RCU_GPIOE, GPIOE, GPIO_PIN_15)
#endif<file_sep>/lib/ST7920/ST7920.hpp
#ifndef __ST7920_H
#define __ST7920_H
#include "SPI.hpp"
#include "GPIO.hpp"
#include "GPIO_pins.hpp"
#define ST7920_LINE0 0x80
#define ST7920_LINE1 0x90
#define ST7920_LINE2 0x88
#define ST7920_LINE3 0x98
enum ST7920Command : uint8_t
{
LCD_CLS = 0x01,
LCD_ADDRINC = 0x06,
LCD_DISPLAYON = 0x0C,
LCD_DISPLAYOFF = 0x08,
LCD_CURSORON = 0x0E,
LCD_CURSORBLINK = 0x0F,
LCD_BASIC = 0x30,
};
class ST7920
{
private:
SPI::SPI _spi;
GPIO::GPIO _cs;
public:
ST7920(SPI::SPIPort spiPort,
SPI::SPISettings spiSettings,
GPIO::GPIO cs)
: ST7920(
SPI::SPI(
spiPort,
spiSettings),
cs) {}
ST7920(SPI::SPIPort spiPort,
GPIO::GPIO cs)
: ST7920(
SPI::SPI(
spiPort,
SPI::SPISettings(
SPI::MSB,
SPI::MODE3,
SPI::PSC_256)),
cs) {}
ST7920(SPI::SPI spi,
GPIO::GPIO cs)
: _spi(spi),
_cs(cs) {}
void init();
void send(uint8_t prefix, uint8_t data);
void send(ST7920Command command);
void send(uint8_t data);
void writeText(uint8_t position, char *str);
};
#endif
<file_sep>/lib/GPIO/GPIO.hpp
#ifndef __GPIO_H
#define __GPIO_H
extern "C"
{
#include "gd32vf103_gpio.h"
#include "gd32vf103_rcu.h"
}
namespace GPIO
{
enum GPIOMode : uint32_t
{
MODE_AIN = GPIO_MODE_AIN,
MODE_IN_FLOATING = GPIO_MODE_IN_FLOATING,
MODE_IPD = GPIO_MODE_IPD,
MODE_IPU = GPIO_MODE_IPU,
MODE_OUT_OD = GPIO_MODE_OUT_OD,
MODE_OUT_PP = GPIO_MODE_OUT_PP,
MODE_AF_OD = GPIO_MODE_AF_OD,
MODE_AF_PP = GPIO_MODE_AF_PP
};
enum GPIOSpeed : uint32_t
{
SPEED_10MHZ = GPIO_OSPEED_10MHZ,
SPEED_2MHZ = GPIO_OSPEED_2MHZ,
SPEED_50MHZ = GPIO_OSPEED_50MHZ
};
class GPIOPin
{
private:
const rcu_periph_enum _rcu_periph;
const uint32_t _gpio_periph;
const uint32_t _pin;
public:
GPIOPin(const rcu_periph_enum rcu_periph,
const uint32_t gpio_periph,
const uint32_t pin)
: _rcu_periph(rcu_periph),
_gpio_periph(gpio_periph),
_pin(pin){};
constexpr rcu_periph_enum rcu_periph() const { return _rcu_periph; }
constexpr uint32_t gpio_periph() const { return _gpio_periph; }
constexpr uint32_t pin() const { return _pin; }
};
class GPIO
{
private:
const GPIOPin _pin;
const GPIOMode _mode;
const GPIOSpeed _speed;
constexpr FlagStatus status(const uint8_t value);
public:
GPIO(const GPIOPin pin,
const GPIOMode mode,
const GPIOSpeed speed = GPIOSpeed::SPEED_50MHZ)
: _pin(pin),
_mode(mode),
_speed(speed) {}
void init();
void set();
void clear();
bool read();
void write(uint8_t value);
};
}; // namespace GPIO
#endif<file_sep>/include/Configuration.h
#ifndef __CONFIG_H
#define __CONFIG_H
// Enable demo for built-in LCD
#define LCD_BUILTIN_DEMO
// Enable demo for built-in RGB LED
#define LED_DEMO
// Enable interrupt driven counter increment with boot button
#define BOOT_COUNTER_DEMO
#endif<file_sep>/lib/SPI/SPI.hpp
#ifndef __SPH_H
#define __SPH_H
extern "C"
{
#include "gd32vf103_spi.h"
}
#include <stdint.h>
namespace SPI
{
#define SPI_0 SPIPort(SPI0, RCU_GPIOA, RCU_SPI0, GPIOA, GPIO_PIN_5 | GPIO_PIN_7, GPIO_PIN_6)
#define SPI_1 SPIPort(SPI1, RCU_GPIOB, RCU_SPI1, GPIOB, GPIO_PIN_13 | GPIO_PIN_15, GPIO_PIN_14)
#define SPI_2 SPIPort(SPI2, RCU_GPIOB, RCU_SPI2, GPIOB, GPIO_PIN_3 | GPIO_PIN_5, GPIO_PIN_4)
enum SPIEndianess : uint32_t
{
MSB = SPI_ENDIAN_MSB,
LSB = SPI_ENDIAN_LSB
};
enum SPIMode : uint32_t
{
MODE0 = SPI_CK_PL_LOW_PH_1EDGE,
MODE1 = SPI_CK_PL_HIGH_PH_1EDGE,
MODE2 = SPI_CK_PL_LOW_PH_2EDGE,
MODE3 = SPI_CK_PL_HIGH_PH_2EDGE
};
enum SPIPrescale : uint32_t
{
PSC_2 = SPI_PSC_2,
PSC_4 = SPI_PSC_4,
PSC_8 = SPI_PSC_8,
PSC_16 = SPI_PSC_16,
PSC_32 = SPI_PSC_32,
PSC_64 = SPI_PSC_64,
PSC_128 = SPI_PSC_128,
PSC_256 = SPI_PSC_256
};
class SPIPort
{
private:
const uint32_t _spi_periph;
const rcu_periph_enum _rcu_gpio_periph;
const rcu_periph_enum _rcu_spi_periph;
const uint32_t _gpio;
const uint32_t _out;
const uint32_t _in;
public:
SPIPort(const uint32_t spi_periph,
const rcu_periph_enum rcu_gpio_periph,
const rcu_periph_enum rcu_spi_periph,
const uint32_t gpio,
const uint32_t out,
const uint32_t in)
: _spi_periph(spi_periph),
_rcu_gpio_periph(rcu_gpio_periph),
_rcu_spi_periph(rcu_spi_periph),
_gpio(gpio),
_out(out),
_in(in) {}
constexpr uint32_t spi_periph() const { return _spi_periph; }
constexpr rcu_periph_enum rcu_gpio_periph() const { return _rcu_gpio_periph; }
constexpr rcu_periph_enum rcu_spi_periph() const { return _rcu_spi_periph; }
constexpr uint32_t gpio() const { return _gpio; }
constexpr uint32_t out() const { return _out; }
constexpr uint32_t in() const { return _in; }
};
class SPISettings
{
private:
const SPIEndianess _endinaess;
const SPIMode _mode;
const SPIPrescale _prescale;
public:
SPISettings(const SPIEndianess endinaess,
const SPIMode mode,
const SPIPrescale prescale = SPIPrescale::PSC_128)
: _endinaess(endinaess),
_mode(mode),
_prescale(prescale) {}
constexpr SPIEndianess endinaess() const { return _endinaess; }
constexpr SPIMode mode() const { return _mode; }
constexpr SPIPrescale prescale() const { return _prescale; }
};
class SPI
{
private:
const SPIPort _spi;
const SPISettings _settings;
public:
SPI(const SPIPort spi,
const SPISettings settings)
: _spi(spi),
_settings(settings) {}
void init();
void begin();
void end();
const uint8_t transfer(const uint8_t data);
};
}; // namespace SPI
#endif<file_sep>/lib/I2C/I2C.cpp
#include "I2C.hpp"
extern "C"
{
#include "gd32vf103_rcu.h"
}
namespace I2C
{
void I2C::init()
{
rcu_periph_clock_enable(RCU_GPIOB); // I2C buses are on PortB
rcu_periph_clock_enable(_port.rcu_periph());
gpio_init(GPIOB, GPIO_MODE_AF_OD, GPIO_OSPEED_50MHZ, _port.pin()); // I2C buses are on PortB
i2c_clock_config(_port.i2c_periph(), _settings.clock(), _settings.duty_cycle());
}
void I2C::startBus(uint32_t address)
{
// wait until I2C bus is idle
while (i2c_flag_get(_port.i2c_periph(), I2C_FLAG_I2CBSY))
;
// send a start condition to I2C bus and wait for it
i2c_start_on_bus(_port.i2c_periph());
while (!i2c_flag_get(_port.i2c_periph(), I2C_FLAG_SBSEND))
;
// send slave address to I2C bus and wait for it
i2c_master_addressing(_port.i2c_periph(), address, I2C_TRANSMITTER);
while (!i2c_flag_get(_port.i2c_periph(), I2C_FLAG_ADDSEND))
;
i2c_flag_clear(_port.i2c_periph(), I2C_FLAG_ADDSEND);
//wait until the transmit data buffer is empty
while (!i2c_flag_get(_port.i2c_periph(), I2C_FLAG_TBE))
;
}
void I2C::stopBus()
{
// send a stop condition to I2C bus
i2c_stop_on_bus(_port.i2c_periph());
/* wait until stop condition generate */
while (I2C_CTL0(_port.i2c_periph()) & I2C_CTL0_STOP)
;
}
void I2C::begin()
{
i2c_enable(_port.i2c_periph());
}
void I2C::end()
{
// i2c_disable(_port.i2c_periph());
}
void I2C::transmit(uint32_t address, uint8_t data)
{
startBus(address);
// data transmission and wait for empty
i2c_data_transmit(_port.i2c_periph(), data);
while (!i2c_flag_get(_port.i2c_periph(), I2C_FLAG_TBE))
;
stopBus();
}
void I2C::transmit(uint32_t address, uint8_t *data, uint32_t size)
{
startBus(address);
while (size--)
{
// data transmission and wait for empty
i2c_data_transmit(_port.i2c_periph(), *(data++));
while (!i2c_flag_get(_port.i2c_periph(), I2C_FLAG_TBE))
;
}
stopBus();
}
} // namespace I2C<file_sep>/lib/SPI/SPI.cpp
#include "SPI.hpp"
extern "C"
{
#include "gd32vf103_rcu.h"
#include "gd32vf103_gpio.h"
}
namespace SPI
{
void SPI::init()
{
rcu_periph_clock_enable(_spi.rcu_gpio_periph());
rcu_periph_clock_enable(RCU_AF);
rcu_periph_clock_enable(_spi.rcu_spi_periph());
gpio_init(_spi.gpio(), GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, _spi.out());
if (_spi.in())
gpio_init(_spi.gpio(), GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, _spi.in());
spi_parameter_struct params;
spi_struct_para_init(¶ms);
params.device_mode = SPI_MASTER;
params.trans_mode = SPI_TRANSMODE_FULLDUPLEX;
params.frame_size = SPI_FRAMESIZE_8BIT;
params.nss = SPI_NSS_SOFT;
params.endian = _settings.endinaess();
params.clock_polarity_phase = _settings.mode();
params.prescale = _settings.prescale();
spi_init(_spi.spi_periph(), ¶ms);
spi_crc_polynomial_set(_spi.spi_periph(), 7);
}
void SPI::begin()
{
spi_enable(_spi.spi_periph());
}
void SPI::end()
{
spi_disable(_spi.spi_periph());
}
const uint8_t SPI::transfer(uint8_t data)
{
while (RESET == spi_i2s_flag_get(_spi.spi_periph(), SPI_FLAG_TBE))
;
spi_i2s_data_transmit(_spi.spi_periph(), data);
while (RESET == spi_i2s_flag_get(_spi.spi_periph(), SPI_FLAG_RBNE))
;
return spi_i2s_data_receive(_spi.spi_periph());
}
} // namespace SPI
|
415f05343a56dbab4c0963c7e4060e5c561dec75
|
[
"Markdown",
"C",
"C++"
] | 20 |
C++
|
fzilic/gd32v-basics
|
ee0b5fc16bc469c6e4ade6c48ad76209974bfc94
|
8bb5e650d29de2a3238f0ca640230a1d06a70983
|
refs/heads/master
|
<file_sep># chatbot-b3
Chatbot que traz a cotação de 3 ações e também as previsões dos próximos 30 dias.
<file_sep>Flask==1.1.1
fbprophet==0.6
matplotlib==3.2.2
pandas==1.0.5
<file_sep>import time
import os
import telebot
from flask import Flask, request
from datetime import date
import pandas as pd
import matplotlib.pyplot as plt
#
from fbprophet import Prophet
TOKEN = "YOUR-TOKEN-HERE" # mybot
bot = telebot.TeleBot(token=TOKEN)
today = str(date.today())
server = Flask(__name__)
# Install yfinance package.
#!pip install yfinance
import yfinance as yf
#
# Get values for
stocks = ['PETR4.SA', 'TAEE4.SA', 'ITSA4.SA']
# Download data
data = {}
for i in range(len(stocks)):
temp = yf.download(stocks[i], '2020-01-01', today)
if stocks[i] == 'PETR4.SA':
df_petr4 = temp[['Open','Close']]
if stocks[i] == 'TAEE4.SA':
df_taee4 = temp[['Open','Close']]
if stocks[i] == 'ITSA4.SA':
df_itsa4 = temp[['Open','Close']]
data.update({stocks[i]:temp.Close})
df = pd.DataFrame(data, columns=stocks)
#
for i, col in enumerate(df.columns):
df[col].plot(grid=True, title='PETR4.SA, TAEE4.SA e ITSA4.SA\nCotação de Fechamento das Ações em 2020\nPeriodo: de 01/jan até hoje')
plt.xticks(rotation=70)
plt.legend(df.columns)
plt.savefig('all.png', bbox_inches='tight')
#####################################################
# Graphics
df_petr4.plot(grid=True, title='Cotação da PETR4 em 2020\nPeriodo: de 01/jan até hoje' )
plt.savefig('petr4.png')
#
df_taee4[['Open', 'Close']].plot(grid=True, title='Cotação da TAEE4 em 2020\nPeriodo: de 01/jan até hoje' )
plt.savefig('taee4.png')
#
df_itsa4[['Open','Close']].plot(grid=True, title='Cotação da ITSA4 em 2020\nPeriodo: de 01/jan até hoje' )
#
plt.savefig('itsa4.png')
##################### Função Forecast ################################
# Forecast by Prophet
prediction_size = 30 # dias
def stock(stock):
stock.reset_index(inplace=True)
df = pd.DataFrame()
df['ds'] = stock['Date']
df['y'] = stock['Close']
return df
def predict_stock(model,df,prediction_size, stock):
model.fit(df)
future = model.make_future_dataframe(periods=prediction_size)
forecast = model.predict(future)
fig = model.plot(forecast, figsize=(10,5))
ax = fig.gca()
ax.set_title(stock+"\nForecast by Prophet\nPeriod: next 30 days from today", size=18)
ax.set_xlabel("Date", size=14)
ax.set_ylabel("Close", size=14)
ax.tick_params(axis='x', labelsize=10)
ax.tick_params(axis='y', labelsize=10)
fig.savefig('prophet-'+stock+'.png', bbox_inches='tight')
#
fig = model.plot_components(forecast, figsize=(10,5))
fig.savefig('components-'+stock+'.png')
##################### Previsões ################################
# PETR4
model1 = Prophet(interval_width=0.95)
df = stock(df_petr4)
predict_stock(model1,df,prediction_size,'PETR4')
#
# TAEE4
model2 = Prophet(interval_width=0.95)
df = stock(df_taee4)
predict_stock(model2,df,prediction_size,'TAEE4')
#
# ITSA4
model3 = Prophet(interval_width=0.95)
df = stock(df_itsa4)
predict_stock(model3,df,prediction_size,'ITSA4')
##################### Mensagens ################################
@bot.message_handler(commands=['start']) # welcome message
def send_welcome(message): # handler
photo = open('bot-b3.png', 'rb')
bot.send_photo(message.chat.id, photo)
texto = 'BEM VINDO\nEste bot traz a cotação de:
\nPETR4, TAEE4 e ITSA4.\nPeriodo: desde janeiro de 2020
até a data atual.\nTraz também a previsão de fechamento
nos próximos 30 dias.\nVeja: /menu'
bot.reply_to(message, texto)
@bot.message_handler(commands=['bot']) # bot-b3
def send_welcome(message):
photo = open('bot-b3.png', 'rb')
bot.send_photo(message.chat.id, photo)
@bot.message_handler(commands=['menu']) # Menu
def send_welcome(message):
photo = open('menu.png', 'rb')
bot.send_photo(message.chat.id, photo)
texto = 'PETR4 -> /petr4 /fore_petr4\nTAEE4 -> /taee4
/fore_taee4\nITSA4 -> /itsa4 /fore_itsa4\nAll -> /all'
bot.reply_to(message, texto)
##################### Cotação ################################
@bot.message_handler(commands=['all']) # todas ações
def send_welcome(message):
photo = open('all.png', 'rb')
bot.send_photo(message.chat.id, photo)
@bot.message_handler(commands=['petr4']) # PETR4
def send_welcome(message):
photo = open('petr4.png', 'rb')
bot.send_photo(message.chat.id, photo)
@bot.message_handler(commands=['taee4']) # TAEE4
def send_welcome(message):
photo = open('taee4.png', 'rb')
bot.send_photo(message.chat.id, photo)
@bot.message_handler(commands=['itsa4']) # ITSA4
def send_welcome(message):
photo = open('itsa4.png', 'rb')
bot.send_photo(message.chat.id, photo)
##################### Forecast ################################
@bot.message_handler(commands=['fore_petr4'])
def send_welcome(message):
photo = open('prophet-PETR4.png', 'rb')
bot.send_photo(message.chat.id, photo)
photo = open('components-PETR4.png', 'rb')
bot.send_photo(message.chat.id, photo)
@bot.message_handler(commands=['fore_taee4'])
def send_welcome(message):
photo = open('prophet-TAEE4.png', 'rb')
bot.send_photo(message.chat.id, photo)
photo = open('components-TAEE4.png', 'rb')
bot.send_photo(message.chat.id, photo)
@bot.message_handler(commands=['fore_itsa4'])
def send_welcome(message):
photo = open('prophet-ITSA4.png', 'rb')
bot.send_photo(message.chat.id, photo)
photo = open('components-ITSA4.png', 'rb')
bot.send_photo(message.chat.id, photo)
#####################################################
@server.route('/' + TOKEN, methods=['POST'])
def getMessage():
bot.process_new_updates([telebot.types.Update.de_json
(request.stream.read().decode("utf-8"))])
return "!", 200
@server.route("/")
def webhook():
bot.remove_webhook()
bot.set_webhook(url='https://YOUR-APP.herokuapp.com/'+TOKEN)
return "!", 200
if __name__ == "__main__":
server.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))
|
7c934649c3934c275f71cbdf379e3a7b6b03c8f7
|
[
"Markdown",
"Python",
"Text"
] | 3 |
Markdown
|
silviolima07/chatbot-b3
|
dcc8d847b504c62150521faccfdd4598c30e24e6
|
96d6920e54719890e4d0462aafb5c94d6cad03b8
|
refs/heads/master
|
<file_sep>angular.module('myApp')
.directive('genTimetable', function () {
return {
restrict: 'A',
templateUrl: 'gen-timetable.tpl.html',
scope: {
slots: '='
},
link: function (scope, element, attributes) {
var _days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var _selection = {
state: false,
day: [0, 0, 0, 0, 0, 0, 0],
hour: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
};
scope.getColor = function(value){
if(value >= 1 && value < 3)
{return 'range1';}
else if (value >= 3 && value < 5)
{return 'range2';}
else if (value >= 5 && value < 7)
{return 'range3';}
else if (value >= 7 && value < 9)
{return 'range4';}
else if (value >= 9)
{return 'range5';}
else{
return '';
}
};
function _loop(begin, end, step) {
var array = [];
for (var i = begin; i <= end; i += step) {
array.push(i);
}
return array;
}
scope.greaterThan = function(n){
n=n+12
if (n>=24){return n-24}
else {return n}
}
function _init() {
scope.loop = _loop;
scope.days = _days;
}
_init();
}
};
});
<file_sep>angular.module('myApp')
.factory('ApiFactory', ['$http', function($http){
var url='http://127.0.0.1:8080/';
function getTimetable(user_id){
return $http.get(url + 'api/users/' + user_id + '/week');
}
function deleteOne(user_id){
return $http.delete(url +'api/users/' + user_id + '/week');
}
function getGenTimetable(){
return $http.get(url + 'api/general/week');
}
function getUserList(){
return $http.get(url + 'api/general/userlist');
}
function putTimetable(user_id, data){
return $http.put(url + 'api/users/' + user_id + '/week', {nick:user_id, week:data});
}
return {
getTimetable : getTimetable,
getGenTimetable : getGenTimetable,
putTimetable : putTimetable,
getUserList : getUserList,
deleteOne : deleteOne
};
}]);
<file_sep># Dofitario: Matcher de horarios
Aplicación que permita a usuarios definir sus horarios para comparar coincidencias con otros usuarios. Facilitando la elección del momento del día para realizar algo en común.
### Desarrollo
Este es mi primer proyecto web, he decidido utilizar Python para el back por partir de algo conocido, el resto ha sido todo nuevo para mí: mongodb para los datos, flask para web, y angularjs para front. Por hacer queda una gestión de usuarios con autenticación, permitir la creación de diferentes horarios/calendarios personalizados, definir e implementar algunos esquemas para la comunicación y mejorar la apariencia visual (tambien soy un paquete en css/html).
<file_sep>angular.module('myApp')
.directive('myTimetable', function () {
return {
restrict: 'A',
templateUrl: 'my-timetable.tpl.html',
scope: {
slots: '='
},
link: function (scope, element, attributes) {
var _days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var _selection = {
state: false,
day: [0, 0, 0, 0, 0, 0, 0],
hour: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
};
function _loop(begin, end, step) {
var array = [];
for (var i = begin; i <= end; i += step) {
array.push(i);
}
return array;
}
scope.greaterThan = function(n){
n=n+12
if (n>=24){return n-24}
else {return n}
}
function _toggle(what, day, hour) {
var i = 0;
switch (what) {
case 'day':
_selection.day[day] = !_selection.day[day] ? 1 : 0;
for (i = 0; i <= 16; i++) {
scope.slots[day][i] = _selection.day[day];
}
break;
case 'hour':
_selection.hour[hour] = !_selection.hour[hour] ? 1 : 0;
for (i = 0; i < 7; i++) {
scope.slots[i][hour] = _selection.hour[hour];
}
break;
case 'slot':
if (_selection.state) {
scope.slots[day][hour] = !scope.slots[day][hour] ? 1 : 0;
}
break;
}
}
function _select(state, day, hour) {
_selection.state = state;
if (_selection.state) {
_toggle('slot', day, hour);
}
}
function _init() {
scope.loop = _loop;
scope.toggle = _toggle;
scope.select = _select;
scope.days = _days;
}
_init();
}
};
});
<file_sep>from flask import Flask, url_for, request, json
from pymongo import MongoClient
import numpy
from flask.ext.cors import CORS
client = MongoClient()
db = client.dofidb
app = Flask(__name__, static_url_path='')
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
@app.route('/')
def root():
return app.send_static_file('index.html')
@app.route('/api/users/<user>/week', methods = ['GET','PUT', 'DELETE'])
def api_userWeek(user):
if request.method == 'GET':
counter = 0
cursor = db.tIndividualWeeklyTimetable.find({"nick":user})
for doc in cursor:
counter = counter+1
result = doc['week']
print result
if counter == 0:
return json.dumps({"response":"Error", "desc": "User not registered"})
else:
return json.dumps({"response":"OK", "week": result})
elif request.method == 'PUT':
week = json.loads(request.data)['week']
print week, type(week)
counter = 0
cursor = db.tIndividualWeeklyTimetable.find({"nick":user})
for doc in cursor:
counter = counter+1
result = doc['week']
print "MANTECA"
# db.tIndividualWeeklyTimetable.insert_one({"nick":user)
if counter == 1:
db.tIndividualWeeklyTimetable.update_one(
{"nick":user},
{
"$set": {
"week": week
}
}
)
return json.dumps({"response":"OK", "desc": "User week updated"})
else:
print week, type(week)
db.tIndividualWeeklyTimetable.insert_one(
{"nick":user,
"week":week}
)
return json.dumps({"response":"OK", "desc": "New user registered"})
else:
db.tIndividualWeeklyTimetable.delete_one({"nick":user})
return json.dumps({"response":"OK", "desc": "Element deleted"})
@app.route('/api/general/week')
def api_genWeek():
print "POLLA"
counter = 0
cursor = db.tIndividualWeeklyTimetable.find()
for line in cursor:
print line['week']
counter = counter + 1
if counter == 1:
aux = numpy.array(line['week'])
else:
aux = aux + numpy.array(line['week'])
print aux
result = numpy.ndarray.tolist(aux)
print result
if counter == 0:
return json.dumps({"response":"Error", "desc": "No results o_O, check DB!!!"})
else:
return json.dumps({"response":"OK", "week": result})
@app.route('/api/general/userlist')
def api_genUserList():
print "POLLA"
counter = 0
userList = list()
cursor = db.tIndividualWeeklyTimetable.find()
for line in cursor:
userList.append(line['nick'])
return json.dumps({"users": userList})
# @app.route('/articles')
# def api_articles():
# return 'List of ' + url_for('api_articles')
@app.route('/articles/<articleid>')
def api_article(articleid):
return 'You are reading ' + articleid
@app.route('/hello')
def api_hello():
if 'name' in request.args:
return 'Hello ' + request.args['name']
else:
return 'Hello <NAME>'
@app.route('/echo', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
def api_echo():
if request.method == 'GET':
return "ECHO: GET\n"
elif request.method == 'POST':
return "ECHO: POST\n"
elif request.method == 'PATCH':
return "ECHO: PACTH\n"
elif request.method == 'PUT':
return "ECHO: PUT\n"
elif request.method == 'DELETE':
return "ECHO: DELETE"
if __name__ == '__main__':
a= app.run(port = 8080)
<file_sep>angular.module('myApp')
.controller('MainCtrl', ['$scope', '$http', 'ApiFactory', function ($scope, $http, ApiFactory) {
var ctrl = this;
var _slots = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
function _init() {
ctrl.slots = _slots;
ctrl.generateUserList()
ctrl.loadGenTable()
}
// ctrl.user = "Henry";
ctrl.generateUserList = function(){
console.log('Generando lista')
ApiFactory.getUserList().then(function(data){
if(data.data.response === "Error"){
}
else {
console.log(data)
ctrl.userList = data.data.users
}
});
};
ctrl.loadTable = function(user){
// console.log(ApiFactory)
console.log(user)
ApiFactory.getTimetable(user).then(function(data){
if(data.data.response === "Error"){
}
else{
console.log(data)
ctrl.slots = data.data.week;
}
});
};
ctrl.deleteUser = function(user){
console.log(ApiFactory)
ApiFactory.deleteOne(user).then(function(data){
if(data.data.response === "Error"){
}
else{
console.log(data)
ctrl.generateUserList()
ctrl.loadGenTable()
ctrl.user = ''
}
});
};
ctrl.saveTable = function(user, slots){
slots = slots || _slots
console.log(ApiFactory)
ApiFactory.putTimetable(user, slots).then(function(data){
if(data.data.response === "Error"){
}
else{
console.log(data)
ctrl.newUser = ''
ctrl.generateUserList()
ctrl.loadGenTable()
}
});
};
ctrl.resetTable = function(user){
console.log(ApiFactory)
ApiFactory.putTimetable(user, _slots).then(function(data){
if(data.data.response === "Error"){
}
else{
console.log(data)
ctrl.newUser = ''
ctrl.slots = _slots
ctrl.loadTable(user)
ctrl.loadGenTable()
}
});
};
ctrl.loadGenTable = function(){
console.log(ApiFactory)
ApiFactory.getGenTimetable().then(function(data){
if(data.data.response === "Error"){
}
else{
console.log(data)
ctrl.slots2 = data.data.week;
}
});
};
//
// it('should check ng-click', function() {
// $http.put('/api/users/PEPE/week')
// });
_init();
}]);
|
47f52bd0d2b0f8871f45a772f1b6b4e6ff84bd36
|
[
"JavaScript",
"Python",
"Markdown"
] | 6 |
JavaScript
|
uborzz/Dofitario
|
3589fd6d5401f1c33c4034ff4dc0e4b502505a59
|
bb8203aad63a22425c51df2b549c21e04bcf24e6
|
refs/heads/master
|
<file_sep>include ':prodo3'
<file_sep>function SuperButton(canvas, size) {
this.canvas = canvas;
this.size = size; // seconds of recording time
this.time = 0; // time pos in recording
this.timer = null; // recorder interval
this.audio = null; // audio buffer
this.demo = 0;
this.demos = []; // sample audio data for demo
try {
window.AudioContext = window.AudioContext||window.webkitAudioContext;
this.audioContext = new AudioContext();
}
catch(e) {
alert('Web Audio API is not supported in this browser');
}
var audioContext = this.audioContext;
// load the sample sounds
var owner = this;
$.each(['whistling3.ogg'], function(i, name) {
console.log("requesting " + name);
var request = new XMLHttpRequest();
request.open("GET", "sounds/" + name, true);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
owner.audio = buffer;
console.log("loaded demo #"+i+". length is "+(buffer.getChannelData(0).length/buffer.sampleRate)+" seconds.");
});
}
request.send();
});
}
SuperButton.prototype = {
render: function() {
var c = this.canvas.getContext('2d');
var width = 2;
var cx = this.canvas.width/2;
var cy = this.canvas.height/2;
var r = this.canvas.width/2-width/2;
// draw circle
c.fillStyle = "#F00";
c.beginPath();
c.arc(cx, cy, r, 0, 2 * Math.PI, false);
// draw outline
c.fillStyle = 'red';
c.fill();
c.lineWidth = width;
c.strokeStyle = '#660000';
c.stroke();
// draw waveform
if(this.audio != null) {
// gather samples and info
function analyze(audio, bins) {
var samples = audio.getChannelData(0);
var rate = audio.sampleRate;
var length = samples.length / rate; // seconds of audio
var binSize = Math.floor(samples.length / bins);
var avgs = [];
var max = 0;
var min = 0;
for(var b = 0; b < bins; b++) {
// average samples
var total = 0;
for(var t = 0; t < binSize; t++)
total += samples[b * binSize + t];
var avg = total / binSize;
avgs[b] = avg;
if(avg > max) {
max = avg;
} else if(avg < min) {
min = avg;
}
}
return {
audio: audio,
samples: samples,
rate: rate,
length: length,
binSize: binSize,
averages: avgs,
max: max,
min: min
}
}
var maxdegrees = 360 * this.audio.getChannelData(0).length / this.size;
var portion = this.time/this.size;
var degrees = Math.floor(portion*maxdegrees);
if(degrees > 360) degrees = 360;
var data = analyze(this.audio, degrees);
c.strokeStyle = 'blue';
var bias = -data.min;
var absmax = data.max + bias;
for(var i = 0; i < data.averages.length * portion; i++) {
var l = r * (data.averages[i] + bias) / absmax;
var a = 2 * Math.PI * i / 360;
c.beginPath();
c.moveTo(cx, cy);
c.lineTo(cx + l * Math.cos(a), cy + l * Math.sin(a));
c.stroke();
}
}
},
play: function() {
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination); // connect the source to the context's destination (the speakers)
source.start(0);
},
record: function() {
var rate = 10; // hz
var btn = this;
if(btn.timer == null) {
btn.timer = setInterval(function() {
btn.time += 1/rate;
btn.render();
if(btn.time > btn.size) btn.stop();
}, 1000/rate);
}
},
stop: function() {
if(this.timer != null) {
clearInterval(this.timer);
this.timer = null;
}
},
trash: function() {
this.stop();
this.time = 0;
this.render();
}
}
<file_sep>audiotext
=========
blurb burst
no
talkie
<file_sep>include ':audiotext'
|
676a4d4a9987bd019a48ca554d8ede85a93107ce
|
[
"JavaScript",
"Markdown",
"Gradle"
] | 4 |
Gradle
|
Flame7746/audiotext
|
8d47457d2597063c863f7c874397dee49c7b604a
|
e1c43ebc159c25b64050cb45d939abc5d7e18f53
|
refs/heads/main
|
<file_sep>from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D,Flatten,Dense
from keras.datasets import mnist
from keras.utils import np_utils as np
import numpy
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000,28, 28, 1).astype("float32")
x_test = x_test.reshape(10000,28, 28, 1).astype("float32")
x_train /= 255
x_test /= 255
y_train = np.to_categorical(y_train)
y_test = np.to_categorical(y_test)
cnn_model = Sequential()
cnn_model.add(Conv2D(32, (3, 3), input_shape=(28, 28, 1), activation="relu"))
cnn_model.add(MaxPooling2D(pool_size=(2, 2)))
cnn_model.add(Conv2D(64, (3, 3), activation="relu"))
cnn_model.add(MaxPooling2D(pool_size=(2, 2)))
cnn_model.add(Conv2D(128, (3, 3), activation="relu"))
cnn_model.add(MaxPooling2D(pool_size=(2, 2)))
cnn_model.add(Flatten())
cnn_model.add(Dense(units=128, activation="relu"))
cnn_model.add(Dense(units=10, activation="softmax"))
cnn_model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
cnn_model.fit(x_train, y_train, validation_data=(x_test, y_test), batch_size=200, epochs=10)
scores = cnn_model.evaluate(x_test, y_test, verbose=0)
print("Error: {:.2f}%".format((1-scores[1])*100))<file_sep># handwritten-digit-recognition
Handwritten digit recognition by using MNIST dataset and convolutional neural network.
|
7585579dcb1c6325297aa41cce3b62344e6d7d72
|
[
"Markdown",
"Python"
] | 2 |
Python
|
rutwikbaheti/handwritten-digit-recognition
|
2c97ed64dbaa311aee1758135715bfda8415e12c
|
9155f0b21c4a32bc591d3491e2c04f29687c0e5d
|
refs/heads/master
|
<repo_name>9OMShitikov/acram-alpha<file_sep>/differentiator_tree/expression_tree.cpp
#include "expression_tree.h"
void ExpressionTree::generate_tree(int& new_variables_count, int& new_nodes_count,
tree_node* new_tree_nodes, variable* new_variables) {
if (new_variables_count > 0) ASSERT(new_variables);
if (new_nodes_count > 0) ASSERT(new_tree_nodes);
variables_count = new_variables_count;
nodes_count = new_nodes_count;
tree_.ptr = new char[sizeof(int) + variables_count * sizeof(variable) + sizeof(int) +
nodes_count * sizeof(tree_node)];
variables.ptr = (reinterpret_cast<variable*> (tree_.ptr + 4));
tree_nodes.ptr = (reinterpret_cast<tree_node*> (tree_.ptr + 4 + variables_count*sizeof(variable) + 4));
*reinterpret_cast<int *>(tree_.ptr) = variables_count;
memcpy(variables.ptr, new_variables, variables_count * sizeof(variable));
*reinterpret_cast<int *>(tree_.ptr + sizeof(int) + variables_count * sizeof(variable)) = nodes_count;
memcpy(tree_nodes.ptr, new_tree_nodes, nodes_count * sizeof(tree_node));
}
void ExpressionTree::copy_tree_nodes(int new_nodes_count, tree_node* new_tree_nodes) {
if (new_nodes_count > 0) ASSERT(new_tree_nodes);
nodes_count = new_nodes_count;
void* buff = tree_.ptr;
tree_.ptr = (char*) realloc(buff, sizeof(int) + variables_count * sizeof(variable) + sizeof(int) +
nodes_count * sizeof(tree_node));
variables.ptr = (reinterpret_cast<variable*> (tree_.ptr + 4));
tree_nodes.ptr = (reinterpret_cast<tree_node*> (tree_.ptr + 4 + variables_count*sizeof(variable) + 4));
*reinterpret_cast<int *>(tree_.ptr + sizeof(int) + variables_count * sizeof(variable)) = nodes_count;
memcpy(tree_nodes.ptr, new_tree_nodes, nodes_count * sizeof(tree_node));
}
bool ExpressionTree::copy_tree(const ExpressionTree& cp_tree) {
variables.ptr = nullptr;
tree_nodes.ptr = nullptr;
delete(tree_.ptr);
variables_count = cp_tree.variables_count;
nodes_count = cp_tree.nodes_count;
tree_.ptr = (char*) calloc(4 + 4 + variables_count*sizeof(variable) + nodes_count*sizeof(tree_node),
sizeof(char));
variables.ptr = (reinterpret_cast<variable*> (tree_.ptr + 4));
tree_nodes.ptr = (reinterpret_cast<tree_node*> (tree_.ptr + 4 + variables_count*sizeof(variable) + 4));
memcpy(tree_.ptr, cp_tree.tree_.ptr, 4 + 4 + variables_count*sizeof(variable) + nodes_count*sizeof(tree_node));
}
ExpressionTree::ExpressionTree(){
tree_.ptr = nullptr;
tree_nodes.ptr = nullptr;
variables.ptr = nullptr;
variables_count = 0;
nodes_count = 0;
}
ExpressionTree::~ExpressionTree(){
tree_nodes.ptr = nullptr;
variables.ptr = nullptr;
delete(tree_.ptr);
tree_.ptr = nullptr;
}
void ExpressionTree::read_tree (AutoFree<char>& buff, int expr_size) {
expr_size --;
buff.ptr[expr_size] = '$';
buff.ptr[expr_size + 1] = '\0';
Bor variables_bor;
my_vector<tree_node> tree;
char* variables_names[100];
for (int i = 0; i < 100; ++i) variables_names[i] = new char[100];
tree.push_back(tree_node());
int s = read_simple_expression (buff.ptr, op_defs, func_defs, variables_bor, variables_names, tree, 0);
ASSERT(s == expr_size);
int nodes_count = tree.size();
int variables_count = variables_bor.get_size();
variable* variables = new variable [variables_count];
for (int i = 0; i < variables_count; ++i) {
strcpy(variables[i].name, variables_names[i]);
}
generate_tree(variables_count, nodes_count, tree.data(), variables);
for (int i = 0; i < 100; ++i) delete(variables_names[i]);
}
void ExpressionTree::differentiate_tree(int k) {
my_vector<tree_node> new_tree;
new_tree.push_back(tree_node());
dfs_differentiate(new_tree, 0, 0, k);
copy_tree_nodes(new_tree.size(), new_tree.data());
}
void ExpressionTree::simplify_tree() {
my_vector<tree_node> new_tree;
new_tree.push_back(tree_node());
int f = 1;
while (f == 1) {
f = dfs_simplify(new_tree, 0, 0);
copy_tree_nodes(new_tree.size(), new_tree.data());
new_tree.clear();
new_tree.push_back(tree_node());
}
}
size_t ExpressionTree::print_latex_tree (MyString& str_buff) {
dfs_latex(0, str_buff);
return str_buff.size();
}
int ExpressionTree::get_priority(int index) const{
ASSERT (index >= 0);
ASSERT(index < nodes_count);
tree_node node = tree_nodes.ptr[index];
if (node.type != operator_node) {
return -1;
}
return op_defs.priorities[node.index];
}<file_sep>/differentiator_tree/expression_parser.cpp
#include "expression_parser.h"
int read_positive_int (const char* start, int& value) {
int pos = 0;
value = 0;
if (start[pos] < '0' || start[pos] > '9') return -1;
while (start[pos] >= '0' && start[pos] <= '9') {
value = value*10 + start[pos] - '0';
pos++;
}
return pos;
}
int read_int (const char* start, int& value) {
int pos = 0;
value = 0;
if (start[0] == '-') {
pos = 1;
int readed = read_positive_int(start + pos, value);
if (readed == -1) return -1;
value = - value;
return readed + 1;
}
else {
int readed = read_positive_int(start, value);
if (readed == -1) return -1;
return readed;
}
}
int read_double (const char* start,
my_vector<tree_node>& tree,
int start_pos) {
double value = 0;
int pos = 0;
while (start[pos] == ' ') pos++;
int mul = 1;
if (start[0] == '-') {
pos = 1;
mul = -1;
}
int first_part = 0;
int readed = read_positive_int(start + pos, first_part);
if (readed == -1) return -1;
if (start[pos + readed] == '.') {
int second_part = 0;
int second_readed = read_positive_int(start + pos + readed + 1, second_part);
if (second_readed == -1) return -1;
value = second_part;
for (int i = 0; i < second_readed; ++i) value /= 10;
value += first_part;
value *= mul;
pos = readed + second_readed + pos + 1;
while (start[pos] == ' ') pos++;
tree[start_pos] = tree_node(constant_node, 0, -1, -1, value);
return pos;
}
else {
value = first_part * mul;
pos = readed + pos;
while (start[pos] == ' ') pos++;
tree[start_pos] = tree_node(constant_node, 0, -1, -1, value);
return pos;
}
}
int read_simple_expression (const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos) {
return read_simple_expression_with_priority (start,
op_defs,
func_defs,
variables_bor,
variables_names,
tree,
start_pos, op_defs.max_priority);
}
int read_simple_expression_with_priority (const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos, int priority) {
size_t last_size = tree.size();
if (priority == 0) {
return read_unit(
start,
op_defs, func_defs,
variables_bor,
variables_names,
tree,
start_pos
);
}
int pos = 0;
int first_node = start_pos;
int f_l = read_simple_expression_with_priority (
start + pos,
op_defs, func_defs,
variables_bor,
variables_names,
tree,
first_node, priority - 1
);
if (f_l == -1) {
return -1;
}
pos = f_l;
while (true) {
int ans = op_defs.operators_bor.check_max(start + pos);
if (ans == -1 || op_defs.read_priorities[ans] != priority) {
return pos;
}
first_node = tree.size();
tree.push_back(tree[start_pos]);
int op_l = strlen(op_defs.operators_names[ans]);
int second_node = tree.size();
tree.push_back(tree_node());
int s_l = read_simple_expression_with_priority(
start + pos + op_l,
op_defs,
func_defs,
variables_bor,
variables_names,
tree,
second_node,
priority - 1
);
if (s_l == -1) {
tree.resize(last_size);
return -1;
}
tree[start_pos] = tree_node(operator_node, ans, first_node, second_node, 0);
pos += s_l + op_l;
}
}
int read_func(const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos) {
size_t last_size = tree.size();
int pos = 0;
while (start[pos] == ' ') pos++;
int cur_func = func_defs.functions_bor.check_max(start + pos);
if (cur_func == -1) {
return -1;
}
pos += strlen(func_defs.functions_names[cur_func]);
while (start[pos] == ' ') pos++;
if (start[pos] != '(') return -1;
pos += 1;
int link = tree.size();
tree.push_back(tree_node());
int exprlen = read_simple_expression(
start + pos,
op_defs,
func_defs,
variables_bor,
variables_names,
tree,
link
);
if (exprlen == -1) {
tree.resize(last_size);
return -1;
}
pos += exprlen;
while (start[pos] == ' ') pos++;
if (start[pos] != ')') {
tree.resize(last_size);
return -1;
}
pos++;
while (start[pos] == ' ') pos++;
tree[start_pos] = tree_node(function_node, cur_func, link, -1, 0);
return pos;
}
int read_var(const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos) {
int pos = 0;
while (start[pos] == ' ') pos++;
if (start[pos] < 'a' || start[pos] > 'z') return -1;
int length = 0;
while ((start[length + pos] >= 'a' && start[length + pos] <= 'z') ||
(start[length + pos] >= '0' && start[length + pos] <= '9')){
length++;
}
if (length > 99) return -1;
char str[MAX_NAME_SIZE];
strncpy(str, start + pos, length);
str[length] = '\0';
int ans = variables_bor.check(str);
if (ans == -1) {
ans = variables_bor.get_size();
variables_bor.add(str, ans);
strcpy(variables_names[ans], str);
}
tree[start_pos] = tree_node(variable_node, ans, -1, -1, 0);
pos += length;
while (start[pos] == ' ')
pos++;
return pos;
}
int read_unit(const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos) {
size_t last_size = tree.size();
int pos = 0;
while (start[pos] == ' ') pos++;
if (start[pos] == '(') {
pos++;
int readed = read_simple_expression(
start + pos,
op_defs,
func_defs,
variables_bor,
variables_names,
tree,
start_pos);
if (readed == -1) {
return -1;
}
pos += readed;
while (start[pos] == ' ') pos++;
if (start[pos] != ')') {
return -1;
}
pos++;
while (start[pos] == ' ') pos++;
return pos;
}
else if ((start[pos] >= '0' && start[pos] <= '9') || start[pos] == '-'){
return read_double(start, tree, start_pos);
}
else {
double val = 0;
int func_len = read_func(
start,
op_defs,
func_defs,
variables_bor,
variables_names,
tree,
start_pos);
if (func_len == -1) {
int var_index;
func_len = read_var(
start,
op_defs,
func_defs,
variables_bor,
variables_names,
tree,
start_pos);
}
return func_len;
}
}
<file_sep>/differentiator_tree/expression_parser.h
#ifndef DIFFERENTIATOR_EXPRESSION_PARSER_H
#define DIFFERENTIATOR_EXPRESSION_PARSER_H
#include "info.h"
#include "tree_node.h"
#include "../containers/my_string/my_string.h"
#include "../containers/my_vector/my_vector.h"
#include "../containers/auto_free/auto_free.h"
#include "../containers/bor/bor.h"
int read_positive_int (const char* start, int& value);
int read_int (const char* start, int& value);
int read_double (const char* start,
my_vector<tree_node>& tree,
int start_pos);
int read_unit(const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos);
int read_simple_expression (const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos);
int read_simple_expression_with_priority (const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos, int priority);
int read_func(const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos);
int read_var(const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos);
int read_unit(const char* start,
operators_definitions& op_defs,
functions_definitions& func_defs,
Bor& variables_bor,
char** variables_names,
my_vector<tree_node>& tree,
int start_pos);
#endif //DIFFERENTIATOR_EXPRESSION_PARSER_H
<file_sep>/CMakeFiles/print_tree.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/print_tree.dir/main_files/print_tree.cpp.o"
"print_tree"
"print_tree.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/print_tree.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/CMakeFiles/print_tree_latex.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/print_tree_latex.dir/main_files/LaTex_print.cpp.o"
"print_tree_latex"
"print_tree_latex.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/print_tree_latex.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/containers/auto_free/auto_free.cpp
#include "auto_free.h"
<file_sep>/CMakeFiles/diferentiator.dir/DependInfo.cmake
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
"/home/oleg/Public/Oleg/course_2/ded/differentiator/containers/auto_free/auto_free.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/containers/auto_free/auto_free.cpp.o"
"/home/oleg/Public/Oleg/course_2/ded/differentiator/containers/bor/bor.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/containers/bor/bor.cpp.o"
"/home/oleg/Public/Oleg/course_2/ded/differentiator/containers/my_string/my_string.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/containers/my_string/my_string.cpp.o"
"/home/oleg/Public/Oleg/course_2/ded/differentiator/containers/my_vector/my_vector.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/containers/my_vector/my_vector.cpp.o"
"/home/oleg/Public/Oleg/course_2/ded/differentiator/differentiator_tree/expression_parser.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/differentiator_tree/expression_parser.cpp.o"
"/home/oleg/Public/Oleg/course_2/ded/differentiator/differentiator_tree/expression_tree.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/differentiator_tree/expression_tree.cpp.o"
"/home/oleg/Public/Oleg/course_2/ded/differentiator/differentiator_tree/tree_dfs.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/differentiator_tree/tree_dfs.cpp.o"
"/home/oleg/Public/Oleg/course_2/ded/differentiator/main.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/main.cpp.o"
"/home/oleg/Public/Oleg/course_2/ded/differentiator/work_with_file_functions/file_work_functions.cpp" "/home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/diferentiator.dir/work_with_file_functions/file_work_functions.cpp.o"
)
set(CMAKE_CXX_COMPILER_ID "GNU")
# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
"containers"
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
)
# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")
<file_sep>/README.md
# Acram-alpha
Tool for differentiating expressions and printing results in LaTex
* pdflatex is required
### Input format:
* Input file(file with expression) and output file names should be given as arguments to the program
* Default input file name is input.txt, default output file name is output.txt.
* If there is only one file name it counts as input file. Output file name is default.
* If there are no file names input file and output file names are default.
##### Input expression format:
Expression in standart notation.
* Variables' names - length is lesser or equal than 99 characters,
characters are latin characters from a to z
and digits from 0 to 9. First character is latin. Examples: x1, er3.
* Numbers - real. Format is standard.
Examples: 2, 4.5, -3, -4.8.
* Mathematical operators:
* addition (+)
* multiplication (*)
* subtraction (-)
* division (/)
* exponentiation (^)
* Functions:
* sine (sin)
* cosine (cos)
* tangent (tan)
* natural logarithm (ln)
* exponent (exp)
* Expression example: sin(x^2) + cos(y*3)^4 - z.
### Output format:
.tex file with LaTex code, compilation files and .pdf files with derivatives of this expression for all variables.
<file_sep>/differentiator_tree/tree_node.h
//
// Created by oleg on 27.05.2020.
//
#ifndef DIFFERENTIATOR_TREE_NODE_H
#define DIFFERENTIATOR_TREE_NODE_H
const int MAX_NAME_SIZE = 100;
enum node_types {
empty_node = 0,
function_node = 1,
variable_node = 2,
constant_node = 3,
operator_node = 4
};
struct tree_node {
node_types type;
int index;
int first_link;
int second_link;
double value;
tree_node():
type(node_types(0)),
index(0),
first_link(0),
second_link(0),
value(0) {
}
tree_node(node_types type_, int index_, int first_link_, int second_link_, double value_):
type(type_),
index(index_),
first_link(first_link_),
second_link(second_link_),
value(value_) {
}
tree_node(double value_):
type(constant_node),
index(-1),
first_link(-1),
second_link(-1),
value(value_) {
}
~tree_node() = default;
};
#endif //DIFFERENTIATOR_TREE_NODE_H
<file_sep>/differentiator_tree/info.h
//
// Created by oleg on 16.12.2019.
//
#ifndef DIFFERENTIATOR_INFO_H
#include "../containers/bor/bor.h"
#include <cstring>
#include <cmath>
enum operators {
SUM,
SUB,
MUL,
DIV,
POW,
POW1
};
class operators_definitions {
public:
const int max_priority = 3;
const static int operators_count = 6;
char operators_names [operators_count] [10];
char operators_differentials [operators_count] [128];
size_t read_priorities [operators_count];
size_t priorities [operators_count];
int priorities_left [operators_count];
int priorities_right [operators_count];
Bor operators_bor;
operators_definitions() {
strcpy(operators_names[SUM], "+");
strcpy(operators_differentials[SUM], "dx1 + dx2");
operators_bor.add("+", SUM);
priorities[SUM] = 4;
priorities_left[SUM] = 4;
priorities_right[SUM] = 4;
read_priorities[SUM] = 3;
strcpy(operators_names[SUB], "-");
strcpy(operators_differentials[SUB], "dx1 - dx2");
operators_bor.add("-", SUB);
priorities[SUB] = 3;
priorities_left[SUB] = 4;
priorities_right[SUB] = 3;
read_priorities[SUB] = 3;
strcpy(operators_names[MUL], "*");
strcpy(operators_differentials[MUL], "(x2*dx1) + (x1*dx2)");
operators_bor.add("*", MUL);
priorities[MUL] = 2;
priorities_left[MUL] = 2;
priorities_right[MUL] = 2;
read_priorities[MUL] = 2;
strcpy(operators_names[DIV], "/");
strcpy(operators_differentials[DIV], "((x2*dx1) - (x1*dx2))/(x2*x2)");
operators_bor.add("/", DIV);
priorities[DIV] = 1;
priorities_left[DIV] = 4;
priorities_right[DIV] = 4;
read_priorities[DIV] = 2;
strcpy(operators_names[POW], "^");
strcpy(operators_differentials[POW], "(x2*(x1^(x2-1))) * dx1");
operators_bor.add("^", POW);
priorities[POW] = 0;
priorities_left[POW] = -1;
priorities_right[POW] = 4;
read_priorities[POW] = 1;
strcpy(operators_names[POW1], "@");
strcpy(operators_differentials[POW1], "(x1^x2) * (((x2 / x1) * dx1) + (ln(x1) * dx2))");
operators_bor.add("@", POW1);
priorities[POW1] = 0;
priorities_left[POW1] = 0;
priorities_right[POW1] = 0;
read_priorities[POW1] = 1;
}
double compute(operators op, double x1, double x2) {
switch (op) {
case SUM: return x1 + x2;
case SUB: return x1 - x2;
case MUL: return x1 * x2;
case DIV: return x1 / x2;
case POW: return pow(x1, x2);
}
}
};
enum functions {
SIN,
COS,
TAN,
SQRT,
LN,
EXP
};
class functions_definitions {
public:
const static int functions_count = 7;
char functions_names [functions_count] [10];
char function_differentials [functions_count] [128];
Bor functions_bor;
functions_definitions() {
strcpy(functions_names[SIN], "sin");
strcpy(function_differentials[SIN], "cos(x) * dx");
functions_bor.add("sin", SIN);
strcpy(functions_names[COS], "cos");
strcpy(function_differentials[COS], "((-1) * sin(x)) * dx");
functions_bor.add("cos", COS);
strcpy(functions_names[TAN], "tan");
strcpy(function_differentials[TAN], "(1 / (cos(x) * cos(x))) * dx");
functions_bor.add("tan", TAN);
strcpy(functions_names[SQRT], "sqrt");
strcpy(function_differentials[SQRT], "(1 / (2 * sqrt(x))) * dx");
functions_bor.add("sqrt", SQRT);
strcpy(functions_names[LN], "ln");
strcpy(function_differentials[LN], "(1/x) * dx");
functions_bor.add("ln", LN);
strcpy(functions_names[EXP], "exp");
strcpy(function_differentials[EXP], "x * dx");
functions_bor.add("exp", EXP);
}
double compute(functions op, double arg) {
switch (op) {
case SIN: return sin(arg);
case COS: return cos(arg);
case TAN: return tan(arg);
case SQRT: return sqrt(arg);
case LN: return log(arg);
case EXP: return exp(arg);
}
}
};
#define DIFFERENTIATOR_INFO_H
#endif //DIFFERENTIATOR_INFO_H
<file_sep>/containers/bor/bor.cpp
#include "bor.h"
Bor::Bor() {
size_ = 0;
zero_node_ = new bor_node;
}
Bor::~Bor() {
delete(zero_node_);
}
[[nodiscard]] size_t Bor::get_size() const {
return size_;
}
int Bor::add (const char* str, int value) {
size_++;
ASSERT(str);
bor_node* cur_node = zero_node_;
int i = 0;
while (str[i] != '\0' && str[i] != ':') {
ASSERT(str[i] >= 0);
if (cur_node->nodes[str[i]] == nullptr) {
cur_node->nodes[str[i]] = new bor_node;
}
cur_node = cur_node->nodes[str[i]];
++i;
}
cur_node->value = value;
return size_;
}
int Bor::check (const char* str) {
ASSERT(str);
bor_node* cur_node = zero_node_;
int i = 0;
while (str[i] != '\0' && str[i] != ':') {
ASSERT(str[i] >= 0);
if (cur_node->nodes[str[i]] == nullptr) {
return -1;
}
cur_node = cur_node->nodes[str[i]];
++i;
}
return cur_node -> value;
}
int Bor::check_max (const char* str) {
ASSERT(str);
ASSERT(str);
bor_node* cur_node = zero_node_;
int i = 0;
int val = -1;
while (str[i] != '\0' && str[i] != ':') {
ASSERT(str[i] >= 0);
if (cur_node->nodes[str[i]] == nullptr) {
return val;
}
cur_node = cur_node->nodes[str[i]];
if (cur_node -> value != -1) val = cur_node -> value;
++i;
}
return val;
}<file_sep>/asserts/my_assert.h
#ifndef DIFFERENTIATOR_MY_ASSERT_H
#define DIFFERENTIATOR_MY_ASSERT_H
#include <cstdio>
#include <iostream>
#ifndef PRINT_CHECKING
#define ASSERT(expr) if (!(expr)) throw std::exception()
#else
#define ASSERT(expr) std::cout<<"Checking " << #expr << std::endl; if (!(expr)) throw std::exception()
#endif
#endif //DIFFERENTIATOR_MY_ASSERT_H
<file_sep>/main.cpp
#include <cmath>
#include "containers/auto_free/auto_free.h"
#include "containers/my_string/my_string.h"
#include "differentiator_tree/expression_tree.h"
int main(int args, char* argv[]) {
AutoFree<char> buff;
const char* input_file;
const char* output_file;
if (args <= 1) input_file = "input.txt";
else input_file = argv[1];
if (args <= 2) output_file = "differentiated.tex";
else output_file = argv[2];
int expr_size = read_string_with_free_place(&buff, input_file, 2);
ExpressionTree my_tree;
my_tree.read_tree(buff, expr_size);
MyString latex_string("\\documentclass{article}\n\
\\usepackage[utf8]{inputenc}\n\
\\usepackage[T2A]{fontenc}\n\
\\usepackage[russian,english]{babel}\n\
\\usepackage{amssymb,amsmath,amsthm}\n\
\\begin{document}\n\
\\par Derivatives\n\
\\begin{gather*}\n");
for (int i = 0; i < my_tree.variables_count; ++i) {
ExpressionTree diff_tree;
diff_tree.copy_tree(my_tree);
latex_string.add_string("F_{");
latex_string.add_string(my_tree.variables.ptr[i].name);
latex_string.add_string("} = ");
diff_tree.differentiate_tree(i);
diff_tree.simplify_tree();
diff_tree.print_latex_tree(latex_string);
latex_string.add_string("\\\\\n");
}
latex_string.add_string("\\end{gather*}\n\
\\end{document}\n");
print_buff(latex_string, output_file);
MyString query("pdflatex ");
query.add_string(output_file);
system(query.data());
return 0;
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(differentiator)
set(CMAKE_CXX_STANDARD 17)
include_directories("containers")
add_executable(diferentiator main.cpp
differentiator_tree/expression_parser.h differentiator_tree/expression_parser.cpp
asserts/my_assert.h
containers/my_string/my_string.h containers/my_string/my_string.cpp
containers/my_vector/my_vector.h containers/my_vector/my_vector.cpp
containers/bor/bor.h containers/bor/bor.cpp
containers/auto_free/auto_free.h containers/auto_free/auto_free.cpp
work_with_file_functions/file_work_functons.h work_with_file_functions/file_work_functions.cpp
differentiator_tree/info.h
differentiator_tree/expression_tree.h differentiator_tree/expression_tree.cpp
differentiator_tree/tree_dfs.cpp)<file_sep>/CMakeFiles/simplify_tree.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/simplify_tree.dir/main_files/simplifier.cpp.o"
"simplify_tree"
"simplify_tree.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/simplify_tree.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/differentiator_tree/expression_tree.h
#ifndef DIFFERENTIATOR_EXPRESSION_TREE_H
#define DIFFERENTIATOR_EXPRESSION_TREE_H
#include "info.h"
#include "../work_with_file_functions/file_work_functons.h"
#include "../containers/my_string/my_string.h"
#include "../containers/my_vector/my_vector.h"
#include "../containers/auto_free/auto_free.h"
#include "../containers/bor/bor.h"
#include "expression_parser.h"
#include "tree_node.h"
struct variable {
char name[MAX_NAME_SIZE];
double value;
};
class ExpressionTree {
public:
AutoFree<tree_node> tree_nodes;
AutoFree<variable> variables;
int variables_count;
int nodes_count;
operators_definitions op_defs;
functions_definitions func_defs;
ExpressionTree(const ExpressionTree&) = delete;
void operator=(const ExpressionTree&) = delete;
void generate_tree(int& new_variables_count, int& new_nodes_count,
tree_node* new_tree_nodes, variable* new_variables);
void copy_tree_nodes(int new_nodes_count, tree_node* new_tree_nodes);
bool copy_tree(const ExpressionTree& cp_tree);
ExpressionTree();
~ExpressionTree();
void read_tree (AutoFree<char>& buff, int expr_size);
void differentiate_tree(int k);
void simplify_tree();
size_t print_latex_tree (MyString& str_buff);
private:
int get_priority(int index) const;
int dfs_find (int cur_node, int k);
int dfs_count (int cur_node, double& value);
int dfs_latex (int cur_node, MyString& str_buff);
int dfs_copy (my_vector<tree_node>& new_tree,
int cur_tree_node,
int cur_new_tree_node);
int dfs_differentiate (my_vector<tree_node>& new_tree,
int cur_tree_node,
int cur_new_tree_node,
int diff_var);
int dfs_simplify (my_vector<tree_node>& new_tree,
int cur_tree_node,
int cur_new_tree_node);
AutoFree<char> tree_;
};
#endif //DIFFERENTIATOR_EXPRESSION_TREE_H
<file_sep>/Makefile
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.16
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /snap/clion/112/bin/cmake/linux/bin/cmake
# The command to remove a file.
RM = /snap/clion/112/bin/cmake/linux/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/oleg/Public/Oleg/course_2/ded/differentiator
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/oleg/Public/Oleg/course_2/ded/differentiator
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/snap/clion/112/bin/cmake/linux/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..."
/snap/clion/98/bin/cmake/linux/bin/ccmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles /home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /home/oleg/Public/Oleg/course_2/ded/differentiator/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named diferentiator
# Build rule for target.
diferentiator: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 diferentiator
.PHONY : diferentiator
# fast build rule for target.
diferentiator/fast:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/build
.PHONY : diferentiator/fast
containers/auto_free/auto_free.o: containers/auto_free/auto_free.cpp.o
.PHONY : containers/auto_free/auto_free.o
# target to build an object file
containers/auto_free/auto_free.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/auto_free/auto_free.cpp.o
.PHONY : containers/auto_free/auto_free.cpp.o
containers/auto_free/auto_free.i: containers/auto_free/auto_free.cpp.i
.PHONY : containers/auto_free/auto_free.i
# target to preprocess a source file
containers/auto_free/auto_free.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/auto_free/auto_free.cpp.i
.PHONY : containers/auto_free/auto_free.cpp.i
containers/auto_free/auto_free.s: containers/auto_free/auto_free.cpp.s
.PHONY : containers/auto_free/auto_free.s
# target to generate assembly for a file
containers/auto_free/auto_free.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/auto_free/auto_free.cpp.s
.PHONY : containers/auto_free/auto_free.cpp.s
containers/bor/bor.o: containers/bor/bor.cpp.o
.PHONY : containers/bor/bor.o
# target to build an object file
containers/bor/bor.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/bor/bor.cpp.o
.PHONY : containers/bor/bor.cpp.o
containers/bor/bor.i: containers/bor/bor.cpp.i
.PHONY : containers/bor/bor.i
# target to preprocess a source file
containers/bor/bor.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/bor/bor.cpp.i
.PHONY : containers/bor/bor.cpp.i
containers/bor/bor.s: containers/bor/bor.cpp.s
.PHONY : containers/bor/bor.s
# target to generate assembly for a file
containers/bor/bor.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/bor/bor.cpp.s
.PHONY : containers/bor/bor.cpp.s
containers/my_string/my_string.o: containers/my_string/my_string.cpp.o
.PHONY : containers/my_string/my_string.o
# target to build an object file
containers/my_string/my_string.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/my_string/my_string.cpp.o
.PHONY : containers/my_string/my_string.cpp.o
containers/my_string/my_string.i: containers/my_string/my_string.cpp.i
.PHONY : containers/my_string/my_string.i
# target to preprocess a source file
containers/my_string/my_string.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/my_string/my_string.cpp.i
.PHONY : containers/my_string/my_string.cpp.i
containers/my_string/my_string.s: containers/my_string/my_string.cpp.s
.PHONY : containers/my_string/my_string.s
# target to generate assembly for a file
containers/my_string/my_string.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/my_string/my_string.cpp.s
.PHONY : containers/my_string/my_string.cpp.s
containers/my_vector/my_vector.o: containers/my_vector/my_vector.cpp.o
.PHONY : containers/my_vector/my_vector.o
# target to build an object file
containers/my_vector/my_vector.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/my_vector/my_vector.cpp.o
.PHONY : containers/my_vector/my_vector.cpp.o
containers/my_vector/my_vector.i: containers/my_vector/my_vector.cpp.i
.PHONY : containers/my_vector/my_vector.i
# target to preprocess a source file
containers/my_vector/my_vector.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/my_vector/my_vector.cpp.i
.PHONY : containers/my_vector/my_vector.cpp.i
containers/my_vector/my_vector.s: containers/my_vector/my_vector.cpp.s
.PHONY : containers/my_vector/my_vector.s
# target to generate assembly for a file
containers/my_vector/my_vector.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/containers/my_vector/my_vector.cpp.s
.PHONY : containers/my_vector/my_vector.cpp.s
differentiator_tree/expression_parser.o: differentiator_tree/expression_parser.cpp.o
.PHONY : differentiator_tree/expression_parser.o
# target to build an object file
differentiator_tree/expression_parser.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/expression_parser.cpp.o
.PHONY : differentiator_tree/expression_parser.cpp.o
differentiator_tree/expression_parser.i: differentiator_tree/expression_parser.cpp.i
.PHONY : differentiator_tree/expression_parser.i
# target to preprocess a source file
differentiator_tree/expression_parser.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/expression_parser.cpp.i
.PHONY : differentiator_tree/expression_parser.cpp.i
differentiator_tree/expression_parser.s: differentiator_tree/expression_parser.cpp.s
.PHONY : differentiator_tree/expression_parser.s
# target to generate assembly for a file
differentiator_tree/expression_parser.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/expression_parser.cpp.s
.PHONY : differentiator_tree/expression_parser.cpp.s
differentiator_tree/expression_tree.o: differentiator_tree/expression_tree.cpp.o
.PHONY : differentiator_tree/expression_tree.o
# target to build an object file
differentiator_tree/expression_tree.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/expression_tree.cpp.o
.PHONY : differentiator_tree/expression_tree.cpp.o
differentiator_tree/expression_tree.i: differentiator_tree/expression_tree.cpp.i
.PHONY : differentiator_tree/expression_tree.i
# target to preprocess a source file
differentiator_tree/expression_tree.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/expression_tree.cpp.i
.PHONY : differentiator_tree/expression_tree.cpp.i
differentiator_tree/expression_tree.s: differentiator_tree/expression_tree.cpp.s
.PHONY : differentiator_tree/expression_tree.s
# target to generate assembly for a file
differentiator_tree/expression_tree.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/expression_tree.cpp.s
.PHONY : differentiator_tree/expression_tree.cpp.s
differentiator_tree/tree_dfs.o: differentiator_tree/tree_dfs.cpp.o
.PHONY : differentiator_tree/tree_dfs.o
# target to build an object file
differentiator_tree/tree_dfs.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/tree_dfs.cpp.o
.PHONY : differentiator_tree/tree_dfs.cpp.o
differentiator_tree/tree_dfs.i: differentiator_tree/tree_dfs.cpp.i
.PHONY : differentiator_tree/tree_dfs.i
# target to preprocess a source file
differentiator_tree/tree_dfs.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/tree_dfs.cpp.i
.PHONY : differentiator_tree/tree_dfs.cpp.i
differentiator_tree/tree_dfs.s: differentiator_tree/tree_dfs.cpp.s
.PHONY : differentiator_tree/tree_dfs.s
# target to generate assembly for a file
differentiator_tree/tree_dfs.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/differentiator_tree/tree_dfs.cpp.s
.PHONY : differentiator_tree/tree_dfs.cpp.s
main.o: main.cpp.o
.PHONY : main.o
# target to build an object file
main.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/main.cpp.o
.PHONY : main.cpp.o
main.i: main.cpp.i
.PHONY : main.i
# target to preprocess a source file
main.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/main.cpp.i
.PHONY : main.cpp.i
main.s: main.cpp.s
.PHONY : main.s
# target to generate assembly for a file
main.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/main.cpp.s
.PHONY : main.cpp.s
work_with_file_functions/file_work_functions.o: work_with_file_functions/file_work_functions.cpp.o
.PHONY : work_with_file_functions/file_work_functions.o
# target to build an object file
work_with_file_functions/file_work_functions.cpp.o:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/work_with_file_functions/file_work_functions.cpp.o
.PHONY : work_with_file_functions/file_work_functions.cpp.o
work_with_file_functions/file_work_functions.i: work_with_file_functions/file_work_functions.cpp.i
.PHONY : work_with_file_functions/file_work_functions.i
# target to preprocess a source file
work_with_file_functions/file_work_functions.cpp.i:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/work_with_file_functions/file_work_functions.cpp.i
.PHONY : work_with_file_functions/file_work_functions.cpp.i
work_with_file_functions/file_work_functions.s: work_with_file_functions/file_work_functions.cpp.s
.PHONY : work_with_file_functions/file_work_functions.s
# target to generate assembly for a file
work_with_file_functions/file_work_functions.cpp.s:
$(MAKE) -f CMakeFiles/diferentiator.dir/build.make CMakeFiles/diferentiator.dir/work_with_file_functions/file_work_functions.cpp.s
.PHONY : work_with_file_functions/file_work_functions.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... rebuild_cache"
@echo "... edit_cache"
@echo "... diferentiator"
@echo "... containers/auto_free/auto_free.o"
@echo "... containers/auto_free/auto_free.i"
@echo "... containers/auto_free/auto_free.s"
@echo "... containers/bor/bor.o"
@echo "... containers/bor/bor.i"
@echo "... containers/bor/bor.s"
@echo "... containers/my_string/my_string.o"
@echo "... containers/my_string/my_string.i"
@echo "... containers/my_string/my_string.s"
@echo "... containers/my_vector/my_vector.o"
@echo "... containers/my_vector/my_vector.i"
@echo "... containers/my_vector/my_vector.s"
@echo "... differentiator_tree/expression_parser.o"
@echo "... differentiator_tree/expression_parser.i"
@echo "... differentiator_tree/expression_parser.s"
@echo "... differentiator_tree/expression_tree.o"
@echo "... differentiator_tree/expression_tree.i"
@echo "... differentiator_tree/expression_tree.s"
@echo "... differentiator_tree/tree_dfs.o"
@echo "... differentiator_tree/tree_dfs.i"
@echo "... differentiator_tree/tree_dfs.s"
@echo "... main.o"
@echo "... main.i"
@echo "... main.s"
@echo "... work_with_file_functions/file_work_functions.o"
@echo "... work_with_file_functions/file_work_functions.i"
@echo "... work_with_file_functions/file_work_functions.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>/containers/my_vector/my_vector.h
#ifndef DIFFERENTIATOR_MY_VECTOR_H
#define DIFFERENTIATOR_MY_VECTOR_H
#include <cstdint>
#include <iostream>
#define DEBUG false
#define CHECK if (DEBUG && check()) dump(check(), __FILE__, __LINE__, __FUNCTION__);
template <typename T>
class my_vector {
private:
enum my_vector_err_code {
ok = 0,
sizes_broken = 1,
buff_broken = 2,
buff_pointer_broken = 3
};
struct stack_buffer {
int first_canary;
int buff_size_copy;
int size_copy;
int hsh;
int size;
int buff_size;
T buff[1];
};
int first_canary_;
stack_buffer* buff_;
int second_canary_;
int* second_canary_ptr () {
return reinterpret_cast<int*> (reinterpret_cast<char*>(buff_) +
4*6 + sizeof(T) * buff_->buff_size + 1);
}
void dump (int err_code, const char file[], int line, const char function[]) {
std::cerr<<"Problem!!! From "<<file<<", line "<<line<<", "<<function<<std::endl;
std::cerr<<"Problem in my_stack<T> where T = ";
const char* str = typeid(T).name();
int pos = 0;
while ('0' <= str[pos] && str[pos] <= '9') ++pos;
std::cerr<<str + pos;
std::cerr<<std::endl;
if (err_code == buff_pointer_broken) {
std::cerr<<"Buffer pointer is broken"<<std::endl;
std::cerr<<"First canary = "<<first_canary_;
if (first_canary_ == 265) std::cerr<<"(alive)."<<std::endl;
else std::cerr<<"(dead)."<<std::endl;
std::cerr<<"Second canary = "<<second_canary_;
if (second_canary_ == 265) std::cerr<<"(alive)."<<std::endl;
else std::cerr<<"(dead)."<<std::endl;
std::cerr<<"Buffer pointer is "<<buff_<<std::endl;
}
else if (err_code == sizes_broken) {
std::cerr<<"Sizes are broken"<<std::endl;
std::cerr<<"First buff canary = "<<buff_->first_canary;
if (buff_->first_canary == 265) std::cerr<<"(alive)."<<std::endl;
else std::cerr<<"(dead)."<<std::endl;
std::cerr<<"Second buff canary = "<<*(reinterpret_cast<int*>(buff_) +
4 * 6 + 4 + buff_->buff_size * sizeof(T));
if (*second_canary_ptr() == 265) std::cerr<<"(alive)."<<std::endl;
else std::cerr<<"(dead)."<<std::endl;
std::cerr<<"Buffer pointer is "<<buff_<<std::endl;
std::cerr<<"size values:"<<std::endl;
std::cerr<<buff_->size<<"(original) "<<buff_->size_copy<<"(copy)"<<std::endl;
std::cerr<<"buff_size values:"<<std::endl;
std::cerr<<buff_->buff_size<<"(original) "<<buff_->buff_size_copy<<"(copy)"<<std::endl;
}
else if (err_code == buff_broken) {
std::cerr<<"Buff is broken"<<std::endl;
std::cerr<<"First buff canary = "<<buff_->first_canary;
if (buff_->first_canary == 265) std::cerr<<"(alive)."<<std::endl;
else std::cerr<<"(dead)."<<std::endl;
std::cerr<<"Second buff canary = "<<*(reinterpret_cast<int*>(buff_) +
4 * 6 + 1+ 4 + buff_->buff_size * sizeof(T));
if (*second_canary_ptr() == 265) std::cerr<<"(alive)."<<std::endl;
else std::cerr<<"(dead)."<<std::endl;
std::cerr<<"Buffer pointer is "<<buff_<<std::endl;
std::cerr<<"size value:"<<std::endl;
std::cerr<<buff_->size<<std::endl;
std::cerr<<"buff_size value:"<<std::endl;
std::cerr<<buff_->buff_size<<std::endl;
std::cerr<<"Buffer:"<<std::endl;
for (int i = 0; i < buff_->buff_size; ++i) {
if (i < buff_->size) std::cerr<<"*";
std::cerr<<"buff["<<i<<"] = "<<std::endl;
}
}
else std::cerr<<"Unknown error"<<std::endl;
throw std::exception();
}
my_vector_err_code check() {
if (first_canary_ != 265 || second_canary_ != 265 || (!buff_))
return buff_pointer_broken;
if (buff_->size != buff_->size_copy || buff_->buff_size != buff_->buff_size_copy)
return sizes_broken;
if (buff_->size < 0 || buff_->buff_size <= 0 || buff_->size > buff_->buff_size)
return sizes_broken;
if (buff_->first_canary != 265 ||
*second_canary_ptr() != 265)
{
return buff_broken;
}
return ok;
}
public:
my_vector():
first_canary_(265),
second_canary_(265) {
buff_ = (stack_buffer*) calloc(4 * 6 + 1 + 4 + 10 * sizeof(T), 1);
buff_ -> first_canary = 265;
buff_ -> buff_size = 10;
buff_ -> size = 0;
buff_ -> buff_size_copy = buff_->buff_size;
*second_canary_ptr() = 265;
}
~my_vector() {
CHECK
free(buff_);
}
void push_back(T elem) {
CHECK
if (buff_->size == buff_->buff_size) {
buff_->buff_size *= 2;
buff_ = (stack_buffer*) realloc(buff_, 4 * 6 + 1 + 4 + buff_->buff_size * sizeof(T));
*second_canary_ptr() = 265;
}
buff_->buff[buff_->size] = elem;
buff_->size++;
buff_ -> buff_size_copy = buff_->buff_size;
buff_ -> size_copy = buff_->size;
CHECK
}
bool pop_back() {
CHECK
if (buff_->size <= 0) return false;
buff_->size--;
buff_->buff[buff_->size].~T();
if (buff_->size * 2 >= 4 && buff_->size * 4 < buff_->buff_size) {
buff_->buff_size = buff_->size * 2;
buff_ = (stack_buffer*) realloc(buff_, 4 * 6 + 1 + 4 + buff_->buff_size * sizeof(T));
*second_canary_ptr() = 265;
}
buff_ -> buff_size_copy = buff_->buff_size;
buff_ -> size_copy = buff_->size;
CHECK
return true;
}
void resize (size_t new_size) {
if (new_size < buff_->size) {
for (int i = new_size; i < buff_->size; ++i) {
buff_->buff[i].~T();
}
}
buff_->size = new_size;
if ((new_size >= 2 && new_size * 4 < buff_->buff_size) || (new_size > buff_->buff_size)) {
buff_->buff_size = new_size * 2;
buff_ = (stack_buffer*) realloc(buff_, 4 * 6 + 1 + 4 + buff_->buff_size * sizeof(T));
*second_canary_ptr() = 265;
}
}
void clear() {
CHECK
for (int i = 0; i < buff_->size; ++i) {
buff_->buff[i].~T();
}
buff_ = (stack_buffer*) calloc(4 * 6 + 1 + 4 + 10 * sizeof(T), 1);
buff_ -> first_canary = 265;
buff_ -> buff_size = 10;
buff_ -> size = 0;
buff_ -> buff_size_copy = buff_->buff_size;
*second_canary_ptr() = 265;
}
T& back() {
CHECK
if (buff_->size <= 0) return 0;
return buff_->buff[buff_->size - 1];
}
size_t size() {
CHECK
return buff_->size;
}
T& operator [] (size_t index) {
ASSERT(index < size());
return buff_->buff[index];
}
T* data() {
CHECK
return buff_->buff;
}
};
#endif //DIFFERENTIATOR_MY_VECTOR_H
<file_sep>/CMakeFiles/diferentiator.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/diferentiator.dir/containers/auto_free/auto_free.cpp.o"
"CMakeFiles/diferentiator.dir/containers/bor/bor.cpp.o"
"CMakeFiles/diferentiator.dir/containers/my_string/my_string.cpp.o"
"CMakeFiles/diferentiator.dir/containers/my_vector/my_vector.cpp.o"
"CMakeFiles/diferentiator.dir/differentiator_tree/expression_parser.cpp.o"
"CMakeFiles/diferentiator.dir/differentiator_tree/expression_tree.cpp.o"
"CMakeFiles/diferentiator.dir/differentiator_tree/tree_dfs.cpp.o"
"CMakeFiles/diferentiator.dir/main.cpp.o"
"CMakeFiles/diferentiator.dir/work_with_file_functions/file_work_functions.cpp.o"
"diferentiator"
"diferentiator.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/diferentiator.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/containers/my_string/my_string.h
#ifndef DIFFERENTIATOR_MY_STRING_H
#define DIFFERENTIATOR_MY_STRING_H
#include <string_view>
#include <cstdio>
#include <cstring>
#include <iostream>
#include "../../asserts/my_assert.h"
class MyString {
public:
MyString();
explicit MyString(const char* origin);
~MyString();
MyString(const MyString&) = delete;
void operator=(const MyString&) = delete;
void add_string (const char* add);
void add_int (const int add_value);
[[nodiscard]] const char* data() const;
[[nodiscard]] size_t size() const;
private:
char* data_;
size_t taken_;
size_t size_;
};
#endif //DIFFERENTIATOR_MY_STRING_H
<file_sep>/work_with_file_functions/file_work_functions.cpp
#include "file_work_functons.h"
size_t read_file (AutoFree<char> *buff, const char* input_name){
ASSERT(buff);
ASSERT(input_name);
FILE *input_file = nullptr;
input_file = fopen(input_name, "r");
ASSERT(input_file);
ASSERT(fseek(input_file, 0L, SEEK_END) == 0);
long size = ftell(input_file);
ASSERT(size >= 0);
ASSERT(fseek(input_file, 0L, SEEK_SET) == 0);
(*buff).ptr = (char *) calloc(size + 1, sizeof(char));
if (fread((*buff).ptr, sizeof(char), size + 1, input_file) != size + 1) {
ASSERT(feof(input_file));
}
ASSERT(fclose(input_file) == 0);
++size;
char *cur_buff_symbol = (*buff).ptr + (size - 2);
while (size > 1 && *cur_buff_symbol == '\0') {
--size;
--cur_buff_symbol;
}
return size;
}
void clear_output(const char *output_name) {
ASSERT(output_name);
FILE *file = fopen(output_name, "w");
ASSERT(file);
ASSERT(fclose(file) == 0);
}
void print_buff(size_t size, AutoFree <char> *buff, const char *output_name) {
ASSERT(buff);
ASSERT(output_name);
FILE *file = fopen(output_name, "a");
ASSERT(file);
for (int i = 0; i < size; i++) {
if (i == 0 || (*buff).ptr[i - 1] == '\0') {
ASSERT(fputs((*buff).ptr + i, file) != EOF);
fputc('\n', file);
ASSERT(!ferror(file));
}
}
ASSERT(fclose(file) == 0);
}
void print_buff(MyString& buff, const char *output_name) {
ASSERT(output_name);
FILE *file = fopen(output_name, "w");
ASSERT(file);
fwrite(buff.data(), sizeof(char), buff.size(), file);
ASSERT(!ferror(file));
ASSERT(fclose(file) == 0);
}
size_t read_string_with_free_place (AutoFree<char> *buff, const char* input_name, int elems_to_reserve){
ASSERT(buff);
ASSERT(input_name);
FILE *input_file = nullptr;
input_file = fopen(input_name, "rb");
ASSERT(input_file);
ASSERT(fseek(input_file, 0L, SEEK_END) == 0);
long size = ftell(input_file)/sizeof(char);
ASSERT(size >= 0);
ASSERT(fseek(input_file, 0L, SEEK_SET) == 0);
(*buff).ptr = (char *) calloc(size + elems_to_reserve + 1, sizeof(char));
if (fread((*buff).ptr, sizeof(char), size + 1, input_file) != size + 1) {
ASSERT(feof(input_file));
}
ASSERT(fclose(input_file) == 0);
return size;
}<file_sep>/containers/auto_free/auto_free.h
#ifndef DIFFERENTIATOR_AUTO_FREE_H
#define DIFFERENTIATOR_AUTO_FREE_H
template <class T>
class AutoFree {
public:
AutoFree() {
ptr = nullptr;
}
~AutoFree() {
if (ptr != nullptr)
free(ptr);
}
AutoFree(const AutoFree&) = delete;
void operator=(const AutoFree&) = delete;
T* ptr;
};
#endif //DIFFERENTIATOR_AUTO_FREE_H
<file_sep>/CMakeFiles/count_expression.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/count_expression.dir/main_files/count_tree.cpp.o"
"count_expression"
"count_expression.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/count_expression.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/cmake-build-debug/CMakeFiles/read_expr.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/read_expr.dir/main_files/reader.cpp.o"
"read_expr"
"read_expr.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/read_expr.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/containers/bor/bor.h
#ifndef DIFFERENTIATOR_BOR_H
#define DIFFERENTIATOR_BOR_H
#include "../../asserts/my_assert.h"
class Bor {
public:
Bor();
~Bor();
[[nodiscard]] size_t get_size() const;
int add (const char* str, int value);
int check (const char* str);
int check_max (const char* str);
private:
struct bor_node {
bor_node* nodes[128];
int value;
bor_node() {
for (int i = 0; i < 128; ++i)
nodes[i] = nullptr;
value = -1;
}
~bor_node() {
for (int i = 0; i < 128; ++i)
if (nodes[i] != nullptr) delete(nodes[i]);
}
};
size_t size_;
bor_node* zero_node_;
};
#endif //DIFFERENTIATOR_BOR_H<file_sep>/differentiator_tree/tree_dfs.cpp
#include "info.h"
#include "expression_tree.h"
const double eps = 0.001;
bool is_equal_to (double a, double b) {
return ((a - eps <= b) && (a + eps >= b));
}
bool is_zero (double a) {
return is_equal_to(a, 0);
}
bool is_one (double a) {
return is_equal_to(a, 1);
}
int ExpressionTree::dfs_count (int cur_node, double& value) {
ASSERT(cur_node >= 0);
tree_node node = tree_nodes.ptr[cur_node];
switch (node.type) {
case function_node: {
ASSERT(node.index >= 0);
ASSERT(node.first_link >= 0);
ASSERT(node.second_link == -1);
double first_value = 0;
dfs_count(node.first_link, first_value);
value = func_defs.compute(functions(node.index), first_value);
}
break;
case operator_node: {
ASSERT(node.index >= 0);
ASSERT(node.first_link >= 0);
ASSERT(node.second_link >= 0);
double first_value = 0, second_value = 0;
dfs_count(node.first_link, first_value);
dfs_count(node.second_link, second_value);
value = op_defs.compute(operators(node.index), first_value, second_value);
}
break;
case variable_node: {
ASSERT(node.index >= 0);
value = variables.ptr[node.index].value;
}
break;
case constant_node: {
value = node.value;
}
break;
}
return 0;
}
int ExpressionTree::dfs_find (int cur_node,
int k) {
ASSERT(cur_node >= 0);
tree_node node = tree_nodes.ptr[cur_node];
int result = 0;
if (node.type == variable_node)
if (node.index == k)
return 1;
if (node.first_link != -1) {
if (dfs_find(node.first_link, k))
result = 1;
}
if (node.second_link != -1) {
if (dfs_find(node.second_link, k))
result = 1;
}
return result;
}
int ExpressionTree::dfs_copy (my_vector<tree_node>& new_tree,
int cur_tree_node,
int cur_new_tree_node) {
tree_node node = tree_nodes.ptr[cur_tree_node];
new_tree[cur_new_tree_node] = node;
if (node.first_link != -1) {
new_tree[cur_new_tree_node].first_link = new_tree.size();
new_tree.push_back(tree_node());
dfs_copy(new_tree, node.first_link, new_tree.size() - 1);
}
if (node.second_link != -1) {
new_tree[cur_new_tree_node].second_link = new_tree.size();
new_tree.push_back(tree_node());
dfs_copy(new_tree, node.second_link, new_tree.size() - 1);
}
return 0;
}
int ExpressionTree::dfs_differentiate (my_vector<tree_node>& new_tree,
int cur_tree_node,
int cur_new_tree_node,
int diff_var) {
ASSERT(cur_tree_node >= 0);
ASSERT(cur_new_tree_node >= 0);
tree_node node = tree_nodes.ptr[cur_tree_node];
int last_size = new_tree.size();
switch (node.type) {
case function_node: {
ASSERT(node.index >= 0);
ASSERT(node.first_link >= 0);
ASSERT(node.second_link == -1);
Bor cur_bor;
const int x = 0;
const int dx = 1;
cur_bor.add("x", x);
cur_bor.add("dx", dx);
char*temp[100];
for (int i = 0; i < 10; ++i) {temp[i] = new char[100]; temp[i][0] = 0;}
int res = read_simple_expression(func_defs.function_differentials[node.index],
op_defs,
func_defs,
cur_bor,
temp,
new_tree,
cur_new_tree_node);
int cur_size = new_tree.size();
for (int i = last_size; i < cur_size; ++i) {
if(new_tree[i].type == variable_node) {
switch(new_tree[i].index) {
case x: {
dfs_copy(new_tree, node.first_link, i);
}
break;
case dx: {
if (!dfs_find(node.first_link, diff_var)) {
new_tree[i] = tree_node( 0);
}
else dfs_differentiate(new_tree, node.first_link, i, diff_var);
}
break;
}
}
}
}
break;
case operator_node: {
Bor cur_bor;
const int x1 = 0;
const int dx1 = 1;
const int x2 = 2;
const int dx2 = 3;
cur_bor.add("x1", x1);
cur_bor.add("dx1", dx1);
cur_bor.add("x2", x2);
cur_bor.add("dx2", dx2);
char** temp = nullptr;
if (node.index == POW) {
if (dfs_find(node.second_link, diff_var)) {
node.index = POW1;
}
}
int res = read_simple_expression(op_defs.operators_differentials[node.index],
op_defs,
func_defs,
cur_bor,
temp,
new_tree,
cur_new_tree_node);
int cur_size = new_tree.size();
for (int i = last_size; i < cur_size; ++i) {
if(new_tree[i].type == variable_node) {
switch(new_tree[i].index) {
case x1: {
dfs_copy(new_tree, node.first_link, i);
}
break;
case dx1: {
if (!dfs_find(node.first_link, diff_var)) {
new_tree[i] = tree_node( 0);
}
else dfs_differentiate(new_tree, node.first_link, i, diff_var);
}
break;
case x2: {
dfs_copy(new_tree, node.second_link, i);
}
break;
case dx2: {
if (!dfs_find(node.second_link, diff_var)) {
new_tree[i] = tree_node( 0);
}
else dfs_differentiate(new_tree, node.second_link, i, diff_var);
}
break;
}
}
}
}
break;
case variable_node: {
ASSERT(node.index >= 0);
if (node.index == diff_var) {
new_tree[cur_new_tree_node] = tree_node(1);
}
else
new_tree[cur_new_tree_node] = tree_node(0);
}
break;
case constant_node: {
new_tree[cur_new_tree_node] = tree_node( 0);
}
break;
default:
break;
}
return 0;
}
int ExpressionTree::dfs_simplify (my_vector<tree_node>& new_tree,
int cur_tree_node,
int cur_new_tree_node) {
ASSERT(cur_tree_node >= 0);
ASSERT(cur_new_tree_node >= 0);
tree_node node = tree_nodes.ptr[cur_tree_node];
int last_size = new_tree.size();
int ret_val = 0;
switch (node.type) {
case function_node: {
ASSERT(node.index >= 0);
ASSERT(node.first_link >= 0);
ASSERT(node.second_link == -1);
if (tree_nodes.ptr[node.first_link].type == constant_node) {
new_tree[cur_new_tree_node] = tree_node(
func_defs.compute(functions(node.index), tree_nodes.ptr[node.first_link].value));
ret_val = 1;
}
else{
new_tree[cur_new_tree_node] = node;
new_tree[cur_new_tree_node].first_link = new_tree.size();
new_tree.push_back(tree_node());
if (dfs_simplify(new_tree,
node.first_link,
new_tree.size() - 1))
ret_val = 1;
}
}
break;
case operator_node: {
bool fl = false;
if (tree_nodes.ptr[node.first_link].type == constant_node)
{
if (tree_nodes.ptr[node.second_link].type == constant_node)
{
new_tree[cur_new_tree_node] = tree_node(
op_defs.compute(operators(node.index),
tree_nodes.ptr[node.first_link].value,
tree_nodes.ptr[node.second_link].value));
fl = true;
ret_val = 1;
}
else {
switch (node.index) {
case SUM:
{
if (is_zero(tree_nodes.ptr[node.first_link].value)) {
dfs_simplify(new_tree,
node.second_link,
cur_new_tree_node);
fl = true;
ret_val = 1;
}
}
break;
case MUL:
{
if (is_one(tree_nodes.ptr[node.first_link].value)) {
dfs_simplify(new_tree,
node.second_link,
cur_new_tree_node);
fl = true;
ret_val = 1;
}
if (is_zero(tree_nodes.ptr[node.first_link].value)) {
new_tree[cur_new_tree_node] = tree_node(0);
fl = true;
ret_val = 1;
}
}
break;
case DIV:
{
if (is_zero(tree_nodes.ptr[node.first_link].value)) {
new_tree[cur_new_tree_node] = tree_node(0);
fl = true;
ret_val = 1;
}
}
break;
default:
break;
}
}
}
else if (tree_nodes.ptr[node.second_link].type == constant_node) {
switch (node.index) {
case SUM:
{
if (is_zero(tree_nodes.ptr[node.second_link].value)) {
dfs_simplify(new_tree,
node.first_link,
cur_new_tree_node);
fl = true;
ret_val = 1;
}
}
break;
case SUB:
{
if (is_zero(tree_nodes.ptr[node.second_link].value)) {
dfs_simplify(new_tree,
node.first_link,
cur_new_tree_node);
fl = true;
ret_val = 1;
}
}
break;
case MUL:
{
if (is_one(tree_nodes.ptr[node.second_link].value)) {
dfs_simplify(new_tree,
node.first_link,
cur_new_tree_node);
fl = true;
ret_val = 1;
}
if (is_zero(tree_nodes.ptr[node.second_link].value)) {
new_tree[cur_new_tree_node] = tree_node(0);
fl = true;
ret_val = 1;
}
}
break;
case DIV:
{
ASSERT(!is_zero(tree_nodes.ptr[node.second_link].value));
}
break;
case POW:
{
if (is_zero(tree_nodes.ptr[node.second_link].value)) {
new_tree[cur_new_tree_node] = tree_node(1);
fl = true;
ret_val = 1;
}
if (is_one(tree_nodes.ptr[node.second_link].value)) {
dfs_simplify(new_tree,
node.first_link,
cur_new_tree_node);
fl = true;
ret_val = 1;
}
}
break;
}
}
if (!fl) {
new_tree[cur_new_tree_node] = node;
new_tree[cur_new_tree_node].first_link = new_tree.size();
new_tree.push_back(tree_node());
if (dfs_simplify(new_tree,
node.first_link,
new_tree.size() - 1))
ret_val = 1;
new_tree[cur_new_tree_node].second_link = new_tree.size();
new_tree.push_back(tree_node());
if (dfs_simplify(new_tree,
node.second_link,
new_tree.size() - 1))
ret_val = 1;
}
}
break;
default: {
new_tree[cur_new_tree_node] = node;
}
}
return ret_val;
}
int ExpressionTree::dfs_latex (int cur_node, MyString& str_buff) {
ASSERT(cur_node >= 0);
tree_node node = tree_nodes.ptr[cur_node];
switch (node.type) {
case function_node: {
ASSERT(node.index >= 0);
ASSERT(node.first_link >= 0);
ASSERT(node.second_link == -1);
double first_value = 0;
str_buff.add_string(func_defs.functions_names[node.index]);
str_buff.add_string("\\left(");
dfs_latex(node.first_link, str_buff);
str_buff.add_string("\\right)");
}
break;
case operator_node: {
ASSERT(node.index >= 0);
ASSERT(node.first_link >= 0);
ASSERT(node.second_link >= 0);
bool left_brace = op_defs.priorities_left[node.index] < get_priority(node.first_link);
bool right_brace = op_defs.priorities_right[node.index] < get_priority(node.second_link);
if (node.index == DIV) {
str_buff.add_string(" \\frac {");
}
if (left_brace) {
str_buff.add_string("\\left(");
}
dfs_latex(node.first_link, str_buff);
if (left_brace) {
str_buff.add_string("\\right)");
}
switch (node.index) {
case DIV: {
str_buff.add_string("} {");
} break;
case MUL: {
str_buff.add_string(" \\cdot ");
} break;
case SUM: {
str_buff.add_string(" + ");
} break;
case SUB: {
str_buff.add_string(" - ");
} break;
case POW: {
str_buff.add_string(" ^ {");
}
}
if (right_brace) {
str_buff.add_string("\\left(");
}
dfs_latex(node.second_link, str_buff);
if (right_brace) {
str_buff.add_string("\\right)");
}
if (node.index == DIV || node.index == POW) {
str_buff.add_string("}");
}
}
break;
case variable_node: {
ASSERT(node.index >= 0);
str_buff.add_string(variables.ptr[node.index].name);
}
break;
case constant_node: {
char c[128];
snprintf(c, 127, "%.4g", node.value);
str_buff.add_string(c);
}
break;
default:
break;
}
return 0;
}
<file_sep>/work_with_file_functions/file_work_functons.h
#ifndef DIFFERENTIATOR_FILE_WORK_FUNCTONS_H
#define DIFFERENTIATOR_FILE_WORK_FUNCTONS_H
#include "../asserts/my_assert.h"
#include "../containers/my_string/my_string.h"
#include "../containers/my_vector/my_vector.h"
#include "../containers/auto_free/auto_free.h"
#include "../containers/bor/bor.h"
size_t read_file (AutoFree<char> *buff, const char* input_name);
void clear_output(const char *output_name);
void print_buff(size_t size, AutoFree <char> *buff, const char *output_name);
void print_buff(MyString& buff, const char *output_name);
size_t read_string_with_free_place (AutoFree<char>* buff, const char* input_name, int elems_to_reserve);
#endif //DIFFERENTIATOR_FILE_WORK_FUNCTONS_H
<file_sep>/CMakeFiles/differentiate_tree.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/differentiate_tree.dir/main_files/differentiator.cpp.o"
"differentiate_tree"
"differentiate_tree.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/differentiate_tree.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/CMakeFiles/read_expression.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/read_expression.dir/main_files/reader.cpp.o"
"read_expression"
"read_expression.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/read_expression.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/containers/my_string/my_string.cpp
#include "my_string.h"
MyString::MyString(): data_(reinterpret_cast<char*>(calloc(16, sizeof(char)))),
size_(0),
taken_(16) {
}
MyString::MyString(const char* origin) {
size_ = strlen(origin);
taken_ = size_;
if (taken_ < 16) {
taken_ = 16;
}
data_ = reinterpret_cast<char*>(calloc(taken_, sizeof(char)));
strcpy(data_, origin);
}
MyString::~MyString() {
free(data_);
}
void MyString::add_string (const char* add) {
ASSERT(add);
if (size_ + strlen(add) + 2 >= taken_) {
taken_ += std::max(taken_, strlen(add));
data_ = (char*) realloc(data_, taken_);
}
strcpy(data_ + size_, add);
size_ += strlen(add);
}
void MyString::add_int (const int add_value) {
char add[17];
sprintf(add, "%d", add_value);
add_string(add);
}
[[nodiscard]] const char* MyString::data() const {
return data_;
}
[[nodiscard]] size_t MyString::size() const{
return size_;
}
|
37bdd7fa7ad251e5d4912c3febbb1f89590b8071
|
[
"CMake",
"Markdown",
"Makefile",
"C",
"C++"
] | 30 |
C++
|
9OMShitikov/acram-alpha
|
7b4439e7f2efcc3d47c81343fee127cfaf7754c2
|
ab9669611b92a299dc0eb6342857f4a77c786df3
|
refs/heads/main
|
<repo_name>ojjy/spark_practices<file_sep>/Regressions/pysparkRegressions.py
from pyspark.sql import SparkSession
from pyspark import SparkContext, SparkConf
conf_spark = SparkConf().set("spark.driver.host", "127.0.0.1")
sc = SparkContext(conf=conf_spark)
spark = SparkSession.builder.appName('Cusomers').getOrCreate()
from pyspark.ml.regression import LinearRegression
dataset = spark.read.csv("customer.csv", inferSchema=True, header=True)
print(dataset)
dataset.show()
dataset.printSchema()
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
featureassembler = VectorAssembler(inputCols=["Avg Session Length","Time on App","Time on Website","Length of Membership"],outputCol="Independent Features")
output = featureassembler.transform(dataset)
output.show()
output.select("Independent Features").show()
print(output.columns)
finalized_data = output.select("Independent Features","Yearly Amount Spent")
finalized_data.show()
train_data,test_data=finalized_data.randomSplit([0.75,0.25])
regressor=LinearRegression(featuresCol='Independent Features', labelCol='Yearly Amount Spent')
regressor=regressor.fit(train_data)
print(regressor.coefficients)
(regressor.intercept)
pred_results = regressor.evaluate(test_data)
pred_results.predictions.show(40)
|
597257e9af5deb3397058ee59bdb396f001e31d5
|
[
"Python"
] | 1 |
Python
|
ojjy/spark_practices
|
8ca64a836de5b01951a9a6c1fa2528ff027a2cc7
|
183d804170ae9c7b20d47bfce9e5c41a95b79c87
|
refs/heads/master
|
<file_sep># FinalRound_SandBox_Demiurge
## Major project for Final Year (2018): A web browser based on JavaFX, which implements the sandbox property!!
The elaborate description will follow, but some key points before that:<br />
1. The sandboxing feature for downloads works in Linux version, hence the windows version is simply a web browser thing.<br />
2. There are 2 branches currently (25-06-2019 1004 hrs): <br />
- master<br />
- branch_LINUX_department<br />
The LINUX branch is the branch containing all the important and up-to-date code, as is dedicated totally for Linux.
So, if you wanna checkout a branch, this is the branch to look forward to, and **not** the master.
<file_sep>import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
/**
* @author Vivek
* @version 1.0
* @since 30-03-2018
*/
public class Albedo_Browser_Downloads extends Application {
public static class DownloadRecord {
int number;
String title;
String downloadTimeStamp;
long downloadTimeStampLong;
boolean commitStatus;
public DownloadRecord() {
}
public DownloadRecord(int number, String title, String downloadTimeStamp, long downloadTimeStampLong) {
this.number = number;
this.title = title;
this.downloadTimeStamp = downloadTimeStamp;
this.downloadTimeStampLong = downloadTimeStampLong;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDownloadTimeStamp() {
return downloadTimeStamp;
}
public void setDownloadTimeStamp(String downloadTimeStamp) {
this.downloadTimeStamp = downloadTimeStamp;
}
public boolean isCommitStatus() {
return commitStatus;
}
public void setCommitStatus(boolean commitStatus) {
this.commitStatus = commitStatus;
}
public long getDownloadTimeStampLong() {
return downloadTimeStampLong;
}
public void setDownloadTimeStampLong(long downloadTimeStampLong) {
this.downloadTimeStampLong = downloadTimeStampLong;
}
}
private class ButtonCell extends TableCell<DownloadRecord, Boolean> {
final Button cellButton = new Button();
ButtonCell() {
localCounter++;
//cellButton.setText("Commit"+localCounter);
buttonMapper.put(cellButton, localCounter);
cellButton.setText("Commit");
cellButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
// do something when button clicked
System.out.println("fileLocationMapper : " + fileLocationMapper);
System.out.println("Firing up from the button click of commit, src : " + t.getSource());
//System.out.println("\tlocalcounter : "+localCounter+", fileLocationMapper val : "+fileLocationMapper.get(localCounter));
//the above approach failed...so trying a new format of fileLocationMapper and button
//the localCounter is apt only for the time of init the buttons, and not for accessing them afterwards
Button caller = (Button) t.getSource();
System.out.println("Button mapping : " + (buttonMapper.get(caller)));
File srcFile = fileLocationMapper.get(buttonMapper.get(caller));
System.out.println("\tFile loc mapping : " + srcFile.getName() + " --> " + srcFile.toPath());
System.out.println("Firing the file commiting ~ transferring");
cellButton.setDisable(true);
new Thread(new Runnable() {
@Override
public void run() {
try {
Files.copy(srcFile.toPath(), Paths.get(downloadFileDirectory_OutBoxPath + srcFile.getName()), StandardCopyOption.REPLACE_EXISTING);
srcFile.delete();
System.out.println("Completed file transfer and deleted the source file!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("FAILURE IN COPYING / DELETING THE FILE WHICH REQUESTED COMMIT");
}
}
}).start();
}
});
}
//Display button if the row is not empty
@Override
protected void updateItem(Boolean t, boolean empty) {
super.updateItem(t, empty);
if (!empty) {
setGraphic(cellButton);
}
}
}
private static ObservableList<DownloadRecord> data = null;
//FXCollections.observableArrayList(new DownloadRecord(1, "Titleeeeeeeeeeeeeeeeeeeeeeeeeee", "Visited Time"));
static int localCounter = 0;
static Map<Integer, File> fileLocationMapper = new HashMap<>();
static Map<Button, Integer> buttonMapper = new HashMap<>();
private static String downloadFileDirectoryPath = "e:\\sandbox_target\\tmp\\";
private static String downloadFileDirectory_OutBoxPath = "e:\\sandbox_outbox\\";
public static void fillData() {
int tr = 1;
if (data != null) data.clear();
localCounter = -2;
File file = new File(downloadFileDirectoryPath);
File filesList[] = file.listFiles();
for (File f1 : filesList) {
System.out.println("File name --> " + f1);
DownloadRecord node = new DownloadRecord();
node.setNumber(tr);
node.setTitle(f1.getName());
try {
//Path localFile = Paths.get("resources/RESIZED_ic_refresh_black_48dp_2x.png");
Path localFile = Paths.get(f1.getPath());
BasicFileAttributes attributes = Files.readAttributes(localFile, BasicFileAttributes.class);
System.out.println("File creation time : " + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format((attributes.lastModifiedTime().toMillis())));
System.out.println("file ccr : " + attributes.lastModifiedTime().toMillis());
node.setDownloadTimeStamp(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format((attributes.lastModifiedTime().toMillis())));
node.setDownloadTimeStampLong(attributes.lastModifiedTime().toMillis());
} catch (Exception e) {
System.out.println("Error encountered while reading file attribute...\n\tException" + e);
node.setDownloadTimeStamp("N.A.");
node.setDownloadTimeStampLong(0);
}
node.setCommitStatus(false);
if (data == null) data = FXCollections.observableArrayList(node);
else data.add(node);
//mapping the number to the file downloaded
fileLocationMapper.put(tr, f1);
tr++;
}
/*
DownloadRecord node = new DownloadRecord();
node.setNumber(1);
node.setTitle("first.pdf");
node.setDownloadTimeStamp(String.valueOf(new Timestamp(System.currentTimeMillis())));
node.setCommitStatus(false);
//localCounter++;
node = new DownloadRecord();
node.setNumber(2);
node.setTitle("second.pdf");
node.setDownloadTimeStamp(String.valueOf(new Timestamp(System.currentTimeMillis())));
node.setCommitStatus(true);
//localCounter++;
data.add(node);
*/
}
public static void clearDownloads() {
//wiping out the downloads folder
File file = new File(downloadFileDirectoryPath);
File filesList[] = file.listFiles();
int i = 0;
//File filesListArray[] = new File[filesList.length];
for (File f1 : filesList) {
System.out.println("\t\tFile " + (++i) + " to be deleted : " + f1);
f1.delete();
//filesListArray[i++] = f1;
}
/*
for(i=0;i<filesListArray.length;i++){
filesListArray[i].delete();
}
*/
System.out.println("Exiting the clear Downloads function");
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("DOWNLOADS");
primaryStage.setWidth(800);
VBox vBox = new VBox();
TableView table = new TableView();
table.setEditable(false);
TableColumn recordNumberCol = new TableColumn("Record number");
recordNumberCol.setCellValueFactory(new PropertyValueFactory<>("number"));
TableColumn siteNameCol = new TableColumn("Site name");
siteNameCol.setCellValueFactory(new PropertyValueFactory<>("title"));
TableColumn lastVisitedTimeCol = new TableColumn("Time of visit");
lastVisitedTimeCol.setCellValueFactory(new PropertyValueFactory<>("downloadTimeStamp"));
TableColumn commitButtonCol = new TableColumn("Commit Status");
commitButtonCol.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<DownloadRecord, Boolean>,
ObservableValue<Boolean>>() {
@Override
public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<DownloadRecord, Boolean> p) {
return new SimpleBooleanProperty(p.getValue() != null);
}
});
commitButtonCol.setCellFactory(
new Callback<TableColumn<DownloadRecord, Boolean>, TableCell<DownloadRecord, Boolean>>() {
@Override
public TableCell<DownloadRecord, Boolean> call(TableColumn<DownloadRecord, Boolean> p) {
return new ButtonCell();
}
});
table.getColumns().addAll(recordNumberCol, siteNameCol, lastVisitedTimeCol, commitButtonCol);
Collections.sort(data, new Comparator<DownloadRecord>() {
@Override
public int compare(DownloadRecord o1, DownloadRecord o2) {
return (int) (o2.getDownloadTimeStampLong() - o1.getDownloadTimeStampLong());
}
});
int tr = data.size();
for (DownloadRecord record : data) {
record.setNumber(tr--);
}
table.setItems(data);
vBox.getChildren().addAll(table);
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
System.out.println("Stage is closing");
Albedo_Browser.downloadsFrameOpen = false;
}
});
}
public static void main(String[] args) {
fillData();
launch(args);
}
}
<file_sep>import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
/**
* @author Vivek
* @version 1.0
* @since 29-03-2018
*/
public class Albedo_Browser_History extends Application {
public static class HistoryRecord {
int number;
String title;
String visitTimeStamp;
public HistoryRecord() {
}
public HistoryRecord(int number, String title, String visitTimeStamp) {
this.number = number;
this.title = title;
this.visitTimeStamp = visitTimeStamp;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getVisitTimeStamp() {
return visitTimeStamp;
}
public void setVisitTimeStamp(String visitTimeStamp) {
this.visitTimeStamp = visitTimeStamp;
}
}
private static ObservableList<HistoryRecord> data = null;
//FXCollections.observableArrayList(new DownloadRecord(1, "Titleeeeeeeeeeeeeeeeeeeeeeeeeee", "Visited Time"));
public static void fillData(WebEngine webEngine) {
WebHistory history = webEngine.getHistory();
ObservableList<WebHistory.Entry> list = history.getEntries();
int tr = 1;
if(data!=null) data.clear();
for (WebHistory.Entry entry : list) {
System.out.println("Entry " + tr + " --> " + entry.getTitle() + " :: " + entry.getUrl() + " :: " + entry.getLastVisitedDate());
HistoryRecord node = new HistoryRecord();
node.setNumber(tr);
try {
node.setTitle(entry.getTitle());
} catch (NullPointerException e1){
node.setTitle("null");
}
try {
node.setVisitTimeStamp(entry.getLastVisitedDate().toString());
} catch (NullPointerException e1){
node.setVisitTimeStamp("null");
}
if (data == null) {
data = FXCollections.observableArrayList(node);
} else {
data.add(node);
}
tr++;
}
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("HISTORY");
primaryStage.setWidth(800);
VBox vBox = new VBox();
TableView table = new TableView();
table.setEditable(false);
TableColumn recordNumberCol = new TableColumn("Record number");
recordNumberCol.setCellValueFactory(new PropertyValueFactory<>("number"));
TableColumn siteNameCol = new TableColumn("Site name");
siteNameCol.setCellValueFactory(new PropertyValueFactory<>("title"));
TableColumn lastVisitedTimeCol = new TableColumn("Time of visit");
lastVisitedTimeCol.setCellValueFactory(new PropertyValueFactory<>("visitTimeStamp"));
table.getColumns().addAll(recordNumberCol, siteNameCol, lastVisitedTimeCol);
table.setItems(data);
vBox.getChildren().addAll(table);
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
System.out.println("Stage is closing");
Albedo_Browser.historyFrameOpen = false;
}
});
}
public static void main(String[] args) {
launch(args);
}
}
|
a0d46465d3a7501ce7c54ac6cf8bb2ecfd77c1b2
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
crackCodeLogn/FinalRound_SandBox_Demiurge
|
4c97c4515ce4ac95bdce839091591e7a5ee63807
|
604f891d2064720a91e4a862c5400ed1c4909033
|
refs/heads/master
|
<file_sep>
import java.net.*;
import java.util.Date;
import java.io.*;
public class ServerHealthConnection extends Thread {
boolean listening = true;
ServerSocket serverSocket = null;
//TaskProducer taskProducer;
Boolean isAlive=false;
@Override
public void run() {
try {
// first i have tried with socket programming in which I am able to check alive port or not
// InetAddress host = InetAddress.getLocalHost();
// Socket socket = null;
// ObjectInputStream ois = null;
// socket = new Socket(host.getHostName(), 12345);
// InputStream is = socket.getInputStream();
// InputStreamReader isReader = new InputStreamReader(is);
// BufferedReader br = new BufferedReader(isReader);
//
// //code to read and print headers
// String headerLine = null;
// while((headerLine = br.readLine()).length() != 0){
// System.out.println(headerLine);
// }
//Second Method
// I have tried with service consuming way
URL url = new URL("http://localhost:12345");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode()+" Getting Error from server ");
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
System.out.println( "Success : HTTP code : "+ conn.getResponseCode()+" Getting Success from server ");
conn.disconnect();
// Thread.sleep(5 * 1000);
// serverSocket.close();
} catch (final IOException e) {
System.err.println("Could not listen on port: 12345.");
e.printStackTrace();
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
public void close() {
try {
serverSocket.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
while (true) {
ServerHealthConnection d1=new ServerHealthConnection();
d1.setDaemon(true);
d1.start();
Thread.sleep(5 * 1000);
}
}
}
|
b3c77bdb461506a48f9a3e35be8443bcced47eea
|
[
"Java"
] | 1 |
Java
|
kirti765/SauceLab
|
7cac250e68336f939c7bfdaaf20b99f5aaec73cb
|
8c44d6a11b6b809207a1296502726abaddeb9db8
|
refs/heads/master
|
<file_sep>import React, {useContext, useState} from 'react'
import listContext from '../Store/list_context'
import {appInstance} from '../Helpers/api_requests'
import history from '../Helpers/history'
import styles from '../Stylesheets/Store.module.css'
import btStyles from '../Stylesheets/Orders.module.css'
import awStyles from '../Stylesheets/Order.module.css'
import cartStyles from '../Stylesheets/Cart.module.css'
import {Link} from 'react-router-dom'
export default function Cart(){
const cart = useContext(listContext)
const [notes, setNotes] = useState()
const itemList = cart.items.map( (item, index) => {
return (
<div key={index} className={cartStyles.itemContainer}>
<p className={cartStyles.info}>{item.name} {'x'+item.amount} - {item.price * item.amount}$ </p>
{<RemoveButton item={item} />}
</div>
)
})
function handleClick(){
const items = []
cart.items.map( item => {
items.push({
item_id: item.id,
quantity: item.amount
})
return null
})
appInstance.post('/orders/', {
customer: localStorage.getItem('user'),
notes: notes,
items: items
})
.then(response => {
console.log(response)
history.push('/success')
})
.catch(error => {
console.log(error)
history.push('/error')
})
}
if (itemList.length > 0){
return(
<div>
<BackButton />
{itemList}
<hr />
<div className={cartStyles.container}>
{cart.getTotal()}
<textarea className={awStyles.notes}placeholder="Feel free to write any extra requests here." value={notes} onChange={e => setNotes(e.target.value)}></textarea>
<button className={awStyles.orderBtn} onClick={handleClick}>Confirm your order.</button>
</div>
</div>
)
}
else {
return (
<div>
<h1 className={styles.container}>Cart is empty</h1>
<BackButton />
</div>
)
}
}
function BackButton(){
return (
<Link to='/make-order/'>
<button className={btStyles.button} style={{backgroundColor: "#f7f7f7"}}>
Go back
</button>
</Link>
)
}
function RemoveButton(props){
const cart = useContext(listContext)
return(
<button className={awStyles.button} onClick={ () => cart.removeItem(props.item)}>
<i className="far fa-times-circle"></i>
</button>
)
}
<file_sep>import React from 'react'
import {Link} from 'react-router-dom'
import styles from '../Stylesheets/Store.module.css'
export default function StartOrder() {
return (
<Link className={styles.container} to='/make-order'>
<button className={styles.button}>Start ordering! </button>
</Link>
)
}
<file_sep>import React, {useState, useEffect, useContext} from 'react'
import {appInstance} from '../Helpers/api_requests'
import listContext from '../Store/list_context'
import {Link} from 'react-router-dom'
import btStyles from '../Stylesheets/Button.module.css'
import orStyles from '../Stylesheets/Order.module.css'
export default function MakeOrder(){
return (
<Items />
)
}
function Items(){
const [category, setCategory] = useState(0)
const [categories, setCategories] = useState()
useEffect(() => {
appInstance.get('/categories')
.then(response => setCategories(response.data))
.catch(error => console.log(error))
},[])
const [items, setItems] = useState()
useEffect(() => {
appInstance.get('/items')
.then(response => setItems(response.data))
.catch(error => console.log(error))
},[category])
function filterItems(item){
return (category === 0 || item.category === category) && item.in_stock
}
return (
<div>
<div className={btStyles.container}>
<button className={btStyles.filterButton} onClick={() => setCategory(0)}>Show all</button>
{categories == null ? "" : categories.map(cat => <Category key={cat.id} fn={setCategory} category={cat}/>)}
<Link to='/cart'>
<button style={{backgroundColor: "#428f38"}} className={btStyles.filterButton}>
<i style={{fontSize:"20px"}} className="fas fa-shopping-cart">Cart</i>
</button>
</Link>
</div>
<div className={orStyles.container} style={{gridGap: "5px", backgroundColor:"#e8e8e8", marginTop: "10px"}}>
{items == null ? <h1>Loading</h1> : items.filter(filterItems).map(item => <Item key={item.id} item={item}/>)}
</div>
</div>
)
}
function Category(props){
return(
<button className={btStyles.filterButton} onClick={() => props.fn(props.category.id)}>{props.category.name}</button>
)
}
function Item(props){
const cart = useContext(listContext)
const amount = cart.items.find( item => item.id === props.item.id)
return (
<div className={orStyles.container}>
<h1>{props.item.name}</h1>
<h2>{props.item.price}$</h2>
<div>
<ContextButton item={props.item} icon='fas fa-plus' fn={cart.incItem} />
<ContextButton item={props.item} icon='fas fa-minus' fn={cart.decItem} />
</div>
<h2>{amount == null ? 0 : amount.amount}x</h2>
</div>
)
}
function ContextButton(props){
return(
<button className={orStyles.button} onClick={() => props.fn(props.item)}>
<i className={props.icon}></i>
</button>
)
}
<file_sep>import React, {useEffect} from 'react'
import {GroupRedirect} from '../Login'
import styles from '../Stylesheets/Store.module.css'
export default function Success(){
useEffect(() => {
setTimeout(() => {
GroupRedirect(localStorage.getItem('group'))
}, 5000)
},[])
return(
<h1 className={styles.container}>Your order was a success!</h1>
)
}
<file_sep>import axios from 'axios'
import history from './history'
const baseURL = `${process.env.REACT_APP_HOST_IP_ADDRESS}/api/`
export const authInstance = axios.create({
baseURL: `${baseURL}auth-token/`,
})
export const appInstance = axios.create({
baseURL: baseURL
})
appInstance.interceptors.request.use( config => {
const token = localStorage.getItem('token')
config.headers.Authorization = `Token ${token}`
return config
})
appInstance.interceptors.response.use( response => {
return response
}, error => {
if (error.response.status !== 401){
return new Promise( (_resolve, reject) => {
reject(error)
})
}
localStorage.clear()
history.push('/login')
})
|
deb1e03e80d0dafca04ef25a3f85dcf847f3e361
|
[
"JavaScript"
] | 5 |
JavaScript
|
SoTeKie/iwb-react
|
6cba76b4cbe34dc445b31b0274ca3a16b6e535dc
|
15f5e483ac160a8cd0c725045296bd87aeedf162
|
refs/heads/master
|
<file_sep>$(function(){
$(".argument .conclusion").each(function(){
if($(this).children(".inference").length == 0){
$(this).prepend("<span class='inference'></span>");
}
});
})<file_sep>ArgunetPresentation
===================
a presentation framework for presenting argument reconstructions and argument maps.
A Demo can be found here: http://christianvoigt.github.io/ArgunetPresentation/
Visit http://www.argunet.org for more information about argument mapping software and argument reconstruction.
Argunet Browser is released under the MIT license. http://en.wikipedia.org/wiki/MIT_License
1. How to create a presentation
-------------------------------
Just start from index.html and delete everything within
<div id='presentation'></div>.
Then start by adding
<section></section>
elements.
ArgunetPresentation uses section elements as slides. You can use h1, h2 and h3 to give your section titles. You can define the first slide as a title slide if you add the class "title" to it.
Within each section, you can animate your presentation. Each slide can contain their own animation timeline. a slide's animation timeline consists of a series of steps. At each steps you can animate as many elements as you like and you can animate them in different ways. You insert an animation step by adding adding "data-step='stepNr'" to one or several elements. All you have left to do is to give these elements one of the following css classes to define how you want them to change at this step in the animation timeline:
###Add an element
<element class="add" data-step="stepNr"> </element>
Add an Element to the slide at stepNr. These elements will be hidden at the beginning and displayed when their step comes.
###Remove an element
<element class="remove" data-step="stepNr"> </element>
Removes an Element from the slide at stepNr. These elements will be shown at the beginning and hidden when their step comes.
###Substitute an element
<element class="substitute" data-step="stepNr" data-target="id"> </element>
Substitutes this Element for the Element with the id at stepNr. This is especially useful for rephrasing and adapting premises step by step.
###Highlight an element
<element class="highlight" data-step="stepNr"> </element>
Highlight this Element at stepNr. The background of these elements will turn yellow when their step comes.
###Adding comments
<element class="comment" data-step="stepNr"></element>
Adds a comment at stepNr. Comments are displayed beside the slide. This is useful for displaying an argument reconstruction side by side with its evaluation or by explaining specific steps in the reconstruction process.
By default, only one comment at a time will be displayed. But you can use all other animation step types within a comment. That makes it possible to expand a comment with .add elements step by step (or substituting parts of it).
###Adding arguments, theses and quotes to your presentation
```
<ol class="argument">
<li>This is a premise</li>
<li class="conclusion">This is a conclusion</li>
<li class="assumption">This is an assumption</li>
<li class="conclusion"><span class="inference">Inference Rule, Sentences used: 2&3</span>This is a conclusion with an inference rule.</li>
</ol>
<div class='thesis'><h4>Title</h4>This is a claim.</div>
<blockquote><p>This is a source text.</p><p class="source"><NAME>, Readme for Argunet Presentation, 2013</p></blockquote>
```
As with every kind of element, you can add the animation step types described above to every part of an argument. So you could start out with just one premise and one conclusion and fill in the other premises and conclusions step by step. You can even change some text within a premise by using:
<li> A premise: <span id='first-version'>All truths</span> are subjective. <span class="substitute" data-step='1' data-target='first-version'>Some truths</span></li>
##2. How to create a print version of your presentation
Argunet Presentation has a print mode that allows you to print out your presentation or to create a PDF file of it. By default Argunet Presentation's print mode does not display animation steps as single slides to keep the page number small. But you can manually customize the print display by adding special css classes for print to your elements. This makes the print mode very flexible and makes it easy to transform your presentation into a concise and nice-looking handout.
###Print step element as extra slide
<element class="print" data-step="stepNr"> </element>
Inserts an extra slide for this step.
###Remove element from print mode
<element class="no-print"> </element>
Removes this element from the print version.
###Show element in print mode only
<element class="print-only"> </element>
Displays this element only in the print mode and removes it from the browser mode. </dd>
###Transform .substitute element into .add element in print mode
<element class="substitute print-as-add"> </element> ```</dt>
This will change the step type to .add in print mode. This is useful because otherwise .substitute steps will prevent the steps they are substituting from being displayed at all if the .substitute step has no .print class (so that it is added as an extra slide).
###Manual page breaks
Use "style='page-break-after:always;'" and "style='page-break-before:always;'" to insert manual page breaks in your document.<file_sep>//namespace:
this.argunet = this.argunet||{};
argunet.ArgunetPresentation = function(settings){
this.presentation = (settings && settings.element)? $(settings.element).addClass("argunet presentation") : $(".argunet.presentation").first();
var listeners = (settings && settings.listeners)? settings.listeners : undefined;
this.stepController = new argunet.StepController(listeners);
var transition = (settings && settings.transition)? settings.transition : "right";
this.transitionController = new argunet.TransitionController(transition);
if(window.location.hash == "#print"){ // print mode
new argunet.ArgunetPresentationForPrint(this.stepController);
return;
}
$(this.presentation).find(".print-only").remove();
var that = this;
this.currentSlideNr = 0;
this.currentStepNr = 0;
this.slides = $("section");
var menu = $("<div id='menu'><h3>Slides</h3><div class='content'></div></div>").appendTo(this.presentation);
var navigation = $("<nav id='navigation'><a href='#' class='open'><img src='src/css/images/menu.png' style='height:1em;' /></a><div class='content'><a href='' class='back'><span>Back</span></a> <div class='info'></div> <a href='' class='forward'><span>Forward</span></a> <a href='#print' target='_blank'><img src='src/css/images/printer.png' style='height:1em;' /></a></div></nav> <a class='logo' href='http://www.argunet.org'><img src='src/css/images/argunet-logo.png' style='width:5em'/></a>").appendTo(this.presentation);
//navigation for touch screens
$("#navigation .back").click(function(){
that.previous();
return false;
});
$("#navigation .forward").click(function(){
that.next();
return false;
});
//nav button
$(menu).hide();
$(navigation).children(".content").hide();
var cont = $(navigation).children(".content");
$(cont).css("marginRight",-$(cont).outerWidth());
$(navigation).children(".open").click(function(){
if(cont.is(":hidden")){
cont.css('marginRight',-cont.outerWidth());
cont.show().animate({marginRight: 0});
}else{
cont.show().animate({marginRight: -cont.outerWidth()},{complete:function(){cont.hide();}});
}
$(menu).toggle();
return false;
});
//menu
menu.click(function(){
if($(this).is(".active"))$(this).transition({x:"0px"}).removeClass("active");
else{
$(this).transition({x:"-11em"});
$(this).addClass("active");
}
});
//slide list
var i=1;
$(this.slides).each(function(i){
//if this slide contains no comments, make it full-width
if($(this).find(".comment").length == 0) $(this).addClass("full-width");
$(this).attr("data-slide",(i+1));
var h1 = $(this).find("h1").get(0);
var h2 = $(this).find("h2").get(0);
var h3 = $(this).find("h3").get(0);
var cssClass = "h3";
if(h1){
titleStr = $(h1).text();
cssClass = "h1";
}else if(h2){
titleStr = $(h2).text();
cssClass = "h2";
}else if(h3)titleStr = $(h3).text();
else titleStr = $(this).text().substr(0,20)+"...";
$("#menu .content").append("<a class='slide "+cssClass+"' title='"+titleStr+"' href='#slide-"+(i+1)+"'>"+titleStr+"</a>");
});
$("#menu .content .slide").click(function(event){
event.stopPropagation();
});
//container for comments (this is necessary because css transitions break position:fixed)
this.presentation.append("<div class='comments'></div>");
this.activateSlide = function(slideNr, stepNr){
var that = this;
$(".comments").empty();
stepNr = stepNr || 0;
var activatedSlide = $(this.slides[slideNr-1]);
var currentSlide = $(this.slides[this.currentSlideNr-1]);
//slide links & navigation info
$("a").filter("[href='#slide-"+this.currentSlideNr+"']").removeClass("active");
$("a").filter("[href='#slide-"+slideNr+"']").addClass("active");
$("#navigation .info").html(slideNr+" - "+this.slides.length);
if(this.currentSlideNr==0)this.currentSlideNr = slideNr;
this.steps = this.stepController.getSteps(this.slides[slideNr-1], true);
var comingFromNextSlide = slideNr == this.currentSlideNr-1;
if(comingFromNextSlide) stepNr = this.steps.length; //if activatedSlide is activated from one slide ahead, we want to activate all steps
//activate/deactivate steps
this.updateSteps(stepNr, comingFromNextSlide);
this.setHash(slideNr, stepNr);
//Animation
if(this.currentSlideNr < slideNr){
this.transitionController.next(currentSlide, activatedSlide);
}else{
this.transitionController.previous(currentSlide, activatedSlide);
}
this.currentSlideNr = slideNr;
}
this.updateSteps = function(stepNr, comingFromNextSlide){
var that = this;
if(stepNr == this.currentStepNr+1){
this.stepController.activateStep(this.steps, stepNr);
}else if(stepNr == this.currentStepNr-1){
this.stepController.deactivateStep(this.steps, this.currentStepNr);
this.stepController.activateStep(this.steps, stepNr);
}else{
this.stepController.deactivateAll(this.steps);
this.stepController.activateAll(this.steps, stepNr);
}
this.currentStepNr = stepNr;
//scroll to step (if it is not a comment, because comments are not displayed within the scrollable section)
if(stepNr>0 && !comingFromNextSlide){
var s = this.steps[stepNr-1];
if(s && !$(s).is(".comment") && $(s).offset()){
$(this.slides[this.currentSlideNr-1]).animate({
scrollTop: $(s).offset().top+"px"
}, 200);
}
}
}
//all navigation runs through haschange events for deep linking capability
$(window).on('hashchange', function() {
that.getHash();
});
this.getHash = function(){
var str = "slide-";
var step, slide;
var hash = window.location.hash;
if(!hash || hash.indexOf(str) != -1 || hash==""){ //if the hash points to a slide or if there is no hash
slide = hash.substring(str.length+1);
if(slide=="") slide=1;
step = 0;
if(slide.indexOf && slide.indexOf("-") != -1){ //does the hash contain a step number
var parts = slide.split("-");
slide = parts[0];
step = parts[1];
}
}else{ //if the hash points to a custom id
//find element
var el = $(hash);
//is el a step? Then get the step nr
step = 0;
if($(el).is("[data-step]")) step = $(el).attr("data-step") || step;
//find slide el is children of
slideEl = el.closest("section");
slide = slideEl.attr("data-slide");
}
if(this.currentSlideNr != slide){
this.activateSlide(parseInt(slide), parseInt(step));
}else if(step >= 0){
this.updateSteps(parseInt(step));
}
}
this.setHash = function (slide, step){
var slideStr = "slide-"+slide;
var stepStr = (step != undefined && step > 0) ? "-"+step : "";
window.location.hash = slideStr+stepStr;
}
this.getHash();
this.next = function(){
if(this.currentStepNr < this.steps.length){
this.setHash(this.currentSlideNr, parseInt(this.currentStepNr)+1);
}else if(this.currentSlideNr == this.slides.length){ //cycle
this.setHash(1);
}else{
this.setHash(this.currentSlideNr+1);
}
}
this.previous = function(){
if(this.currentStepNr > 0){
this.setHash(this.currentSlideNr, this.currentStepNr-1);
}else if(this.currentSlideNr == 1) { //cycle
this.setHash(this.slides.length);
}else{
this.setHash(this.currentSlideNr-1);
}
}
// bind arrow and spacebar keys
$(document).keydown(function(e){
if (e.keyCode == 37 || e.keyCode == 38) {
that.previous();
return false;
}else if (e.keyCode == 32 || e.keyCode == 39 || e.keyCode == 40 || e.keyCode == 9) {
that.next();
return false;
}
});
};
|
abaab2874e047f7941c4f17c0864508db9de0951
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
christianvoigt/ArgunetPresentation
|
b8d73366fdf9b014fced78bc79db289552fb2bdc
|
d6a58ebf9911728cd4a8f66fdffe93cf00cb27fb
|
refs/heads/master
|
<file_sep>### 给阿源加密md5用<file_sep># linYuanmd5
#### 介绍
给阿源加密md5用
<file_sep>import fs from "fs"
import md5 from "md5"
const readFile = "data/ly.txt"
let writeFile = "data/fly.txt"
async function main() {
let count = 0
let countFile = 1
const data = fs.readFileSync(readFile, "utf-8")
const lines = data.split(/\r?\n/)
lines.forEach((line) => {
const li = line.replace("\"", "").replace("\"", "").trim()
console.log(li);
const ali = md5(li)
// console.log("after md5 ="+ali)
// console.log(`length =${ali.length}`)
ali.concat("/r/n").concat("/r/n")
console.log("ali =" + ali)
if(count < 70000){
count ++
fs.appendFileSync(writeFile, `${ali}\r\n`)
}else{
count = 0
countFile++
writeFile=`data/fly-${countFile}.txt`
fs.appendFileSync(writeFile, `${ali}\r\n`)
}
console.log("count = "+count)
});
}
main()
|
577cdfc23eb4245f7d2856c86fd6d6d59d83277b
|
[
"Markdown",
"TypeScript"
] | 3 |
Markdown
|
Linal-zhuang/md5Transformer
|
fd06319bc536a8b3fbe79945406027da8b6430af
|
164578010aa721174e1930d84b6ebaa05e76a0cd
|
refs/heads/master
|
<file_sep>from flask import Flask, request
from flask_restful import Resource, Api
from flask_jwt import JWT, jwt_required
from security import authenticate, identity
app=Flask(__name__)
app.secret_key='<KEY>'
api=Api(app)
jwt=JWT(app,authenticate,identity)
items=[]
class Item(Resource):
@jwt_required()
def get(self, name):
item =next(filter(lambda x:x['name']==name,items), None)
return {'item':item},200 if item else 404
def post(self, name):
if next(filter(lambda x:x['name']==name,items), None):
return {'message': "An item with {} already exists".format(name)}, 400
data=request.get_json()
item ={'name': name, 'price':data['price']}
items.append(item)
return item, 201
def delete(self, name):
global items
items=list(filter(lambda x: x['name']!=name,items))
return {'message':'Item deleted'}
def put(self, name):
data=request.get_json()
item=next(filter(lambda x: x['name']==name, items),None)
if item is None:
item={'name':name, 'price':data['price']}
items.append(item)
else:
item.update(data)
return item
class ItemList(Resource):
def get(self):
return {'items':items}
api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
app.run(port=5000, debug=True)
<file_sep>from werkzeug.security import safe_str_cmp
from user import User
users=[
User(1,'AbdlMalik','testing')
]
username_mapping={u.username:u for u in users}
userid_mapping={u.id:u for u in users}
def authenticate(username, password):
user=username_mapping.get(username, None)
if user and safe_str_cmp(user.password, password):
return user
def identity(payload):
user_id=payload['identity']
return userid_mapping.get(user_id, None)
<file_sep># REST-APIs-with-FLASK-of-JOSE
This is combination of code snippets from Jose's REST APIs with FLASK course.
<file_sep># B_R_R
# M_S_A_W
from flask import Flask, jsonify, request, render_template
app=Flask(__name__)
stores=[
{ 'name': 'My Pretty Store',
'items':[
{
'name': 'item1',
'price':15
}
]
}
]
@app.route('/')
def home():
return render_template('index.html')
@app.route('/store', methods=['POST'])
def create_store():
request_data=request.get_json()
new_store={
'name':request_data['name'],
'items':[]
}
stores.append(new_store)
return jsonify(new_store)
@app.route('/store/<string:name>', methods=['GET'])
def get_store(name):
for store in stores:
if store['name']==name:
return jsonify(store)
return jsonify({'message':'store not found'})
@app.route('/store')
def get_stores():
return jsonify({'stores':stores})
@app.route('/store/<string:name>/item', methods=['POST'])
def create_item_in_store(name):
request_data=request.get_json()
for store in stores:
if store['name']==name:
new_item={
'name':request_data['name'],
'price':request_data['price']
}
store['itmes'].append(new_item)
return jsonify(new_item)
return jsonify({'message':'store not found'})
@app.route('/store/<string:name>/item')
def get_items_in_store(name):
for store in stores:
if store['name']==name:
return jsonify({'items': store['items']})
return jsonify({'message': 'store not found '})
app.run(port=5000)
|
eddac5ecc3c9c60270c518d18a558bfc40b723b5
|
[
"Markdown",
"Python"
] | 4 |
Python
|
frontendprof/REST-APIs-with-FLASK-of-JOSE
|
162875dd39cb748971c9d90ca06fc502e04b171b
|
b0c085b746db6edb24444e456c57175eb3096d66
|
refs/heads/master
|
<file_sep>// OPTIONAL
// VK_KHR_swapchain
VUK_X(vkAcquireNextImageKHR)
VUK_X(vkQueuePresentKHR)
VUK_X(vkDestroySwapchainKHR)
// VK_KHR_debug_utils
VUK_Y(vkSetDebugUtilsObjectNameEXT)
VUK_Y(vkCmdBeginDebugUtilsLabelEXT)
VUK_Y(vkCmdEndDebugUtilsLabelEXT)
// VK_KHR_ray_tracing
VUK_X(vkCmdBuildAccelerationStructuresKHR)
VUK_X(vkGetAccelerationStructureBuildSizesKHR)
VUK_X(vkCmdTraceRaysKHR)
VUK_X(vkCreateAccelerationStructureKHR)
VUK_X(vkDestroyAccelerationStructureKHR)
VUK_X(vkGetRayTracingShaderGroupHandlesKHR)
VUK_X(vkCreateRayTracingPipelinesKHR)<file_sep>#pragma once
#include <string_view>
#include "vuk/Image.hpp"
namespace vuk {
std::string_view image_view_type_to_sv(ImageViewType) noexcept;
}<file_sep>#include "example_runner.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
#include <stb_image.h>
/* 04_texture
* In this example we will build on the previous examples (02_cube and 03_multipass), but we will make the cube textured.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
float angle = 0.f;
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
// A vuk::Texture is an owned pair of Image and ImageView
// An optional is used here so that we can reset this on cleanup, despite being a global (which is to simplify the code here)
std::optional<vuk::Texture> texture_of_doge;
vuk::Example x{
.name = "04_texture",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/ubo_test_tex.vert").generic_string()),
(root / "examples/ubo_test_tex.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle_depthshaded_tex.frag").generic_string()),
(root / "examples/triangle_depthshaded_tex.frag").generic_string());
runner.context->create_named_pipeline("textured_cube", pci);
}
// Use STBI to load the image
int x, y, chans;
auto doge_image = stbi_load((root / "examples/doge.png").generic_string().c_str(), &x, &y, &chans, 4);
// Similarly to buffers, we allocate the image and enqueue the upload
auto [tex, tex_fut] = create_texture(allocator, vuk::Format::eR8G8B8A8Srgb, vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u }, doge_image, true);
texture_of_doge = std::move(tex);
runner.enqueue_setup(std::move(tex_fut));
stbi_image_free(doge_image);
// We set up the cube data, same as in example 02_cube
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
// For the example, we just ask these that these uploads complete before moving on to rendering
// In an engine, you would integrate these uploads into some explicit system
runner.enqueue_setup(std::move(vert_fut));
runner.enqueue_setup(std::move(ind_fut));
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
vp.view = glm::lookAt(glm::vec3(0, 1.5, 3.5), glm::vec3(0), glm::vec3(0, 1, 0));
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 1.f, 10.f);
vp.proj[1][1] *= -1;
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
vuk::RenderGraph rg("04");
rg.attach_in("04_texture", std::move(target));
// Set up the pass to draw the textured cube, with a color and a depth attachment
rg.add_pass({ .resources = { "04_texture"_image >> vuk::eColorWrite >> "04_texture_final", "04_texture_depth"_image >> vuk::eDepthStencilRW },
.execute = [uboVP](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
.depthWriteEnable = true,
.depthCompareOp = vuk::CompareOp::eLessOrEqual,
})
.broadcast_color_blend({}) // Set the default color blend state
.bind_vertex_buffer(0,
*verts,
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat,
vuk::Ignore{ offsetof(util::Vertex, uv_coordinates) - sizeof(util::Vertex::position) },
vuk::Format::eR32G32Sfloat })
.bind_index_buffer(*inds, vuk::IndexType::eUint32)
// Here we bind our vuk::Texture to (set = 0, binding = 2) with default sampler settings
.bind_image(0, 2, *texture_of_doge->view)
.bind_sampler(0, 2, {})
.bind_graphics_pipeline("textured_cube")
.bind_buffer(0, 0, uboVP);
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = static_cast<glm::mat4>(glm::angleAxis(glm::radians(angle), glm::vec3(0.f, 1.f, 0.f)));
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
} });
angle += 180.f * ImGui::GetIO().DeltaTime;
rg.attach_and_clear_image("04_texture_depth", { .format = vuk::Format::eD32Sfloat }, vuk::ClearDepthStencil{ 1.0f, 0 });
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "04_texture_final" };
},
// Perform cleanup for the example
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
verts.reset();
inds.reset();
// We release the texture resources
texture_of_doge.reset();
}
};
REGISTER_EXAMPLE(x);
} // namespace<file_sep>#pragma once
#ifndef VUK_CUSTOM_VULKAN_HEADER
#include <vulkan/vulkan.h>
#else
#include VUK_CUSTOM_VULKAN_HEADER
#endif
// number of sets that can be bound to the command buffer
#ifndef VUK_MAX_SETS
#define VUK_MAX_SETS 8u
#endif
// number of bindings (individual descriptor) per set for non-persistent descriptorsets
#ifndef VUK_MAX_BINDINGS
#define VUK_MAX_BINDINGS 16u
#endif
// number of attributes that can be bound to the command buffer
#ifndef VUK_MAX_ATTRIBUTES
#define VUK_MAX_ATTRIBUTES 8u
#endif
// number of color attachments supported
#ifndef VUK_MAX_COLOR_ATTACHMENTS
#define VUK_MAX_COLOR_ATTACHMENTS 8u
#endif
// size of the push constant buffer
#ifndef VUK_MAX_PUSHCONSTANT_SIZE
#define VUK_MAX_PUSHCONSTANT_SIZE 128u
#endif
// number of individual push constant ranges that can be bound to the command buffer
#ifndef VUK_MAX_PUSHCONSTANT_RANGES
#define VUK_MAX_PUSHCONSTANT_RANGES 8u
#endif
// number of specialization constants that can be set per pipeline
#ifndef VUK_MAX_SPECIALIZATIONCONSTANT_RANGES
#define VUK_MAX_SPECIALIZATIONCONSTANT_RANGES 64u
#endif
// number of bytes specialization constants can take up for pipelines
#ifndef VUK_MAX_SPECIALIZATIONCONSTANT_SIZE
#define VUK_MAX_SPECIALIZATIONCONSTANT_SIZE 32u
#endif
// number of viewports that can be set on the command buffer
#ifndef VUK_MAX_VIEWPORTS
#define VUK_MAX_VIEWPORTS 1u
#endif
// number of scissors that can be set on the command buffer
#ifndef VUK_MAX_SCISSORS
#define VUK_MAX_SCISSORS 1u
#endif
#ifndef VUK_DISABLE_EXCEPTIONS
#define VUK_USE_EXCEPTIONS 1
#else
#define VUK_USE_EXCEPTIONS 0
#endif<file_sep>#include "bench_runner.hpp"
#include "vuk/Partials.hpp"
#include <stb_image.h>
namespace {
template<size_t Count>
struct DrawCount {
static constexpr unsigned n_draws = Count;
};
template<size_t Count>
struct TriangleCount {
static constexpr unsigned n_tris = Count;
};
struct V1 : DrawCount<10>, TriangleCount<1> {
std::string_view description = "10 draws";
};
struct V2 : DrawCount<100>, TriangleCount<1> {
std::string_view description = "100 draws";
};
struct V3 : TriangleCount<10>, DrawCount<1> {
std::string_view description = "10 tris";
};
struct V4 : TriangleCount<100>, DrawCount<1> {
std::string_view description = "100 tris";
};
template<class T>
vuk::RenderGraph test_case(vuk::Allocator& allocator, bool dependent, vuk::Texture& src, vuk::Texture& dst, vuk::Query start, vuk::Query end, T parameters) {
vuk::RenderGraph rg;
rg.add_pass({ .resources = { "_dst"_image >> vuk::eColorWrite }, .execute = [start, end, parameters, &src, dependent](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({})
.broadcast_color_blend({})
.bind_image(0, 0, *src.view)
.bind_sampler(0, 0, vuk::SamplerCreateInfo{ .magFilter = vuk::Filter::eLinear, .minFilter = vuk::Filter::eLinear });
if (dependent) {
command_buffer.bind_graphics_pipeline("dependent");
command_buffer.push_constants<unsigned>(vuk::ShaderStageFlagBits::eFragment, 0, 1.0f / (float)src.extent.width);
} else {
command_buffer.bind_graphics_pipeline("nondependent");
}
vuk::TimedScope _{ command_buffer, start, end };
for (auto i = 0; i < parameters.n_draws; i++) {
command_buffer.draw(3 * parameters.n_tris, 1, 0, 0);
}
} });
rg.add_pass(
{ .resources = { "_final"_image >> vuk::eColorWrite, "_dst+"_image >> vuk::eFragmentSampled }, .execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({})
.broadcast_color_blend({})
.bind_graphics_pipeline("blit")
.bind_image(0, 0, "_dst")
.bind_sampler(0, 0, vuk::SamplerCreateInfo{ .magFilter = vuk::Filter::eLinear, .minFilter = vuk::Filter::eLinear });
command_buffer.draw(3, 1, 0, 0);
} });
rg.attach_image("_dst", vuk::ImageAttachment::from_texture(dst), vuk::Access::eNone);
return rg;
}
void blit(vuk::Allocator& allocator, vuk::Texture& src, vuk::Texture& dst) {
std::shared_ptr<vuk::RenderGraph> rg = std::make_shared<vuk::RenderGraph>("blit");
rg->add_pass({ .resources = { "dst"_image >> vuk::eColorWrite }, .execute = [&src](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({})
.broadcast_color_blend({})
.bind_graphics_pipeline("blit")
.bind_image(0, 0, *src.view)
.bind_sampler(0, 0, { .magFilter = vuk::Filter::eLinear, .minFilter = vuk::Filter::eLinear });
command_buffer.draw(3, 1, 0, 0);
} });
rg->attach_image("dst", vuk::ImageAttachment::from_texture(dst), vuk::Access::eNone);
rg->release("dst+", vuk::Access::eFragmentSampled);
vuk::Compiler c;
auto erg = *c.link({ &rg, 1 }, {});
vuk::execute_submit_and_wait(allocator, std::move(erg));
}
std::optional<vuk::Texture> texture_of_doge, tex2k, tex4k, tex8k;
std::optional<vuk::Texture> dstsmall, dst2k, dst4k, dst8k;
vuk::Bench<V1, V2, V3, V4> x{
// The display name of this example
.base = {
.name = "Dependent vs. non-dependent texture fetch",
// Setup code, ran once in the beginning
.setup = [](vuk::BenchRunner& runner, vuk::Allocator& allocator) {
auto& ctx = allocator.get_context();
// Pipelines are created by filling out a vuk::PipelineCreateInfo
// In this case, we only need the shaders, we don't care about the rest of the state
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file(VUK_EX_PATH_TO_ROOT "benchmarks/fullscreen.vert"), VUK_EX_PATH_TO_ROOT "examples/fullscreen.vert");
pci.add_glsl(util::read_entire_file(VUK_EX_PATH_TO_ROOT "benchmarks/dependent_texture_fetch_explicit_lod.frag"),
VUK_EX_PATH_TO_ROOT "examples/dependent_texture_fetch_explicit_lod.frag");
runner.context->create_named_pipeline("dependent", pci);
}
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file(VUK_EX_PATH_TO_ROOT "benchmarks/fullscreen.vert"), VUK_EX_PATH_TO_ROOT "examples/fullscreen.vert");
pci.add_glsl(util::read_entire_file(VUK_EX_PATH_TO_ROOT "benchmarks/nondependent_texture_fetch_explicit_lod.frag"),
VUK_EX_PATH_TO_ROOT "examples/nondependent_texture_fetch_explicit_lod.frag");
runner.context->create_named_pipeline("nondependent", pci);
}
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file(VUK_EX_PATH_TO_ROOT "benchmarks/fullscreen.vert"), VUK_EX_PATH_TO_ROOT "examples/fullscreen.vert");
pci.add_glsl(util::read_entire_file(VUK_EX_PATH_TO_ROOT "benchmarks/blit.frag"), VUK_EX_PATH_TO_ROOT "examples/blit.frag");
runner.context->create_named_pipeline("blit", pci);
}
int x, y, chans;
auto doge_image = stbi_load(VUK_EX_PATH_TO_ROOT "examples/doge.png", &x, &y, &chans, 4);
auto [tex, tex_fut] = create_texture(allocator, vuk::Format::eR8G8B8A8Srgb, vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u }, doge_image, false);
texture_of_doge = std::move(tex);
vuk::Compiler c;
tex_fut.wait(allocator, c);
stbi_image_free(doge_image);
tex2k = ctx.allocate_texture(allocator, vuk::ImageCreateInfo{.format = vuk::Format::eR8G8B8A8Srgb, .extent = {.width = 2048, .height = 2048, .depth = 1}, .usage = vuk::ImageUsageFlagBits::eColorAttachment | vuk::ImageUsageFlagBits::eSampled });
tex4k = ctx.allocate_texture(allocator, vuk::ImageCreateInfo{.format = vuk::Format::eR8G8B8A8Srgb, .extent = {.width = 4096, .height = 4096, .depth = 1}, .usage = vuk::ImageUsageFlagBits::eColorAttachment | vuk::ImageUsageFlagBits::eSampled });
tex8k = ctx.allocate_texture(allocator, vuk::ImageCreateInfo{.format = vuk::Format::eR8G8B8A8Srgb, .extent = {.width = 8192, .height = 8192, .depth = 1}, .usage = vuk::ImageUsageFlagBits::eColorAttachment | vuk::ImageUsageFlagBits::eSampled });
blit(allocator, *texture_of_doge, *tex2k);
blit(allocator, *texture_of_doge, *tex4k);
blit(allocator, *texture_of_doge, *tex8k);
dstsmall = ctx.allocate_texture(allocator, vuk::ImageCreateInfo{.format = vuk::Format::eR8G8B8A8Srgb, .extent = {.width = (unsigned)x, .height = (unsigned)y, .depth = 1}, .usage = vuk::ImageUsageFlagBits::eColorAttachment | vuk::ImageUsageFlagBits::eSampled });
dst2k = ctx.allocate_texture(allocator, vuk::ImageCreateInfo{.format = vuk::Format::eR8G8B8A8Srgb, .extent = {.width = 2048, .height = 2048, .depth = 1}, .usage = vuk::ImageUsageFlagBits::eColorAttachment | vuk::ImageUsageFlagBits::eSampled });
dst4k = ctx.allocate_texture(allocator, vuk::ImageCreateInfo{.format = vuk::Format::eR8G8B8A8Srgb, .extent = {.width = 4096, .height = 4096, .depth = 1}, .usage = vuk::ImageUsageFlagBits::eColorAttachment | vuk::ImageUsageFlagBits::eSampled });
dst8k = ctx.allocate_texture(allocator, vuk::ImageCreateInfo{.format = vuk::Format::eR8G8B8A8Srgb, .extent = {.width = 8192, .height = 8192, .depth = 1}, .usage = vuk::ImageUsageFlagBits::eColorAttachment | vuk::ImageUsageFlagBits::eSampled });
},
.gui = [](vuk::BenchRunner& runner, vuk::Allocator& allocator) {
},
.cleanup = [](vuk::BenchRunner& runner, vuk::Allocator& allocator) {
// We release the texture resources
texture_of_doge.reset();
tex2k.reset();
tex4k.reset();
tex8k.reset();
dstsmall.reset();
dst2k.reset();
dst4k.reset();
dst8k.reset();
}
},
.cases = {
{"Dependent 112x112", [](vuk::BenchRunner& runner, vuk::Allocator& allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
return test_case(allocator, true, *texture_of_doge, *dstsmall, start, end, parameters);
}},
{"Non-dependent 112x112", [](vuk::BenchRunner& runner, vuk::Allocator& allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
return test_case(allocator, false, *texture_of_doge, *dstsmall, start, end, parameters);
}},
{"Dependent 2K", [](vuk::BenchRunner& runner, vuk::Allocator& allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
return test_case(allocator, true, *tex2k, *dst2k, start, end, parameters);
}},
{"Non-dependent 2K", [](vuk::BenchRunner& runner, vuk::Allocator& allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
return test_case(allocator, false, *tex2k, *dst2k, start, end, parameters);
}},
{"Dependent 4K", [](vuk::BenchRunner& runner, vuk::Allocator& allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
return test_case(allocator, true, *tex4k, *dst4k, start, end, parameters);
}},
{"Non-dependent 4K", [](vuk::BenchRunner& runner, vuk::Allocator& allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
return test_case(allocator, false, *tex4k, *dst4k, start, end, parameters);
}},
/*{"Dependent 8K", [](vuk::BenchRunner& runner, vuk::Allocator& allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
return test_case(allocator, true, *tex8k, *dst8k, start, end, parameters);
}},
{"Non-dependent 8K", [](vuk::BenchRunner& runner, vuk::Allocator& allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
return test_case(allocator, false, *tex8k, *dst8k, start, end, parameters);
}},*/
}
};
REGISTER_BENCH(x);
} // namespace<file_sep>#pragma once
#include "RenderGraphUtil.hpp"
#include "RenderPass.hpp"
#include "vuk/RelSpan.hpp"
#include "vuk/RenderGraphReflection.hpp"
#include "vuk/ShortAlloc.hpp"
#include "vuk/SourceLocation.hpp"
#include <deque>
#include <robin_hood.h>
namespace vuk {
struct RenderPassInfo {
RelSpan<AttachmentRPInfo> attachments;
vuk::RenderPassCreateInfo rpci;
vuk::FramebufferCreateInfo fbci;
VkRenderPass handle = {};
VkFramebuffer framebuffer;
};
using IARule = std::function<void(const struct InferenceContext&, ImageAttachment&)>;
using BufferRule = std::function<void(const struct InferenceContext&, Buffer&)>;
struct IAInference {
QualifiedName resource;
IARule rule;
};
struct IAInferences {
Name prefix;
std::vector<IARule> rules;
};
struct BufferInference {
QualifiedName resource;
BufferRule rule;
};
struct BufferInferences {
Name prefix;
std::vector<BufferRule> rules;
};
struct Release {
Access original;
QueueResourceUse dst_use;
FutureBase* signal = nullptr;
};
struct PassWrapper {
Name name;
DomainFlags execute_on = DomainFlagBits::eAny;
RelSpan<Resource> resources;
std::function<void(CommandBuffer&)> execute;
std::byte* arguments; // internal use
PassType type;
source_location source;
};
struct PassInfo {
PassInfo(PassWrapper&);
PassWrapper* pass;
QualifiedName qualified_name;
size_t batch_index;
size_t command_buffer_index = 0;
int32_t render_pass_index = -1;
uint32_t subpass;
DomainFlags domain = DomainFlagBits::eAny;
RelSpan<Resource> resources;
RelSpan<VkImageMemoryBarrier2KHR> pre_image_barriers, post_image_barriers;
RelSpan<VkMemoryBarrier2KHR> pre_memory_barriers, post_memory_barriers;
RelSpan<std::pair<DomainFlagBits, uint64_t>> relative_waits;
RelSpan<std::pair<DomainFlagBits, uint64_t>> absolute_waits;
RelSpan<FutureBase*> future_signals;
RelSpan<int32_t> referenced_swapchains; // TODO: maybe not the best place for it
int32_t is_waited_on = 0;
};
#define INIT(x) x(decltype(x)::allocator_type(*arena_))
struct RGImpl {
std::unique_ptr<arena> arena_;
std::vector<PassWrapper, short_alloc<PassWrapper, 64>> passes;
std::vector<QualifiedName, short_alloc<QualifiedName, 64>> imported_names; // names coming from subgraphs
std::vector<std::pair<Name, Name>, short_alloc<std::pair<Name, Name>, 64>> aliases; // maps resource names to resource names
std::vector<std::pair<QualifiedName, std::pair<QualifiedName, Subrange::Image>>,
short_alloc<std::pair<QualifiedName, std::pair<QualifiedName, Subrange::Image>>, 64>>
diverged_subchain_headers;
robin_hood::unordered_flat_map<QualifiedName, AttachmentInfo> bound_attachments;
robin_hood::unordered_flat_map<QualifiedName, BufferInfo> bound_buffers;
std::vector<IAInference, short_alloc<IAInference, 64>> ia_inference_rules;
std::vector<BufferInference, short_alloc<BufferInference, 64>> buf_inference_rules;
std::vector<Resource> resources;
struct SGInfo {
uint64_t count = 0;
std::span<std::pair<Name, QualifiedName>> exported_names = {};
};
std::vector<std::pair<std::shared_ptr<RenderGraph>, SGInfo>, short_alloc<std::pair<std::shared_ptr<RenderGraph>, SGInfo>, 64>> subgraphs;
std::vector<std::pair<QualifiedName, Acquire>, short_alloc<std::pair<QualifiedName, Acquire>, 64>> acquires;
std::vector<std::pair<QualifiedName, Release>, short_alloc<std::pair<QualifiedName, Release>, 64>> releases;
RGImpl() :
arena_(new arena(sizeof(Pass) * 64)),
INIT(passes),
INIT(imported_names),
INIT(aliases),
INIT(diverged_subchain_headers),
INIT(ia_inference_rules),
INIT(buf_inference_rules),
INIT(subgraphs),
INIT(acquires),
INIT(releases) {}
Name resolve_alias(Name in) {
auto it = std::find_if(aliases.begin(), aliases.end(), [=](auto& v) { return v.first == in; });
if (it == aliases.end()) {
return in;
} else {
return resolve_alias(it->second);
}
};
robin_hood::unordered_flat_set<QualifiedName> get_available_resources();
Resource& get_resource(std::vector<PassInfo>& pass_infos, ChainAccess& ca) {
return resources[pass_infos[ca.pass].resources.offset0 + ca.resource];
}
size_t temporary_name_counter = 0;
Name temporary_name = "_temporary";
};
using ResourceLinkMap = robin_hood::unordered_node_map<QualifiedName, ChainLink>;
struct RGCImpl {
RGCImpl() : arena_(new arena(4 * 1024 * 1024)), INIT(computed_passes), INIT(ordered_passes), INIT(partitioned_passes), INIT(rpis) {}
RGCImpl(arena* a) : arena_(a), INIT(computed_passes), INIT(ordered_passes), INIT(partitioned_passes), INIT(rpis) {}
std::unique_ptr<arena> arena_;
// per PassInfo
std::vector<Resource> resources;
std::vector<std::pair<DomainFlagBits, uint64_t>> waits;
std::vector<std::pair<DomainFlagBits, uint64_t>> absolute_waits;
std::vector<FutureBase*> future_signals;
std::deque<QualifiedName> qfname_references;
// /per PassInfo
std::vector<PassInfo, short_alloc<PassInfo, 64>> computed_passes;
std::vector<PassInfo*, short_alloc<PassInfo*, 64>> ordered_passes;
std::vector<size_t> computed_pass_idx_to_ordered_idx;
std::vector<size_t> ordered_idx_to_computed_pass_idx;
std::vector<PassInfo*, short_alloc<PassInfo*, 64>> partitioned_passes;
std::vector<size_t> computed_pass_idx_to_partitioned_idx;
robin_hood::unordered_flat_map<QualifiedName, QualifiedName> computed_aliases; // maps resource names to resource names
robin_hood::unordered_flat_map<QualifiedName, QualifiedName> assigned_names; // maps resource names to attachment names
robin_hood::unordered_flat_map<Name, uint64_t> sg_name_counter;
robin_hood::unordered_flat_map<const RenderGraph*, std::string> sg_prefixes;
std::vector<VkImageMemoryBarrier2KHR> image_barriers;
std::vector<VkMemoryBarrier2KHR> mem_barriers;
ResourceLinkMap res_to_links;
std::vector<ChainAccess> pass_reads;
Resource& get_resource(ChainAccess& ca) {
return resources[computed_passes[ca.pass].resources.offset0 + ca.resource];
}
const Resource& get_resource(const ChainAccess& ca) const {
return resources[computed_passes[ca.pass].resources.offset0 + ca.resource];
}
PassInfo& get_pass(ChainAccess& ca) {
return computed_passes[ca.pass];
}
PassInfo& get_pass(int32_t ordered_pass_idx) {
assert(ordered_pass_idx >= 0);
return *ordered_passes[ordered_pass_idx];
}
std::vector<ChainLink*> chains;
std::vector<ChainLink*> child_chains;
std::deque<ChainLink> helper_links;
std::vector<int32_t> swapchain_references;
std::vector<AttachmentRPInfo> rp_infos;
std::array<size_t, 3> last_ordered_pass_idx_in_domain_array;
int32_t last_ordered_pass_idx_in_domain(DomainFlagBits queue) {
uint32_t idx;
if (queue == DomainFlagBits::eGraphicsQueue) {
idx = 0;
} else if (queue == DomainFlagBits::eComputeQueue) {
idx = 1;
} else {
idx = 2;
}
return (int32_t)last_ordered_pass_idx_in_domain_array[idx];
}
std::vector<AttachmentInfo> bound_attachments;
std::vector<BufferInfo> bound_buffers;
AttachmentInfo& get_bound_attachment(int32_t idx) {
assert(idx < 0);
return bound_attachments[(-1 * idx - 1)];
}
BufferInfo& get_bound_buffer(int32_t idx) {
assert(idx < 0);
return bound_buffers[(-1 * idx - 1)];
}
std::vector<ChainLink*> attachment_use_chain_references;
std::vector<RenderPassInfo*> attachment_rp_references;
std::vector<std::pair<QualifiedName, Release>> releases;
Release& get_release(int64_t idx) {
return releases[-1 * (idx)-1].second;
}
std::unordered_map<QualifiedName, IAInferences> ia_inference_rules;
std::unordered_map<QualifiedName, BufferInferences> buf_inference_rules;
robin_hood::unordered_flat_map<QualifiedName, std::pair<QualifiedName, Subrange::Image>> diverged_subchain_headers;
QualifiedName resolve_name(QualifiedName in) {
auto it = assigned_names.find(in);
if (it == assigned_names.end()) {
return in;
} else {
return it->second;
}
};
QualifiedName resolve_alias(QualifiedName in) {
auto it = computed_aliases.find(in);
if (it == computed_aliases.end()) {
return in;
} else {
return it->second;
}
};
QualifiedName resolve_alias_rec(QualifiedName in) {
auto it = computed_aliases.find(in);
if (it == computed_aliases.end()) {
return in;
} else {
return resolve_alias_rec(it->second);
}
};
void compute_assigned_names();
std::vector<RenderPassInfo, short_alloc<RenderPassInfo, 64>> rpis;
std::span<PassInfo*> transfer_passes, compute_passes, graphics_passes;
void append(Name subgraph_name, const RenderGraph& other);
void merge_diverge_passes(std::vector<PassInfo, short_alloc<PassInfo, 64>>& passes);
void compute_prefixes(const RenderGraph& rg, std::string& prefix);
void inline_subgraphs(const RenderGraph& rg, robin_hood::unordered_flat_set<RenderGraph*>& consumed_rgs);
Result<void> terminate_chains();
Result<void> diagnose_unheaded_chains();
Result<void> schedule_intra_queue(std::span<struct PassInfo> passes, const RenderGraphCompileOptions& compile_options);
Result<void> fix_subchains();
void emit_image_barrier(RelSpan<VkImageMemoryBarrier2KHR>&,
int32_t bound_attachment,
QueueResourceUse last_use,
QueueResourceUse current_use,
Subrange::Image& subrange,
ImageAspectFlags aspect,
bool is_release = false);
void emit_memory_barrier(RelSpan<VkMemoryBarrier2KHR>&, QueueResourceUse last_use, QueueResourceUse current_use);
// opt passes
Result<void> merge_rps();
// link passes
Result<void> generate_barriers_and_waits();
Result<void> assign_passes_to_batches();
Result<void> build_waits();
Result<void> build_renderpasses();
void emit_barriers(Context& ctx,
VkCommandBuffer cbuf,
vuk::DomainFlagBits domain,
RelSpan<VkMemoryBarrier2KHR> mem_bars,
RelSpan<VkImageMemoryBarrier2KHR> im_bars);
ImageUsageFlags compute_usage(const ChainLink* head);
};
#undef INIT
inline PassInfo::PassInfo(PassWrapper& p) : pass(&p) {}
template<class T, class A, class F>
T* contains_if(std::vector<T, A>& v, F&& f) {
auto it = std::find_if(v.begin(), v.end(), f);
if (it != v.end())
return &(*it);
else
return nullptr;
}
template<class T, class A, class F>
T const* contains_if(const std::vector<T, A>& v, F&& f) {
auto it = std::find_if(v.begin(), v.end(), f);
if (it != v.end())
return &(*it);
else
return nullptr;
}
template<class T, class A>
T const* contains(const std::vector<T, A>& v, const T& f) {
auto it = std::find(v.begin(), v.end(), f);
if (it != v.end())
return &(*it);
else
return nullptr;
}
template<typename Iterator, typename Compare>
void topological_sort(Iterator begin, Iterator end, Compare cmp) {
while (begin != end) {
auto const new_begin = std::partition(begin, end, [&](auto const& a) { return std::none_of(begin, end, [&](auto const& b) { return cmp(b, a); }); });
assert(new_begin != begin && "not a partial ordering");
begin = new_begin;
}
}
namespace errors {
RenderGraphException make_unattached_resource_exception(PassInfo& pass_info, Resource& resource);
RenderGraphException make_cbuf_references_unknown_resource(PassInfo& pass_info, Resource::Type type, Name name);
RenderGraphException make_cbuf_references_undeclared_resource(PassInfo& pass_info, Resource::Type type, Name name);
} // namespace errors
}; // namespace vuk<file_sep>#include "example_runner.hpp"
#include <algorithm>
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
#include <numeric>
#include <random>
#include <stb_image.h>
/* 07_commands
* In this example we will see how to create passes that execute outside of renderpasses.
* To showcase this, we will manually resolve an MSAA image (from the previous example),
* then blit parts of it to the final image.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
float time = 0.f;
bool start = false;
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
std::optional<vuk::Texture> texture_of_doge;
std::vector<unsigned> shuf(9);
vuk::Example x{
.name = "07_commands",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
// Same setup as for 04_texture
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/ubo_test_tex.vert").generic_string()),
(root / "examples/ubo_test_tex.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle_depthshaded_tex.frag").generic_string()),
(root / "examples/triangle_depthshaded_text.frag").generic_string());
runner.context->create_named_pipeline("textured_cube", pci);
}
int x, y, chans;
auto doge_image = stbi_load((root / "examples/doge.png").generic_string().c_str(), &x, &y, &chans, 4);
auto [tex, tex_fut] = create_texture(allocator, vuk::Format::eR8G8B8A8Srgb, vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u }, doge_image, false);
texture_of_doge = std::move(tex);
runner.enqueue_setup(std::move(tex_fut));
// We set up the cube data, same as in example 02_cube
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
// For the example, we just ask these that these uploads complete before moving on to rendering
// In an engine, you would integrate these uploads into some explicit system
runner.enqueue_setup(std::move(vert_fut));
runner.enqueue_setup(std::move(ind_fut));
// Init tiles
std::iota(shuf.begin(), shuf.end(), 0);
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
vp.view = glm::lookAt(glm::vec3(0, 0, 1.75), glm::vec3(0), glm::vec3(0, 1, 0));
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 0.1f, 10.f);
vp.proj[1][1] *= -1;
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
vuk::RenderGraph rg("07");
rg.attach_in("07_commands", std::move(target));
// The rendering pass is unchanged by going to multisampled,
// but we will use an offscreen multisampled color attachment
rg.add_pass({ .resources = { "07_commands_MS"_image >> vuk::eColorWrite, "07_commands_depth"_image >> vuk::eDepthStencilRW },
.execute = [uboVP](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
.depthWriteEnable = true,
.depthCompareOp = vuk::CompareOp::eLessOrEqual,
})
.broadcast_color_blend({}) // Set the default color blend state
.bind_vertex_buffer(0,
*verts,
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat,
vuk::Ignore{ offsetof(util::Vertex, uv_coordinates) - sizeof(util::Vertex::position) },
vuk::Format::eR32G32Sfloat })
.bind_index_buffer(*inds, vuk::IndexType::eUint32)
.bind_image(0, 2, *texture_of_doge->view)
.bind_sampler(0, 2, {})
.bind_graphics_pipeline("textured_cube")
.bind_buffer(0, 0, uboVP);
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = static_cast<glm::mat4>(glm::angleAxis(glm::radians(0.f), glm::vec3(0.f, 1.f, 0.f)));
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
} });
// Add a pass where we resolve our multisampled image
// Since we didn't declare any framebuffer forming resources, this pass will execute outside of a renderpass
// Hence we can only call commands that are valid outside of a renderpass
rg.add_pass({ .name = "resolve",
.resources = { "07_commands_MS+"_image >> vuk::eTransferRead, "07_commands_NMS"_image >> vuk::eTransferWrite },
.execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.resolve_image("07_commands_MS+", "07_commands_NMS");
} });
// Here we demonstrate blitting by splitting up the resolved image into 09 tiles
float tile_x_count = 3;
float tile_y_count = 3;
// And blitting those tiles in the order dictated by 'shuf'
// We will also sort shuf over time, to show a nice animation
rg.add_pass({ .name = "blit",
.resources = { "07_commands_NMS+"_image >> vuk::eTransferRead, "07_commands"_image >> vuk::eTransferWrite >> "07_commands_final" },
.execute = [tile_x_count, tile_y_count](vuk::CommandBuffer& command_buffer) {
for (auto i = 0; i < 9; i++) {
auto x = i % 3;
auto y = i / 3;
auto dst_extent = command_buffer.get_resource_image_attachment("07_commands")->extent;
float tile_x_size = dst_extent.extent.width / tile_x_count;
float tile_y_size = dst_extent.extent.height / tile_y_count;
auto sx = shuf[i] % 3;
auto sy = shuf[i] / 3;
vuk::ImageBlit blit;
blit.srcSubresource.aspectMask = vuk::ImageAspectFlagBits::eColor;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.srcSubresource.mipLevel = 0;
blit.srcOffsets[0] = vuk::Offset3D{ static_cast<int>(x * tile_x_size), static_cast<int>(y * tile_y_size), 0 };
blit.srcOffsets[1] = vuk::Offset3D{ static_cast<int>((x + 1) * tile_x_size), static_cast<int>((y + 1) * tile_y_size), 1 };
blit.dstSubresource = blit.srcSubresource;
blit.dstOffsets[0] = vuk::Offset3D{ static_cast<int>(sx * tile_x_size), static_cast<int>(sy * tile_y_size), 0 };
blit.dstOffsets[1] = vuk::Offset3D{ static_cast<int>((sx + 1) * tile_x_size), static_cast<int>((sy + 1) * tile_y_size), 1 };
command_buffer.blit_image("07_commands_NMS+", "07_commands", blit, vuk::Filter::eLinear);
}
} });
time += ImGui::GetIO().DeltaTime;
if (!start && time > 5.f) {
start = true;
time = 0;
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(shuf.begin(), shuf.end(), g);
}
if (start && time > 1.f) {
time = 0;
// World's slowest bubble sort, one iteration per second
bool swapped = false;
for (unsigned i = 1; i < shuf.size(); i++) {
if (shuf[i - 1] > shuf[i]) {
std::swap(shuf[i - 1], shuf[i]);
swapped = true;
break;
}
}
// 'shuf' is sorted, restart
if (!swapped) {
start = false;
}
}
// We mark our MS attachment as multisampled (8 samples)
// from the final image, and we don't need to specify here
// We use the swapchain format & extents, since resolving needs identical formats & extents
rg.attach_and_clear_image("07_commands_MS", { .sample_count = vuk::Samples::e8 }, vuk::ClearColor{ 0.f, 0.f, 0.f, 1.f });
rg.attach_and_clear_image("07_commands_depth", { .format = vuk::Format::eD32Sfloat }, vuk::ClearDepthStencil{ 1.0f, 0 });
rg.attach_image("07_commands_NMS", { .sample_count = vuk::Samples::e1, .level_count = 1, .layer_count = 1 });
rg.inference_rule("07_commands_MS", vuk::same_extent_as("07_commands"));
rg.inference_rule("07_commands_MS", vuk::same_format_as("07_commands"));
rg.inference_rule("07_commands_NMS", vuk::same_extent_as("07_commands_MS"));
rg.inference_rule("07_commands_NMS", vuk::same_format_as("07_commands_MS"));
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "07_commands_final" };
},
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
verts.reset();
inds.reset();
texture_of_doge.reset();
}
};
REGISTER_EXAMPLE(x);
} // namespace<file_sep>#include "BufferAllocator.hpp"
#include "vuk/Allocator.hpp"
#include "vuk/Result.hpp"
#include "vuk/SourceLocation.hpp"
#include <iostream>
// Aligns given value down to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 8.
// Use types like uint32_t, uint64_t as T.
template<typename T>
static inline T VmaAlignDown(T val, T align) {
return val / align * align;
}
// Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16.
// Use types like uint32_t, uint64_t as T.
template<typename T>
static inline T VmaAlignUp(T val, T align) {
return (val + align - 1) / align * align;
}
namespace vuk {
Result<void, AllocateException> BufferLinearAllocator::grow(size_t num_blocks, SourceLocationAtFrame source) {
std::lock_guard _(mutex);
int best_fit_block_size = 1024;
int best_fit_index = -1;
size_t actual_blocks = num_blocks;
// find best fit allocation
for (size_t i = 0; i < available_allocation_count; i++) {
int block_over = (int)available_allocations[i].num_blocks - (int)num_blocks;
if (block_over >= 0 && block_over < best_fit_block_size) {
best_fit_block_size = block_over;
best_fit_index = (int)i;
if (block_over == 0) {
break;
}
}
}
if (best_fit_index == -1) { // no allocation suitable, allocate new one
Buffer alloc;
BufferCreateInfo bci{ .mem_usage = mem_usage, .size = block_size * num_blocks };
auto result = upstream->allocate_buffers(std::span{ &alloc, 1 }, std::span{ &bci, 1 }, source);
if (!result) {
return result;
}
for (auto i = 0; i < num_blocks; i++) {
used_allocations[used_allocation_count + i] = { alloc, i > 0 ? 0 : num_blocks, 0 };
}
current_buffer += (int)num_blocks;
} else { // we found one, we swap it into the used allocations and compact the available allocations
std::swap(used_allocations[used_allocation_count], available_allocations[best_fit_index]);
std::swap(available_allocations[best_fit_index], available_allocations[available_allocation_count - 1]);
available_allocation_count--;
auto& alloc = used_allocations[used_allocation_count];
for (auto i = 1; i < alloc.num_blocks; i++) {
// create 1 entry per block in used_allocations
used_allocations[used_allocation_count + i] = { alloc.buffer, 0, 0 };
}
current_buffer += (int)used_allocations[used_allocation_count].num_blocks;
actual_blocks = used_allocations[used_allocation_count].num_blocks;
}
used_allocations[0].base_address = 0;
for (auto i = 0; i < actual_blocks; i++) {
if (used_allocation_count + i == 0) {
continue;
}
if (i == 0) { // the first block will have its based_address calculated, the remaining blocks share this address
for (int j = (int)used_allocation_count - 1; j >= 0; j--) {
if (used_allocations[j].num_blocks > 0) {
used_allocations[used_allocation_count].base_address = used_allocations[j].base_address + used_allocations[j].num_blocks * block_size;
break;
}
}
} else {
used_allocations[used_allocation_count + i].base_address = used_allocations[used_allocation_count + i - 1].base_address;
}
}
used_allocation_count += actual_blocks;
return {expected_value};
}
// lock-free bump allocation if there is still space
Result<Buffer, AllocateException> BufferLinearAllocator::allocate_buffer(size_t size, size_t alignment, SourceLocationAtFrame source) {
if (size == 0) {
return { expected_value, Buffer{ .buffer = VK_NULL_HANDLE, .size = 0 } };
}
uint64_t old_needle = needle.load();
uint64_t new_needle = VmaAlignUp(old_needle, alignment) + size;
uint64_t low_buffer = old_needle / block_size;
uint64_t high_buffer = new_needle / block_size;
bool is_straddling = low_buffer != high_buffer;
if (is_straddling) { // boost alignment to place on block start
new_needle = VmaAlignUp(old_needle, block_size) + size;
low_buffer = old_needle / block_size;
high_buffer = new_needle / block_size;
is_straddling = low_buffer != high_buffer;
}
while (!std::atomic_compare_exchange_strong(&needle, &old_needle, new_needle)) { // CAS loop
old_needle = needle.load();
new_needle = VmaAlignUp(old_needle, alignment) + size;
low_buffer = old_needle / block_size;
high_buffer = new_needle / block_size;
is_straddling = low_buffer != high_buffer;
if (is_straddling) { // boost alignment to place on block start
new_needle = VmaAlignUp(old_needle, block_size) + size;
low_buffer = old_needle / block_size;
high_buffer = new_needle / block_size;
is_straddling = low_buffer != high_buffer;
}
}
uint64_t base = new_needle - size;
int base_buffer = (int)(base / block_size);
bool needs_to_create = old_needle == 0 || is_straddling;
if (needs_to_create) {
size_t num_blocks = std::max(high_buffer - low_buffer + (old_needle == 0 ? 1 : 0), static_cast<uint64_t>(1));
while (current_buffer.load() < (int)high_buffer) {
grow(num_blocks, source);
}
assert(base % block_size == 0);
}
// wait for the buffer to be allocated
while (current_buffer.load() < (int)high_buffer) {
};
auto& current_alloc = used_allocations[base_buffer];
auto offset = base - current_alloc.base_address;
Buffer b = current_alloc.buffer;
b.offset += offset;
b.size = size;
b.mapped_ptr = b.mapped_ptr != nullptr ? b.mapped_ptr + offset : nullptr;
b.device_address = b.device_address != 0 ? b.device_address + offset : 0;
return { expected_value, b };
}
void BufferLinearAllocator::reset() {
std::lock_guard _(mutex);
for (size_t i = 0; i < used_allocation_count;) {
available_allocations[available_allocation_count++] = used_allocations[i];
i += used_allocations[i].num_blocks;
}
used_allocations = {};
used_allocation_count = 0;
current_buffer = -1;
needle = 0;
}
// we just destroy the buffers that we have left in the available allocations
void BufferLinearAllocator::trim() {
std::lock_guard _(mutex);
for (size_t i = 0; i < available_allocation_count; i++) {
auto& alloc = available_allocations[i];
if (alloc.num_blocks > 0) {
upstream->deallocate_buffers(std::span{ &alloc.buffer, 1 });
}
}
available_allocation_count = 0;
}
BufferLinearAllocator::~BufferLinearAllocator() {
free();
}
void BufferLinearAllocator::free() {
for (size_t i = 0; i < used_allocation_count; i++) {
auto& buf = used_allocations[i].buffer;
if (buf && used_allocations[i].num_blocks > 0) {
upstream->deallocate_buffers(std::span{ &buf, 1 });
}
}
used_allocation_count = 0;
for (size_t i = 0; i < available_allocation_count; i++) {
auto& buf = available_allocations[i].buffer;
if (buf && available_allocations[i].num_blocks > 0) {
upstream->deallocate_buffers(std::span{ &buf, 1 });
}
}
available_allocation_count = 0;
}
Result<Buffer, AllocateException> BufferSubAllocator::allocate_buffer(size_t size, size_t alignment, SourceLocationAtFrame source) {
std::lock_guard _(mutex);
VmaVirtualAllocation va;
VkDeviceSize offset;
VmaVirtualAllocationCreateInfo vaci{};
vaci.size = size + alignment;
vaci.alignment = 0; // VMA does not handle NPOT alignment
std::vector<VmaVirtualAllocation> straddlers;
bool is_straddling = true;
while (is_straddling) {
auto result = vmaVirtualAllocate(virtual_alloc, &vaci, &va, &offset);
if (result != VK_SUCCESS) { // this must always succeed, we have 128 GiB memory to allocate from
return { expected_error, AllocateException(result) };
}
is_straddling = offset / block_size != (offset + vaci.size) / block_size;
if (is_straddling) {
straddlers.push_back(va);
}
}
for (auto& s : straddlers) {
vmaVirtualFree(virtual_alloc, s);
}
auto block_index = offset / block_size;
if (blocks.size() <= block_index) {
blocks.resize(block_index + 1);
}
if (!blocks[block_index].buffer) {
BufferCreateInfo bci{ .mem_usage = mem_usage, .size = block_size, .alignment = 256 };
auto result = upstream->allocate_buffers(std::span{ &blocks[block_index].buffer, 1 }, std::span{ &bci, 1 }, source);
if (!result) {
return result;
}
}
auto aligned_offset = VmaAlignUp(offset - block_index * block_size, alignment);
Buffer buf = blocks[block_index].buffer.add_offset(aligned_offset);
assert(buf.offset % alignment == 0);
assert((buf.offset + size) < block_size);
buf.size = size;
buf.allocation = new SubAllocation{ block_index, va };
blocks[block_index].allocation_count++;
return { expected_value, buf };
}
void BufferSubAllocator::deallocate_buffer(const Buffer& buf) {
std::lock_guard _(mutex);
auto sa = static_cast<SubAllocation*>(buf.allocation);
vmaVirtualFree(virtual_alloc, sa->allocation);
if (--blocks[sa->block_index].allocation_count == 0) {
upstream->deallocate_buffers(std::span{ &blocks[sa->block_index].buffer, 1 });
blocks[sa->block_index].buffer = {};
}
delete sa;
}
BufferSubAllocator::BufferSubAllocator(DeviceResource& upstream, MemoryUsage mem_usage, BufferUsageFlags buf_usage, size_t block_size) :
upstream(&upstream),
mem_usage(mem_usage),
usage(buf_usage),
block_size(block_size) {
VmaVirtualBlockCreateInfo vbci{};
vbci.size = 1024ULL * 1024 * 1024 * 128; // 128 GiB baybeh
auto result2 = vmaCreateVirtualBlock(&vbci, &virtual_alloc);
assert(result2 == VK_SUCCESS);
}
BufferSubAllocator::~BufferSubAllocator() {
assert(vmaIsVirtualBlockEmpty(virtual_alloc));
vmaDestroyVirtualBlock(virtual_alloc);
}
} // namespace vuk<file_sep>if(doctest_force_link_static_lib_in_target_included)
return()
endif()
set(doctest_force_link_static_lib_in_target_included true)
cmake_minimum_required(VERSION 3.0)
# includes the file to the source with compiler flags
function(doctest_include_file_in_sources header sources)
foreach(src ${sources})
if(${src} MATCHES \\.\(cc|cp|cpp|CPP|c\\+\\+|cxx\)$)
# get old flags
get_source_file_property(old_compile_flags ${src} COMPILE_FLAGS)
if(old_compile_flags STREQUAL "NOTFOUND")
set(old_compile_flags "")
endif()
# update flags
if(MSVC)
set_source_files_properties(${src} PROPERTIES COMPILE_FLAGS
"${old_compile_flags} /FI\"${header}\"")
else()
set_source_files_properties(${src} PROPERTIES COMPILE_FLAGS
"${old_compile_flags} -include \"${header}\"")
endif()
endif()
endforeach()
endfunction()
# this is the magic function - forces every object file from the library to be linked into the target (dll or executable)
# it doesn't work in 2 scenarios:
# - either the target or the library uses a precompiled header - see the end of this issue for details: https://github.com/doctest/doctest/issues/21
# - either the target or the library is an imported target (pre-built) and not built within the current cmake tree
# Alternatives:
# - use CMake object libraries instead of static libraries - >> THIS IS ACTUALLY PREFERRED << to all this CMake trickery
# - checkout these 2 repositories:
# - https://github.com/pthom/cmake_registertest
# - https://github.com/pthom/doctest_registerlibrary
function(doctest_force_link_static_lib_in_target target lib)
# check if the library has generated dummy headers
get_target_property(DDH ${lib} DOCTEST_DUMMY_HEADER)
get_target_property(LIB_NAME ${lib} NAME)
if(${DDH} STREQUAL "DDH-NOTFOUND")
# figure out the paths and names of the dummy headers - should be in the build folder for the target
set(BD ${CMAKE_CURRENT_BINARY_DIR})
if(NOT CMAKE_VERSION VERSION_LESS 3.4)
get_target_property(BD ${lib} BINARY_DIR) # 'BINARY_DIR' target property unsupported before CMake 3.4 ...
endif()
set(dummy_dir ${BD}/${LIB_NAME}_DOCTEST_STATIC_LIB_FORCE_LINK_DUMMIES/)
set(dummy_header ${dummy_dir}/all_dummies.h)
file(MAKE_DIRECTORY ${dummy_dir})
# create a dummy header for each source file, include a dummy function in it and include it in the source file
set(curr_dummy "0")
set(DLL_PRIVATE "#ifndef _WIN32\n#define DLL_PRIVATE __attribute__ ((visibility (\"hidden\")))\n#else\n#define DLL_PRIVATE\n#endif\n\n")
get_target_property(lib_sources ${lib} SOURCES)
foreach(src ${lib_sources})
if(${src} MATCHES \\.\(cc|cp|cpp|CPP|c\\+\\+|cxx\)$)
math(EXPR curr_dummy "${curr_dummy} + 1")
set(curr_dummy_header ${dummy_dir}/dummy_${curr_dummy}.h)
file(WRITE ${curr_dummy_header} "${DLL_PRIVATE}namespace doctest { namespace detail { DLL_PRIVATE int dummy_for_${LIB_NAME}_${curr_dummy}(); DLL_PRIVATE int dummy_for_${LIB_NAME}_${curr_dummy}() { return ${curr_dummy}; } } }\n")
doctest_include_file_in_sources(${curr_dummy_header} ${src})
endif()
endforeach()
set(total_dummies ${curr_dummy})
# create the master dummy header
file(WRITE ${dummy_header} "${DLL_PRIVATE}namespace doctest { namespace detail {\n\n")
# forward declare the dummy functions in the master dummy header
foreach(curr_dummy RANGE 1 ${total_dummies})
file(APPEND ${dummy_header} "DLL_PRIVATE int dummy_for_${LIB_NAME}_${curr_dummy}();\n")
endforeach()
# call the dummy functions in the master dummy header
file(APPEND ${dummy_header} "\nDLL_PRIVATE int dummies_for_${LIB_NAME}();\nDLL_PRIVATE int dummies_for_${LIB_NAME}() {\n int res = 0;\n")
foreach(curr_dummy RANGE 1 ${total_dummies})
file(APPEND ${dummy_header} " res += dummy_for_${LIB_NAME}_${curr_dummy}();\n")
endforeach()
file(APPEND ${dummy_header} " return res;\n}\n\n} } // namespaces\n")
# set the dummy header property so we don't recreate the dummy headers the next time this macro is called for this library
set_target_properties(${lib} PROPERTIES DOCTEST_DUMMY_HEADER ${dummy_header})
set(DDH ${dummy_header})
endif()
get_target_property(DFLLTD ${target} DOCTEST_FORCE_LINKED_LIBRARIES_THROUGH_DUMMIES)
get_target_property(target_sources ${target} SOURCES)
if("${DFLLTD}" STREQUAL "DFLLTD-NOTFOUND")
# if no library has been force linked to this target
foreach(src ${target_sources})
if(${src} MATCHES \\.\(cc|cp|cpp|CPP|c\\+\\+|cxx\)$)
doctest_include_file_in_sources(${DDH} ${src})
break()
endif()
endforeach()
# add the library as force linked to this target
set_target_properties(${target} PROPERTIES DOCTEST_FORCE_LINKED_LIBRARIES_THROUGH_DUMMIES ${LIB_NAME})
else()
# if this particular library hasn't been force linked to this target
list(FIND DFLLTD ${LIB_NAME} lib_forced_in_target)
if(${lib_forced_in_target} EQUAL -1)
foreach(src ${target_sources})
if(${src} MATCHES \\.\(cc|cp|cpp|CPP|c\\+\\+|cxx\)$)
doctest_include_file_in_sources(${DDH} ${src})
break()
endif()
endforeach()
# add this library to the list of force linked libraries for this target
list(APPEND DFLLTD ${LIB_NAME})
set_target_properties(${target} PROPERTIES DOCTEST_FORCE_LINKED_LIBRARIES_THROUGH_DUMMIES "${DFLLTD}")
else()
message(AUTHOR_WARNING "LIBRARY \"${lib}\" ALREADY FORCE-LINKED TO TARGET \"${target}\"!")
endif()
endif()
endfunction()
# a utility function to create an executable for a static library with tests - as requested by https://github.com/pthom
function(doctest_make_exe_for_static_lib exe_name lib_name)
set(exe_dir ${CMAKE_CURRENT_BINARY_DIR}/${exe_name}_generated_sources)
file(MAKE_DIRECTORY ${exe_dir})
file(WRITE ${exe_dir}/main.cpp "#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#include \"doctest.h\"\n")
add_executable(${exe_name} ${exe_dir}/main.cpp)
target_link_libraries(${exe_name} ${lib_name})
doctest_force_link_static_lib_in_target(${exe_name} ${lib_name})
add_test(NAME ${exe_name} COMMAND $<TARGET_FILE:${exe_name}>)
endfunction()
<file_sep>#pragma once
#include "../src/CreateInfo.hpp"
#include "Pipeline.hpp"
#include "vuk/Buffer.hpp"
#include "vuk/Config.hpp"
#include "vuk/FixedVector.hpp"
#include "vuk/Hash.hpp"
#include <bit>
inline bool operator==(VkSpecializationMapEntry const& lhs, VkSpecializationMapEntry const& rhs) noexcept {
return (lhs.constantID == rhs.constantID) && (lhs.offset == rhs.offset) && (lhs.size == rhs.size);
}
namespace vuk {
struct GraphicsPipelineInstanceCreateInfo {
PipelineBaseInfo* base;
VkRenderPass render_pass;
uint16_t dynamic_state_flags : 6;
uint16_t extended_size = 0;
struct RecordsExist {
uint32_t nonzero_subpass : 1;
uint32_t vertex_input : 1;
uint32_t color_blend_attachments : 1;
uint32_t broadcast_color_blend_attachment_0 : 1;
uint32_t logic_op : 1;
uint32_t blend_constants : 1;
uint32_t specialization_constants : 1;
uint32_t viewports : 1;
uint32_t scissors : 1;
uint32_t non_trivial_raster_state : 1;
uint32_t depth_stencil : 1;
uint32_t depth_bias : 1;
uint32_t depth_bias_enable : 1;
uint32_t depth_bounds : 1;
uint32_t stencil_state : 1;
uint32_t line_width_not_1 : 1;
uint32_t more_than_one_sample : 1;
uint32_t conservative_rasterization_enabled : 1;
} records = {};
uint32_t attachmentCount : std::bit_width(VUK_MAX_COLOR_ATTACHMENTS); // up to VUK_MAX_COLOR_ATTACHMENTS attachments
// input assembly state
uint32_t topology : std::bit_width(10u);
uint32_t primitive_restart_enable : 1;
VkCullModeFlags cullMode : 2;
union {
std::byte inline_data[80];
std::byte* extended_data;
};
#pragma pack(push, 1)
struct VertexInputBindingDescription {
uint32_t stride : 31;
uint32_t inputRate : 1;
uint8_t binding;
};
struct VertexInputAttributeDescription {
Format format;
uint32_t offset;
uint8_t location;
uint8_t binding;
};
struct PipelineColorBlendAttachmentState {
Bool32 blendEnable : 1;
BlendFactor srcColorBlendFactor : std::bit_width(18u);
BlendFactor dstColorBlendFactor : std::bit_width(18u);
BlendOp colorBlendOp : std::bit_width(5u); // not supporting blend op zoo yet
BlendFactor srcAlphaBlendFactor : std::bit_width(18u);
BlendFactor dstAlphaBlendFactor : std::bit_width(18u);
BlendOp alphaBlendOp : std::bit_width(5u); // not supporting blend op zoo yet
uint32_t colorWriteMask : 4;
};
// blend state
struct BlendStateLogicOp {
uint32_t logic_op : std::bit_width(16u);
};
struct RasterizationState {
uint8_t depthClampEnable : 1;
uint8_t rasterizerDiscardEnable : 1;
uint8_t polygonMode : 2;
uint8_t frontFace : 1;
};
struct ConservativeState {
uint8_t conservativeMode : 2;
float overestimationAmount;
};
struct DepthBias {
float depthBiasConstantFactor;
float depthBiasClamp;
float depthBiasSlopeFactor;
};
struct Depth {
uint8_t depthTestEnable : 1;
uint8_t depthWriteEnable : 1;
uint8_t depthCompareOp : std::bit_width(7u);
};
struct DepthBounds {
float minDepthBounds;
float maxDepthBounds;
};
struct Stencil {
VkStencilOpState front;
VkStencilOpState back;
};
struct Multisample {
uint32_t rasterization_samples : 7;
bool sample_shading_enable : 1;
// pSampleMask not yet supported
bool alpha_to_coverage_enable : 1;
bool alpha_to_one_enable : 1;
float min_sample_shading;
};
#pragma pack(pop)
bool operator==(const GraphicsPipelineInstanceCreateInfo& o) const noexcept {
return base == o.base && render_pass == o.render_pass && extended_size == o.extended_size && attachmentCount == o.attachmentCount &&
topology == o.topology && primitive_restart_enable == o.primitive_restart_enable && cullMode == o.cullMode &&
(is_inline() ? (memcmp(inline_data, o.inline_data, extended_size) == 0) : (memcmp(extended_data, o.extended_data, extended_size) == 0));
}
bool is_inline() const noexcept {
return extended_size <= sizeof(inline_data);
}
};
struct GraphicsPipelineInfo {
PipelineBaseInfo* base;
VkPipeline pipeline;
VkPipelineLayout pipeline_layout;
std::array<DescriptorSetLayoutAllocInfo, VUK_MAX_SETS> layout_info = {};
};
template<>
struct create_info<GraphicsPipelineInfo> {
using type = vuk::GraphicsPipelineInstanceCreateInfo;
};
struct ComputePipelineInstanceCreateInfo {
PipelineBaseInfo* base;
std::array<std::byte, VUK_MAX_SPECIALIZATIONCONSTANT_SIZE> specialization_constant_data = {};
vuk::fixed_vector<VkSpecializationMapEntry, VUK_MAX_SPECIALIZATIONCONSTANT_RANGES> specialization_map_entries;
VkSpecializationInfo specialization_info = {};
bool operator==(const ComputePipelineInstanceCreateInfo& o) const noexcept {
return base == o.base && specialization_map_entries == o.specialization_map_entries && specialization_info.dataSize == o.specialization_info.dataSize &&
memcmp(specialization_constant_data.data(), o.specialization_constant_data.data(), specialization_info.dataSize) == 0;
}
};
struct ComputePipelineInfo : GraphicsPipelineInfo {
std::array<unsigned, 3> local_size;
};
template<>
struct create_info<ComputePipelineInfo> {
using type = vuk::ComputePipelineInstanceCreateInfo;
};
struct RayTracingPipelineInstanceCreateInfo {
PipelineBaseInfo* base;
std::array<std::byte, VUK_MAX_SPECIALIZATIONCONSTANT_SIZE> specialization_constant_data = {};
vuk::fixed_vector<VkSpecializationMapEntry, VUK_MAX_SPECIALIZATIONCONSTANT_RANGES> specialization_map_entries;
VkSpecializationInfo specialization_info = {};
bool operator==(const RayTracingPipelineInstanceCreateInfo& o) const noexcept {
return base == o.base && specialization_map_entries == o.specialization_map_entries && specialization_info.dataSize == o.specialization_info.dataSize &&
memcmp(specialization_constant_data.data(), o.specialization_constant_data.data(), specialization_info.dataSize) == 0;
}
};
struct RayTracingPipelineInfo : GraphicsPipelineInfo {
VkStridedDeviceAddressRegionKHR rgen_region{};
VkStridedDeviceAddressRegionKHR miss_region{};
VkStridedDeviceAddressRegionKHR hit_region{};
VkStridedDeviceAddressRegionKHR call_region{};
Buffer sbt;
};
template<>
struct create_info<RayTracingPipelineInfo> {
using type = vuk::RayTracingPipelineInstanceCreateInfo;
};
} // namespace vuk
namespace std {
template<>
struct hash<vuk::GraphicsPipelineInstanceCreateInfo> {
size_t operator()(vuk::GraphicsPipelineInstanceCreateInfo const& x) const noexcept;
};
template<>
struct hash<VkSpecializationMapEntry> {
size_t operator()(VkSpecializationMapEntry const& x) const noexcept;
};
template<>
struct hash<vuk::ComputePipelineInstanceCreateInfo> {
size_t operator()(vuk::ComputePipelineInstanceCreateInfo const& x) const noexcept;
};
template<>
struct hash<vuk::RayTracingPipelineInstanceCreateInfo> {
size_t operator()(vuk::RayTracingPipelineInstanceCreateInfo const& x) const noexcept;
};
template<>
struct hash<VkPushConstantRange> {
size_t operator()(VkPushConstantRange const& x) const noexcept;
};
template<>
struct hash<vuk::PipelineLayoutCreateInfo> {
size_t operator()(vuk::PipelineLayoutCreateInfo const& x) const noexcept;
};
}; // namespace std
<file_sep>#include "bench_runner.hpp"
#include "../src/RenderGraphUtil.hpp"
std::vector<std::string> chosen_resource;
vuk::BenchRunner::BenchRunner() {
vkb::InstanceBuilder builder;
builder
.set_debug_callback([](VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) -> VkBool32 {
auto ms = vkb::to_string_message_severity(messageSeverity);
auto mt = vkb::to_string_message_type(messageType);
printf("[%s: %s](user defined)\n%s\n", ms, mt, pCallbackData->pMessage);
return VK_FALSE;
})
.set_app_name("vuk_bench")
.set_engine_name("vuk")
.require_api_version(1, 2, 0)
.set_app_version(0, 1, 0);
auto inst_ret = builder.build();
if (!inst_ret.has_value()) {
// error
}
vkbinstance = inst_ret.value();
auto instance = vkbinstance.instance;
vkb::PhysicalDeviceSelector selector{ vkbinstance };
window = create_window_glfw("vuk-benchmarker", false);
surface = create_surface_glfw(vkbinstance.instance, window);
selector.set_surface(surface).set_minimum_version(1, 0).add_required_extension(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME);
auto phys_ret = selector.select();
if (!phys_ret.has_value()) {
// error
}
vkb::PhysicalDevice vkbphysical_device = phys_ret.value();
physical_device = vkbphysical_device.physical_device;
vkb::DeviceBuilder device_builder{ vkbphysical_device };
VkPhysicalDeviceVulkan12Features vk12features{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES };
vk12features.timelineSemaphore = true;
vk12features.descriptorBindingPartiallyBound = true;
vk12features.descriptorBindingUpdateUnusedWhilePending = true;
vk12features.shaderSampledImageArrayNonUniformIndexing = true;
vk12features.runtimeDescriptorArray = true;
vk12features.descriptorBindingVariableDescriptorCount = true;
vk12features.hostQueryReset = true;
VkPhysicalDeviceSynchronization2FeaturesKHR sync_feat{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR, .synchronization2 = true };
auto dev_ret = device_builder.add_pNext(&vk12features).add_pNext(&sync_feat).build();
if (!dev_ret.has_value()) {
// error
}
vkbdevice = dev_ret.value();
graphics_queue = vkbdevice.get_queue(vkb::QueueType::graphics).value();
auto graphics_queue_family_index = vkbdevice.get_queue_index(vkb::QueueType::graphics).value();
device = vkbdevice.device;
context.emplace(ContextCreateParameters{ instance, device, physical_device, graphics_queue, graphics_queue_family_index });
const unsigned num_inflight_frames = 3;
xdev_rf_alloc.emplace(*context, num_inflight_frames);
global.emplace(*xdev_rf_alloc);
swapchain = context->add_swapchain(util::make_swapchain(vkbdevice, {}));
}
constexpr unsigned stage_wait = 0;
constexpr unsigned stage_warmup = 1;
constexpr unsigned stage_variance = 2;
constexpr unsigned stage_live = 3;
constexpr unsigned stage_complete = 4;
void vuk::BenchRunner::render() {
Compiler compiler;
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
auto& xdev_frame_resource = xdev_rf_alloc->get_next_frame();
context->next_frame();
Allocator frame_allocator(xdev_frame_resource);
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(ImGui::GetIO().DisplaySize.x - 552.f, 2));
ImGui::SetNextWindowSize(ImVec2(550, 0));
ImGui::Begin("Benchmark", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoResize);
ImGui::Text("%s", bench->name.data());
ImGui::SameLine();
if (current_stage == 0 && ImGui::Button("Start")) {
current_stage = 1;
}
ImGui::NewLine();
ImGui::Separator();
for (auto i = 0; i < bench->num_cases; i++) {
auto& bcase = bench->get_case(i);
if (ImGui::CollapsingHeader(bcase.label.data(), ImGuiTreeNodeFlags_DefaultOpen)) {
for (auto j = 0; j < bcase.subcases.size(); j++) {
bool sel = current_case == i && current_subcase == j;
ImVec2 size = ImVec2(0.f, 0.f);
uint32_t runs;
if (current_stage == stage_warmup) {
runs = 50;
} else if (current_stage == stage_variance) {
runs = 50;
} else if (current_stage == stage_live) {
runs = bcase.runs_required[j];
} else {
runs = num_runs;
}
if (sel && current_stage != stage_wait && current_stage != stage_complete) {
size.x = (float)num_runs / runs * ImGui::GetContentRegionAvail().x;
}
ImGui::Selectable(bcase.subcase_labels[j].data(), &sel, sel ? 0 : ImGuiSelectableFlags_Disabled, size);
ImGui::Indent();
auto& lsr = bcase.last_stage_ran[j];
bool w = sel && current_stage == stage_warmup;
std::string l1 = "Warmup";
if (lsr > stage_warmup) {
l1 += " - done";
} else if (w) {
l1 += " (" + std::to_string(num_runs) + " / " + std::to_string(runs) + ")";
}
ImGui::Selectable(l1.c_str(), &w, w ? 0 : ImGuiSelectableFlags_Disabled);
w = sel && current_stage == stage_variance;
std::string l2 = "Variance estimation";
if (w) {
l2 = "Estimating variance (" + std::to_string(num_runs) + " / " + std::to_string(runs) + ")";
} else if (lsr > stage_variance) {
l2 = "Estimate (mu=" + std::to_string(bcase.est_mean[j] * 1e6) + " us, sigma=" + std::to_string(bcase.est_variance[j] * 1e12) +
" us2, runs: " + std::to_string(bcase.runs_required[j]) + ")";
}
ImGui::Selectable(l2.c_str(), &w, w ? 0 : ImGuiSelectableFlags_Disabled);
w = sel && current_stage == stage_live;
std::string l3 = "Sampling";
if (w) {
l3 = "Sampling (" + std::to_string(num_runs) + " / " + std::to_string(runs) + ")";
} else if (lsr > stage_live) {
l3 = "Result (mu=" + std::to_string(bcase.mean[j] * 1e6) + " us, sigma=" + std::to_string(bcase.variance[j] * 1e12) +
" us2, SEM = " + std::to_string(sqrt(bcase.variance[j] * 1e12 / sqrt(bcase.runs_required[j]))) + " us)";
}
ImGui::Selectable(l3.c_str(), &w, w ? 0 : ImGuiSelectableFlags_Disabled);
if (lsr > stage_live) {
ImGui::PlotHistogram("Bins", bcase.binned[j].data(), (int)bcase.binned[j].size());
}
ImGui::Unindent();
}
}
}
bench->gui(*this, frame_allocator);
ImGui::End();
auto& bench_case = bench->get_case(current_case);
auto& subcase = bench_case.subcases[current_subcase];
auto rg = std::make_shared<vuk::RenderGraph>(subcase(*this, frame_allocator, start, end));
ImGui::Render();
vuk::Name attachment_name = "_final";
rg->attach_swapchain("_swp", swapchain);
rg->clear_image("_swp", attachment_name, vuk::ClearColor{ 0.3f, 0.5f, 0.3f, 1.0f });
auto fut = util::ImGui_ImplVuk_Render(frame_allocator, Future{ rg, "_final+" }, imgui_data, ImGui::GetDrawData(), sampled_images);
present(frame_allocator, compiler, swapchain, std::move(fut));
sampled_images.clear();
std::optional<double> duration = context->retrieve_duration(start, end);
auto& bcase = bench->get_case(current_case);
if (!duration) {
continue;
} else if (current_stage != stage_complete && current_stage != stage_wait) {
bcase.timings[current_subcase].push_back(*duration);
num_runs++;
}
// transition between stages
if (current_stage == stage_warmup && num_runs >= 50) {
current_stage++;
bcase.last_stage_ran[current_subcase]++;
bcase.last_stage_ran[current_subcase]++;
double& mean = bcase.est_mean[current_subcase];
mean = 0;
for (auto& t : bcase.timings[current_subcase]) {
mean += t;
}
num_runs = 0;
bcase.timings[current_subcase].clear();
} else if (current_stage == stage_variance && num_runs >= 50) {
double& mean = bcase.est_mean[current_subcase];
mean = 0;
for (auto& t : bcase.timings[current_subcase]) {
mean += t;
}
mean /= num_runs;
double& variance = bcase.est_variance[current_subcase];
variance = 0;
for (auto& t : bcase.timings[current_subcase]) {
variance += (t - mean) * (t - mean);
}
variance *= 1.0 / (num_runs - 1);
const auto Z = 1.96; // 95% confidence
bcase.runs_required[current_subcase] = (uint32_t)std::ceil(4 * Z * Z * variance / ((0.1 * mean) * (0.1 * mean)));
// run at least 128 iterations
bcase.runs_required[current_subcase] = std::max(bcase.runs_required[current_subcase], 128u);
current_stage++;
bcase.last_stage_ran[current_subcase]++;
// reuse timings for subsequent live
} else if (current_stage == stage_live && num_runs >= bcase.runs_required[current_subcase]) {
double& mean = bcase.mean[current_subcase];
mean = 0;
double& min = bcase.min_max[current_subcase].first;
min = DBL_MAX;
double& max = bcase.min_max[current_subcase].second;
max = 0;
for (auto& t : bcase.timings[current_subcase]) {
mean += t;
min = std::min(min, t);
max = std::max(max, t);
}
mean /= num_runs;
auto& bins = bcase.binned[current_subcase];
bins.resize(64);
double& variance = bcase.variance[current_subcase];
variance = 0;
for (auto& t : bcase.timings[current_subcase]) {
variance += (t - mean) * (t - mean);
auto bin_index = (uint32_t)std::floor((bins.size() - 1) * (t - min) / (max - min));
bins[bin_index]++;
}
variance *= 1.0 / (num_runs - 1);
bcase.last_stage_ran[current_subcase]++;
//TODO: https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test
if (bcase.subcases.size() > current_subcase + 1) {
current_subcase++;
current_stage = 1;
num_runs = 0;
continue;
}
if (bench->num_cases > current_case + 1) {
current_case++;
current_subcase = 0;
current_stage = 1;
num_runs = 0;
continue;
}
current_stage = 0;
current_case = 0;
current_subcase = 0;
}
}
}
int main() {
vuk::BenchRunner::get_runner().setup();
vuk::BenchRunner::get_runner().render();
vuk::BenchRunner::get_runner().cleanup();
}
<file_sep>#pragma once
#include "../src/ToIntegral.hpp"
#include "CreateInfo.hpp"
#include "RenderPass.hpp"
#include "vuk/Hash.hpp"
#include "vuk/Pipeline.hpp"
#include "vuk/Program.hpp"
#include "vuk/Types.hpp"
#include <atomic>
#include <optional>
#include <span>
#include <unordered_map>
#include <utility>
#include <vector>
#include <robin_hood.h>
namespace std {
template<>
struct hash<VkVertexInputBindingDescription> {
size_t operator()(VkVertexInputBindingDescription const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.binding, x.inputRate, x.stride);
return h;
}
};
template<>
struct hash<VkVertexInputAttributeDescription> {
size_t operator()(VkVertexInputAttributeDescription const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.binding, x.format, x.location, x.offset);
return h;
}
};
template<>
struct hash<VkPipelineTessellationStateCreateInfo> {
size_t operator()(VkPipelineTessellationStateCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.flags, x.patchControlPoints);
return h;
}
};
template<>
struct hash<vuk::Extent2D> {
size_t operator()(vuk::Extent2D const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.width, x.height);
return h;
}
};
template<>
struct hash<vuk::Extent3D> {
size_t operator()(vuk::Extent3D const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.width, x.height, x.depth);
return h;
}
};
template<>
struct hash<vuk::Offset2D> {
size_t operator()(vuk::Offset2D const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.x, x.y);
return h;
}
};
template<>
struct hash<VkRect2D> {
size_t operator()(VkRect2D const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.extent, x.offset);
return h;
}
};
template<>
struct hash<VkExtent2D> {
size_t operator()(VkExtent2D const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.width, x.height);
return h;
}
};
template<>
struct hash<VkExtent3D> {
size_t operator()(VkExtent3D const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.width, x.height, x.depth);
return h;
}
};
template<>
struct hash<VkOffset2D> {
size_t operator()(VkOffset2D const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.x, x.y);
return h;
}
};
template<>
struct hash<VkViewport> {
size_t operator()(VkViewport const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.x, x.y, x.width, x.height, x.minDepth, x.maxDepth);
return h;
}
};
template<>
struct hash<VkAttachmentDescription> {
size_t operator()(VkAttachmentDescription const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.flags, x.initialLayout, x.finalLayout, x.format, x.loadOp, x.stencilLoadOp, x.storeOp, x.stencilStoreOp, x.samples);
return h;
}
};
template<>
struct hash<VkAttachmentReference> {
size_t operator()(VkAttachmentReference const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.attachment, x.layout);
return h;
}
};
template<>
struct hash<VkSubpassDependency> {
size_t operator()(VkSubpassDependency const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.dependencyFlags, x.srcAccessMask, x.srcStageMask, x.srcSubpass, x.dstAccessMask, x.dstStageMask, x.dstSubpass);
return h;
}
};
template<>
struct hash<vuk::ImageCreateInfo> {
size_t operator()(vuk::ImageCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h,
x.flags,
x.arrayLayers,
x.extent,
to_integral(x.format),
to_integral(x.imageType),
to_integral(x.initialLayout),
x.mipLevels,
std::span(x.pQueueFamilyIndices, x.queueFamilyIndexCount),
to_integral(x.samples),
to_integral(x.sharingMode),
to_integral(x.tiling),
x.usage);
return h;
}
};
template<>
struct hash<vuk::CachedImageIdentifier> {
size_t operator()(vuk::CachedImageIdentifier const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.ici, x.id, x.multi_frame_index);
return h;
}
};
template<>
struct hash<vuk::ImageSubresourceRange> {
size_t operator()(vuk::ImageSubresourceRange const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.aspectMask, x.baseArrayLayer, x.baseMipLevel, x.layerCount, x.levelCount);
return h;
}
};
template<>
struct hash<vuk::ComponentMapping> {
size_t operator()(vuk::ComponentMapping const& x) const noexcept {
size_t h = 0;
hash_combine(h, to_integral(x.r), to_integral(x.g), to_integral(x.b), to_integral(x.a));
return h;
}
};
template<>
struct hash<vuk::ImageViewCreateInfo> {
size_t operator()(vuk::ImageViewCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.flags, x.components, to_integral(x.format), reinterpret_cast<uint64_t>((VkImage)x.image), x.subresourceRange, to_integral(x.viewType));
return h;
}
};
template<>
struct hash<vuk::CompressedImageViewCreateInfo> {
size_t operator()(vuk::CompressedImageViewCreateInfo const& x) const noexcept {
return robin_hood::hash_bytes((const char*)&x, sizeof(vuk::CompressedImageViewCreateInfo));
}
};
template<>
struct hash<vuk::SamplerCreateInfo> {
size_t operator()(vuk::SamplerCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h,
x.flags,
x.addressModeU,
x.addressModeV,
x.addressModeW,
x.anisotropyEnable,
x.borderColor,
x.compareEnable,
x.compareOp,
x.magFilter,
x.maxAnisotropy,
x.maxLod,
x.minFilter,
x.minLod,
x.mipLodBias,
x.mipmapMode,
x.unnormalizedCoordinates);
return h;
}
};
}; // namespace std
namespace vuk {
template<class U>
struct CacheImpl;
template<class T>
class Cache {
private:
CacheImpl<T>* impl = nullptr;
public:
using create_fn = T (*)(void*, const create_info_t<T>&);
using destroy_fn = void (*)(void*, const T&);
Cache(void* allocator, create_fn create, destroy_fn destroy);
~Cache();
struct LRUEntry {
T* ptr;
size_t last_use_frame;
std::atomic<uint8_t> load_cnt;
LRUEntry(T* ptr, size_t last_use_frame) : ptr(ptr), last_use_frame(last_use_frame), load_cnt(0) {}
LRUEntry(const LRUEntry& other) : ptr(other.ptr), last_use_frame(other.last_use_frame), load_cnt(other.load_cnt.load()) {}
};
std::optional<T> remove(const create_info_t<T>& ci);
void remove_ptr(const T* ptr);
T& acquire(const create_info_t<T>& ci);
T& acquire(const create_info_t<T>& ci, uint64_t current_frame);
void collect(uint64_t current_frame, size_t threshold);
void clear();
create_fn create;
destroy_fn destroy;
void* allocator;
};
} // namespace vuk
<file_sep>#include "vuk/Util.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/Context.hpp"
#include "vuk/Future.hpp"
#include "vuk/RenderGraph.hpp"
#include "vuk/SampledImage.hpp"
#include <atomic>
#ifndef DOCTEST_CONFIG_DISABLE
#include <doctest/doctest.h>
#endif
#include <mutex>
#include <sstream>
#include <utility>
namespace vuk {
struct QueueImpl {
// TODO: this recursive mutex should be changed to better queue handling
std::recursive_mutex queue_lock;
PFN_vkQueueSubmit queueSubmit;
PFN_vkQueueSubmit2KHR queueSubmit2KHR;
TimelineSemaphore submit_sync;
VkQueue queue;
std::array<std::atomic<uint64_t>, 3> last_device_waits;
std::atomic<uint64_t> last_host_wait;
uint32_t family_index;
QueueImpl(PFN_vkQueueSubmit fn1, PFN_vkQueueSubmit2KHR fn2, VkQueue queue, uint32_t queue_family_index, TimelineSemaphore ts) :
queueSubmit(fn1),
queueSubmit2KHR(fn2),
submit_sync(ts),
queue(queue),
family_index(queue_family_index) {}
};
Queue::Queue(PFN_vkQueueSubmit fn1, PFN_vkQueueSubmit2KHR fn2, VkQueue queue, uint32_t queue_family_index, TimelineSemaphore ts) :
impl(new QueueImpl(fn1, fn2, queue, queue_family_index, ts)) {}
Queue::~Queue() {
delete impl;
}
Queue::Queue(Queue&& o) noexcept : impl(std::exchange(o.impl, nullptr)) {}
Queue& Queue::operator=(Queue&& o) noexcept {
impl = std::exchange(o.impl, nullptr);
return *this;
}
TimelineSemaphore& Queue::get_submit_sync() {
return impl->submit_sync;
}
std::recursive_mutex& Queue::get_queue_lock() {
return impl->queue_lock;
}
Result<void> Queue::submit(std::span<VkSubmitInfo2KHR> sis, VkFence fence) {
VkResult result = impl->queueSubmit2KHR(impl->queue, (uint32_t)sis.size(), sis.data(), fence);
if (result != VK_SUCCESS) {
return { expected_error, VkException{ result } };
}
return { expected_value };
}
Result<void> Queue::submit(std::span<VkSubmitInfo> sis, VkFence fence) {
std::lock_guard _(impl->queue_lock);
VkResult result = impl->queueSubmit(impl->queue, (uint32_t)sis.size(), sis.data(), fence);
if (result != VK_SUCCESS) {
return { expected_error, VkException{ result } };
}
return { expected_value };
}
Result<void> Context::wait_for_domains(std::span<std::pair<DomainFlags, uint64_t>> queue_waits) {
std::array<uint32_t, 3> domain_to_sema_index = { ~0u, ~0u, ~0u };
std::array<VkSemaphore, 3> queue_timeline_semaphores;
std::array<uint64_t, 3> values = {};
uint32_t count = 0;
for (auto [domain, v] : queue_waits) {
auto idx = domain_to_queue_index(domain);
auto& mapping = domain_to_sema_index[idx];
if (mapping == -1) {
mapping = count++;
}
auto& q = domain_to_queue(domain);
queue_timeline_semaphores[mapping] = q.impl->submit_sync.semaphore;
values[mapping] = values[mapping] > v ? values[mapping] : v;
}
VkSemaphoreWaitInfo swi{ .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO };
swi.pSemaphores = queue_timeline_semaphores.data();
swi.pValues = values.data();
swi.semaphoreCount = count;
VkResult result = this->vkWaitSemaphores(device, &swi, UINT64_MAX);
for (auto [domain, v] : queue_waits) {
auto& q = domain_to_queue(domain);
q.impl->last_host_wait.store(v);
}
if (result != VK_SUCCESS) {
return { expected_error, VkException{ result } };
}
return { expected_value };
}
Result<void> link_execute_submit(Allocator& allocator, Compiler& compiler, std::span<std::shared_ptr<RenderGraph>> rgs) {
auto erg = compiler.link(rgs, {});
if (!erg) {
return erg;
}
std::pair erg_and_alloc = std::pair{ &allocator, &*erg };
return execute_submit(allocator, std::span(&erg_and_alloc, 1), {}, {}, {});
}
Result<std::vector<SubmitBundle>> execute(std::span<std::pair<Allocator*, ExecutableRenderGraph*>> ergs,
std::vector<std::pair<SwapchainRef, size_t>> swapchains_with_indexes) {
std::vector<SubmitBundle> bundles;
for (auto& [alloc, rg] : ergs) {
auto sbundle = rg->execute(*alloc, swapchains_with_indexes);
if (!sbundle) {
return Result<std::vector<SubmitBundle>>(std::move(sbundle));
}
bool has_waits = false;
for (auto& batch : sbundle->batches) {
for (auto& s : batch.submits) {
if (s.relative_waits.size() > 0) {
has_waits = true;
}
}
}
// in the case where there are no waits in the entire bundle, we can merge all the submits together
if (!has_waits && bundles.size() > 0) {
auto& last = bundles.back();
for (auto& batch : sbundle->batches) {
auto tgt_domain = batch.domain;
auto it = std::find_if(last.batches.begin(), last.batches.end(), [=](auto& batch) { return batch.domain == tgt_domain; });
if (it != last.batches.end()) {
it->submits.insert(it->submits.end(), batch.submits.begin(), batch.submits.end());
} else {
last.batches.emplace_back(batch);
}
}
} else {
bundles.push_back(*sbundle);
}
}
return { expected_value, bundles };
}
std::string_view to_name(vuk::DomainFlagBits d) {
switch (d) {
case DomainFlagBits::eTransferQueue:
return "Transfer";
case DomainFlagBits::eGraphicsQueue:
return "Graphics";
case DomainFlagBits::eComputeQueue:
return "Compute";
default:
return "Unknown";
}
}
std::string to_dot(SubmitBundle& bundle) {
std::stringstream ss;
ss << "digraph {";
for (auto& batch : bundle.batches) {
ss << "subgraph cluster_" << to_name(batch.domain) << " {";
char name = 'A';
for (size_t i = 0; i < batch.submits.size(); i++) {
ss << to_name(batch.domain)[0] << name << ";";
name++;
}
ss << "}";
}
for (auto& batch : bundle.batches) {
char name = 'A';
for (auto& sub : batch.submits) {
for (auto& wait : sub.relative_waits) {
char dst_name = wait.second == 0 ? 'X' : 'A' + (char)wait.second - 1;
ss << to_name(batch.domain)[0] << name << "->" << to_name(wait.first)[0] << dst_name << ";";
}
name++;
}
}
ss << "}";
return ss.str();
}
void flatten_transfer_and_compute_onto_graphics(SubmitBundle& bundle) {
if (bundle.batches.empty()) {
return;
}
auto domain_to_index = [](vuk::DomainFlagBits d) {
switch (d) {
case DomainFlagBits::eTransferQueue:
return 2;
case DomainFlagBits::eGraphicsQueue:
return 0;
case DomainFlagBits::eComputeQueue:
return 1;
default:
assert(0);
return 4;
}
};
size_t num_submits = 0;
for (auto& batch : bundle.batches) {
num_submits += batch.submits.size();
}
SubmitBatch dst_batch{ .domain = DomainFlagBits::eGraphicsQueue };
uint64_t progress[3] = {};
while (true) {
for (auto& batch : bundle.batches) {
auto queue = (DomainFlagBits)(batch.domain & DomainFlagBits::eQueueMask).m_mask;
auto our_id = domain_to_index(queue);
for (size_t i = progress[our_id]; i < batch.submits.size(); i++) {
auto b = batch.submits[i];
bool all_waits_satisfied = true;
// check if all waits can be satisfied for this submit
for (auto& [queue, wait_id] : b.relative_waits) {
auto q_id = domain_to_index((DomainFlagBits)(queue & DomainFlagBits::eQueueMask).m_mask);
auto& progress_on_wait_queue = progress[q_id];
if (progress_on_wait_queue < wait_id) {
all_waits_satisfied = false;
break;
}
}
if (all_waits_satisfied) {
if (!b.relative_waits.empty()) {
b.relative_waits = { { DomainFlagBits::eGraphicsQueue, dst_batch.submits.size() } }; // collapse into a single wait
}
dst_batch.submits.emplace_back(b);
progress[our_id]++; // retire this batch
} else {
// couldn't make progress
// break here is not correct, because there might be multiple waits with the same rank
// TODO: we need to break here anyways for unsorted - we need to sort
break;
}
}
}
if (dst_batch.submits.size() == num_submits) { // we have moved all the submits to the dst_batch
break;
}
}
bundle.batches = { dst_batch };
}
#ifndef DOCTEST_CONFIG_DISABLE
TEST_CASE("testing flattening submit graphs") {
{
SubmitBundle empty{};
auto before = to_dot(empty);
flatten_transfer_and_compute_onto_graphics(empty);
auto after = to_dot(empty);
CHECK(before == after);
}
{
// transfer : TD -> TC -> TB -> TA
// everything moved to graphics
SubmitBundle only_transfer{ .batches = { SubmitBatch{ .domain = vuk::DomainFlagBits::eTransferQueue,
.submits = { { .relative_waits = {} },
{ .relative_waits = { { vuk::DomainFlagBits::eTransferQueue, 1 } } },
{ .relative_waits = { { vuk::DomainFlagBits::eTransferQueue, 2 } } },
{ .relative_waits = { { vuk::DomainFlagBits::eTransferQueue, 3 } } } } } } };
auto before = to_dot(only_transfer);
flatten_transfer_and_compute_onto_graphics(only_transfer);
auto after = to_dot(only_transfer);
CHECK(after == "digraph {subgraph cluster_Graphics {GA;GB;GC;GD;}GB->GA;GC->GB;GD->GC;}");
}
{
// transfer : TD TC -> TB TA
// v ^ v
// graphics : GD->GC GB->GA
// flattens to
// graphics : TD -> GD -> GC -> TC -> TB -> GB -> GA TA
SubmitBundle two_queue{ .batches = { SubmitBatch{ .domain = vuk::DomainFlagBits::eTransferQueue,
.submits = { { .relative_waits = {} },
{ .relative_waits = { { vuk::DomainFlagBits::eGraphicsQueue, 2 } } },
{ .relative_waits = { { vuk::DomainFlagBits::eTransferQueue, 2 } } },
{ .relative_waits = { { vuk::DomainFlagBits::eGraphicsQueue, 4 } } } } },
SubmitBatch{ .domain = vuk::DomainFlagBits::eGraphicsQueue,
.submits = { { .relative_waits = {} },
{ .relative_waits = { { vuk::DomainFlagBits::eGraphicsQueue, 1 } } },
{ .relative_waits = { { vuk::DomainFlagBits::eTransferQueue, 3 } } },
{ .relative_waits = { { vuk::DomainFlagBits::eGraphicsQueue, 3 } } } } } } };
auto before = to_dot(two_queue);
flatten_transfer_and_compute_onto_graphics(two_queue);
auto after = to_dot(two_queue);
CHECK(after == "digraph {subgraph cluster_Graphics {GA;GB;GC;GD;GE;GF;GG;GH;}GC->GB;GD->GC;GE->GD;GF->GE;GG->GF;GH->GG;}");
}
}
#endif
Result<void> submit(Allocator& allocator, SubmitBundle bundle, VkSemaphore present_rdy, VkSemaphore render_complete) {
Context& ctx = allocator.get_context();
vuk::DomainFlags used_domains;
for (auto& batch : bundle.batches) {
used_domains |= batch.domain;
}
std::array<uint64_t, 3> queue_progress_references;
std::unique_lock<std::recursive_mutex> gfx_lock;
if (used_domains & DomainFlagBits::eGraphicsQueue) {
queue_progress_references[ctx.domain_to_queue_index(DomainFlagBits::eGraphicsQueue)] = *ctx.graphics_queue->impl->submit_sync.value;
gfx_lock = std::unique_lock{ ctx.graphics_queue->impl->queue_lock };
}
std::unique_lock<std::recursive_mutex> compute_lock;
if (used_domains & DomainFlagBits::eComputeQueue) {
queue_progress_references[ctx.domain_to_queue_index(DomainFlagBits::eComputeQueue)] = *ctx.compute_queue->impl->submit_sync.value;
compute_lock = std::unique_lock{ ctx.compute_queue->impl->queue_lock };
}
std::unique_lock<std::recursive_mutex> transfer_lock;
if (used_domains & DomainFlagBits::eTransferQueue) {
queue_progress_references[ctx.domain_to_queue_index(DomainFlagBits::eTransferQueue)] = *ctx.transfer_queue->impl->submit_sync.value;
transfer_lock = std::unique_lock{ ctx.transfer_queue->impl->queue_lock };
}
bool needs_flatten = ((used_domains & DomainFlagBits::eTransferQueue) &&
(ctx.domain_to_queue_index(DomainFlagBits::eTransferQueue) == ctx.domain_to_queue_index(DomainFlagBits::eGraphicsQueue) ||
ctx.domain_to_queue_index(DomainFlagBits::eTransferQueue) == ctx.domain_to_queue_index(DomainFlagBits::eComputeQueue))) ||
((used_domains & DomainFlagBits::eComputeQueue) &&
(ctx.domain_to_queue_index(DomainFlagBits::eComputeQueue) == ctx.domain_to_queue_index(DomainFlagBits::eGraphicsQueue)));
if (needs_flatten) {
bool needs_transfer_compute_flatten =
ctx.domain_to_queue_index(DomainFlagBits::eTransferQueue) == ctx.domain_to_queue_index(DomainFlagBits::eGraphicsQueue) &&
ctx.domain_to_queue_index(DomainFlagBits::eComputeQueue) == ctx.domain_to_queue_index(DomainFlagBits::eGraphicsQueue);
if (needs_transfer_compute_flatten) {
flatten_transfer_and_compute_onto_graphics(bundle);
} else {
assert(false && "NYI");
}
} else {
if (bundle.batches.size() > 1) {
std::swap(bundle.batches[0], bundle.batches[1]); // FIXME: silence some false positive validation
}
}
for (SubmitBatch& batch : bundle.batches) {
auto domain = batch.domain;
Queue& queue = ctx.domain_to_queue(domain);
Unique<VkFence> fence(allocator);
VUK_DO_OR_RETURN(allocator.allocate_fences({ &*fence, 1 }));
uint64_t num_cbufs = 0;
uint64_t num_waits = 1; // 1 extra for present_rdy
for (uint64_t i = 0; i < batch.submits.size(); i++) {
SubmitInfo& submit_info = batch.submits[i];
num_cbufs += submit_info.command_buffers.size();
num_waits += submit_info.relative_waits.size();
num_waits += submit_info.absolute_waits.size();
}
std::vector<VkSubmitInfo2KHR> sis;
std::vector<VkCommandBufferSubmitInfoKHR> cbufsis;
cbufsis.reserve(num_cbufs);
std::vector<VkSemaphoreSubmitInfoKHR> wait_semas;
wait_semas.reserve(num_waits);
std::vector<VkSemaphoreSubmitInfoKHR> signal_semas;
signal_semas.reserve(batch.submits.size() + 1); // 1 extra for render_complete
for (uint64_t i = 0; i < batch.submits.size(); i++) {
SubmitInfo& submit_info = batch.submits[i];
for (auto& fut : submit_info.future_signals) {
fut->status = FutureBase::Status::eSubmitted;
}
if (submit_info.command_buffers.size() == 0) {
continue;
}
for (uint64_t i = 0; i < submit_info.command_buffers.size(); i++) {
cbufsis.emplace_back(
VkCommandBufferSubmitInfoKHR{ .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO_KHR, .commandBuffer = submit_info.command_buffers[i] });
}
uint32_t wait_sema_count = 0;
for (auto& w : submit_info.relative_waits) {
VkSemaphoreSubmitInfoKHR ssi{ VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR };
auto& wait_queue = ctx.domain_to_queue(w.first).impl->submit_sync;
ssi.semaphore = wait_queue.semaphore;
ssi.value = queue_progress_references[ctx.domain_to_queue_index(w.first)] + w.second;
ssi.stageMask = (VkPipelineStageFlagBits2KHR)PipelineStageFlagBits::eAllCommands;
wait_semas.emplace_back(ssi);
wait_sema_count++;
}
for (auto& w : submit_info.absolute_waits) {
VkSemaphoreSubmitInfoKHR ssi{ VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR };
auto& wait_queue = ctx.domain_to_queue(w.first).impl->submit_sync;
ssi.semaphore = wait_queue.semaphore;
ssi.value = w.second;
ssi.stageMask = (VkPipelineStageFlagBits2KHR)PipelineStageFlagBits::eAllCommands;
wait_semas.emplace_back(ssi);
wait_sema_count++;
}
if (domain == DomainFlagBits::eGraphicsQueue && i == 0 && present_rdy != VK_NULL_HANDLE) { // TODO: for first cbuf only that refs the swapchain attment
VkSemaphoreSubmitInfoKHR ssi{ VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR };
ssi.semaphore = present_rdy;
ssi.stageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
wait_semas.emplace_back(ssi);
wait_sema_count++;
}
VkSemaphoreSubmitInfoKHR ssi{ VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR };
ssi.semaphore = queue.impl->submit_sync.semaphore;
ssi.value = ++(*queue.impl->submit_sync.value);
ssi.stageMask = (VkPipelineStageFlagBits2KHR)PipelineStageFlagBits::eAllCommands;
for (auto& fut : submit_info.future_signals) {
fut->status = FutureBase::Status::eSubmitted;
fut->initial_domain = domain;
fut->initial_visibility = ssi.value;
}
uint32_t signal_sema_count = 1;
signal_semas.emplace_back(ssi);
if (domain == DomainFlagBits::eGraphicsQueue && i == batch.submits.size() - 1 &&
render_complete != VK_NULL_HANDLE) { // TODO: for final cbuf only that refs the swapchain attment
ssi.semaphore = render_complete;
ssi.value = 0; // binary sema
signal_semas.emplace_back(ssi);
signal_sema_count++;
}
VkSubmitInfo2KHR& si = sis.emplace_back(VkSubmitInfo2KHR{ VK_STRUCTURE_TYPE_SUBMIT_INFO_2_KHR });
VkCommandBufferSubmitInfoKHR* p_cbuf_infos = &cbufsis.back() - (submit_info.command_buffers.size() - 1);
VkSemaphoreSubmitInfoKHR* p_wait_semas = wait_sema_count > 0 ? &wait_semas.back() - (wait_sema_count - 1) : nullptr;
VkSemaphoreSubmitInfoKHR* p_signal_semas = &signal_semas.back() - (signal_sema_count - 1);
si.pWaitSemaphoreInfos = p_wait_semas;
si.waitSemaphoreInfoCount = wait_sema_count;
si.pCommandBufferInfos = p_cbuf_infos;
si.commandBufferInfoCount = (uint32_t)submit_info.command_buffers.size();
si.pSignalSemaphoreInfos = p_signal_semas;
si.signalSemaphoreInfoCount = signal_sema_count;
}
VUK_DO_OR_RETURN(queue.submit(std::span{ sis }, *fence));
}
return { expected_value };
}
// assume rgs are independent - they don't reference eachother
Result<void> execute_submit(Allocator& allocator,
std::span<std::pair<Allocator*, ExecutableRenderGraph*>> rgs,
std::vector<std::pair<SwapchainRef, size_t>> swapchains_with_indexes,
VkSemaphore present_rdy,
VkSemaphore render_complete) {
auto bundles = execute(rgs, swapchains_with_indexes);
if (!bundles) {
return bundles;
}
for (auto& bundle : *bundles) {
VUK_DO_OR_RETURN(submit(allocator, bundle, present_rdy, render_complete));
}
return { expected_value };
}
Result<VkResult> present_to_one(Context& ctx, SingleSwapchainRenderBundle&& bundle) {
VkPresentInfoKHR pi{ .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
pi.swapchainCount = 1;
pi.pSwapchains = &bundle.swapchain->swapchain;
pi.pImageIndices = &bundle.image_index;
pi.waitSemaphoreCount = 1;
pi.pWaitSemaphores = &bundle.render_complete;
auto present_result = ctx.vkQueuePresentKHR(ctx.graphics_queue->impl->queue, &pi);
if (present_result != VK_SUCCESS && present_result != VK_SUBOPTIMAL_KHR) {
return { expected_error, VkException{ present_result } };
}
if (present_result == VK_SUBOPTIMAL_KHR || bundle.acquire_result == VK_SUBOPTIMAL_KHR) {
return { expected_value, VK_SUBOPTIMAL_KHR };
}
return { expected_value, VK_SUCCESS };
}
Result<SingleSwapchainRenderBundle> acquire_one(Allocator& allocator, SwapchainRef swapchain) {
Context& ctx = allocator.get_context();
Unique<std::array<VkSemaphore, 2>> semas(allocator);
VUK_DO_OR_RETURN(allocator.allocate_semaphores(*semas));
auto [present_rdy, render_complete] = *semas;
uint32_t image_index = (uint32_t)-1;
VkResult acq_result = ctx.vkAcquireNextImageKHR(ctx.device, swapchain->swapchain, UINT64_MAX, present_rdy, VK_NULL_HANDLE, &image_index);
// VK_SUBOPTIMAL_KHR shouldn't stop presentation; it is handled at the end
if (acq_result != VK_SUCCESS && acq_result != VK_SUBOPTIMAL_KHR) {
return { expected_error, VkException{ acq_result } };
}
return { expected_value, SingleSwapchainRenderBundle{ swapchain, image_index, present_rdy, render_complete, acq_result } };
}
Result<SingleSwapchainRenderBundle> acquire_one(Context& ctx, SwapchainRef swapchain, VkSemaphore present_ready, VkSemaphore render_complete) {
uint32_t image_index = (uint32_t)-1;
VkResult acq_result = ctx.vkAcquireNextImageKHR(ctx.device, swapchain->swapchain, UINT64_MAX, present_ready, VK_NULL_HANDLE, &image_index);
// VK_SUBOPTIMAL_KHR shouldn't stop presentation; it is handled at the end
if (acq_result != VK_SUCCESS && acq_result != VK_SUBOPTIMAL_KHR) {
return { expected_error, VkException{ acq_result } };
}
return { expected_value, SingleSwapchainRenderBundle{ swapchain, image_index, present_ready, render_complete, acq_result } };
}
Result<SingleSwapchainRenderBundle> execute_submit(Allocator& allocator, ExecutableRenderGraph&& rg, SingleSwapchainRenderBundle&& bundle) {
std::vector<std::pair<SwapchainRef, size_t>> swapchains_with_indexes = { { bundle.swapchain, bundle.image_index } };
std::pair v = { &allocator, &rg };
VUK_DO_OR_RETURN(execute_submit(allocator, std::span{ &v, 1 }, swapchains_with_indexes, bundle.present_ready, bundle.render_complete));
return { expected_value, std::move(bundle) };
}
Result<VkResult> execute_submit_and_present_to_one(Allocator& allocator, ExecutableRenderGraph&& rg, SwapchainRef swapchain) {
auto bundle = acquire_one(allocator, swapchain);
if (!bundle) {
return bundle;
}
auto bundle2 = execute_submit(allocator, std::move(rg), std::move(*bundle));
if (!bundle2) {
return bundle2;
}
return present_to_one(allocator.get_context(), std::move(*bundle2));
}
Result<void> execute_submit_and_wait(Allocator& allocator, ExecutableRenderGraph&& rg) {
Context& ctx = allocator.get_context();
std::pair v = { &allocator, &rg };
VUK_DO_OR_RETURN(execute_submit(allocator, std::span{ &v, 1 }, {}, {}, {}));
ctx.wait_idle(); // TODO:
return { expected_value };
}
Result<VkResult> present(Allocator& allocator, Compiler& compiler, SwapchainRef swapchain, Future&& future, RenderGraphCompileOptions compile_options) {
auto ptr = future.get_render_graph();
auto erg = compiler.link(std::span{ &ptr, 1 }, compile_options);
if (!erg) {
return erg;
}
return execute_submit_and_present_to_one(allocator, std::move(*erg), swapchain);
}
SampledImage make_sampled_image(ImageView iv, SamplerCreateInfo sci) {
return { SampledImage::Global{ iv, sci, ImageLayout::eReadOnlyOptimalKHR } };
}
SampledImage make_sampled_image(NameReference n, SamplerCreateInfo sci) {
return { SampledImage::RenderGraphAttachment{ n, sci, {}, ImageLayout::eReadOnlyOptimalKHR } };
}
SampledImage make_sampled_image(NameReference n, ImageViewCreateInfo ivci, SamplerCreateInfo sci) {
return { SampledImage::RenderGraphAttachment{ n, sci, ivci, ImageLayout::eReadOnlyOptimalKHR } };
}
Future::Future(std::shared_ptr<struct RenderGraph> org, Name output_binding, DomainFlags dst_domain) :
output_binding(QualifiedName{ {}, output_binding }),
rg(std::move(org)),
control(std::make_shared<FutureBase>()) {
rg->attach_out(QualifiedName{ {}, output_binding }, *this, dst_domain);
}
Future::Future(std::shared_ptr<struct RenderGraph> org, QualifiedName output_binding, DomainFlags dst_domain) :
output_binding(output_binding),
rg(std::move(org)),
control(std::make_shared<FutureBase>()) {
rg->attach_out(output_binding, *this, dst_domain);
}
Future::Future(const Future& o) noexcept : output_binding(o.output_binding), rg(o.rg), control(o.control) {}
Future& Future::operator=(const Future& o) noexcept {
control = o.control;
rg = o.rg;
output_binding = o.output_binding;
return *this;
}
Future::Future(Future&& o) noexcept :
output_binding{ std::exchange(o.output_binding, QualifiedName{}) },
rg{ std::exchange(o.rg, nullptr) },
control{ std::exchange(o.control, nullptr) } {}
Future& Future::operator=(Future&& o) noexcept {
control = std::exchange(o.control, nullptr);
rg = std::exchange(o.rg, nullptr);
output_binding = std::exchange(o.output_binding, QualifiedName{});
return *this;
}
Future::~Future() {
if (rg && rg->impl) {
rg->detach_out(output_binding, *this);
}
}
Result<void> Future::wait(Allocator& allocator, Compiler& compiler) {
if (control->status == FutureBase::Status::eInitial && !rg) {
return { expected_error,
RenderGraphException{} }; // can't get wait for future that has not been attached anything or has been attached into a rendergraph
} else if (control->status == FutureBase::Status::eHostAvailable) {
return { expected_value };
} else if (control->status == FutureBase::Status::eSubmitted) {
std::pair w = { (DomainFlags)control->initial_domain, control->initial_visibility };
allocator.get_context().wait_for_domains(std::span{ &w, 1 });
return { expected_value };
} else {
auto erg = compiler.link(std::span{ &rg, 1 }, {});
if (!erg) {
return erg;
}
std::pair v = { &allocator, &*erg };
VUK_DO_OR_RETURN(execute_submit(allocator, std::span{ &v, 1 }, {}, {}, {}));
std::pair w = { (DomainFlags)control->initial_domain, control->initial_visibility };
allocator.get_context().wait_for_domains(std::span{ &w, 1 });
control->status = FutureBase::Status::eHostAvailable;
return { expected_value };
}
}
template<class T>
Result<T> Future::get(Allocator& allocator, Compiler& compiler) {
if (auto result = wait(allocator, compiler)) {
return { expected_value, get_result<T>() };
} else {
return result;
}
}
Result<void> Future::submit(Allocator& allocator, Compiler& compiler) {
if (control->status == FutureBase::Status::eInitial && !rg) {
return { expected_error, RenderGraphException{} };
} else if (control->status == FutureBase::Status::eHostAvailable || control->status == FutureBase::Status::eSubmitted) {
return { expected_value }; // nothing to do
} else {
control->status = FutureBase::Status::eSubmitted;
auto erg = compiler.link(std::span{ &rg, 1 }, {});
if (!erg) {
return erg;
}
std::pair v = { &allocator, &*erg };
VUK_DO_OR_RETURN(execute_submit(allocator, std::span{ &v, 1 }, {}, {}, {}));
return { expected_value };
}
}
template Result<Buffer> Future::get(Allocator&, Compiler&);
template Result<ImageAttachment> Future::get(Allocator&, Compiler&);
std::string_view image_view_type_to_sv(ImageViewType view_type) noexcept {
switch (view_type) {
case ImageViewType::e1D:
return "1D";
case ImageViewType::e2D:
return "2D";
case ImageViewType::e3D:
return "3D";
case ImageViewType::eCube:
return "Cube";
case ImageViewType::e1DArray:
return "1DArray";
case ImageViewType::e2DArray:
return "2DArray";
case ImageViewType::eCubeArray:
return "CubeArray";
default:
assert(0 && "not reached.");
return "";
}
}
} // namespace vuk
<file_sep>CommandBuffer
=============
The CommandBuffer class offers a convenient abstraction over command recording, pipeline state and descriptor sets of Vulkan.
Setting pipeline state
----------------------
The CommandBuffer encapsulates the current pipeline and descriptor state. When calling state-setting commands, the current state of the CommandBuffer is updated. The state of the CommandBuffer persists for the duration of the execution callback, and there is no state leakage between callbacks of different passes.
The various states of the pipeline can be reconfigured by calling the appropriate function, such as :cpp:func:`vuk::CommandBuffer::set_rasterization()`.
There is no default state - you must explicitly bind all state used for the commands recorded.
Static and dynamic state
------------------------
Vulkan allows some pipeline state to be dynamic. In vuk this is exposed as an optimisation - you may let the CommandBuffer know that certain pipeline state is dynamic by calling :cpp:func:`vuk::CommandBuffer::set_dynamic_state()`. This call changes which states are considered dynamic. Dynamic state is usually cheaper to change than entire pipelines and leads to fewer pipeline compilations, but has more overhead compared to static state - use it when a state changes often. Some state can be set dynamic on some platforms without cost. As with other pipeline state, setting states to be dynamic or static persist only during the callback.
Binding pipelines & specialization constants
--------------------------------------------
The CommandBuffer maintains separate bind points for compute and graphics pipelines. The CommandBuffer also maintains an internal buffer of specialization constants that are applied to the pipeline bound. Changing specialization constants will trigger a pipeline compilation when using the pipeline for the first time.
Binding descriptors & push constants
------------------------------------
vuk allows two types of descriptors to be bound: ephemeral and persistent.
Ephemeral descriptors are bound individually to the CommandBuffer via `bind_XXX()` calls where `XXX` denotes the type of the descriptor (eg. uniform buffer). These descriptors are internally managed by the CommandBuffer and the Allocator it references. Ephemeral descriptors are very convenient to use, but they are limited in the number of bindable descriptors (`VUK_MAX_BINDINGS`) and they incur a small overhead on bind.
Persistent descriptors are managed by the user via allocation of a PersistentDescriptorSet from Allocator and manually updating the contents. There is no limit on the number of descriptors and binding such descriptor sets do not have an overhead over the direct Vulkan call. Large descriptor arrays (such as the ones used in "bindless" techniques) are only possible via persistent descriptor sets.
The number of bindable sets is limited by `VUK_MAX_SETS`. Both ephemeral descriptors and persistent descriptor sets retain their bindings until overwritten, disturbed or the the callback ends.
Push constants can be changed by calling :cpp:func:`vuk::CommandBuffer::push_constants()`.
Vertex buffers and attributes
-----------------------------
While vertex buffers are waning in popularity, vuk still offers a convenient API for most attribute arrangements. If advanced addressing schemes are not required, they can be a convenient alternative to vertex pulling.
The shader declares attributes, which require a `location`. When binding vertex buffers, you are telling vuk where each attribute, corresponding to a `location` can be found.
Each :cpp:func:`vuk::CommandBuffer::bind_vertex_buffer()` binds a single vuk::Buffer, which can contain multiple attributes
The first two arguments to :cpp:func:`vuk::CommandBuffer::bind_vertex_buffer()` specify the index of the vertex buffer binding and buffer to binding to that binding.
(so if you have 1 vertex buffers, you pass 0, if you have 2 vertex buffers, you have 2 calls where you pass 0 and 1 as `binding` - these don't need to start at 0 or be contiguous but they might as well be)
In the second part of the arguments you specify which attributes can be found the vertex buffer that is being bound, what is their format, and what is their offset.
For convenience vuk offers a utility called `vuk::Packed` to describe common vertex buffers that contain interleaved attribute data.
The simplest case is a single attribute per vertex buffer, this is described by calling `bind_vertex_buffer(binding, buffer, location, vuk::Packed{ vuk::Format::eR32G32B32Sfloat })` - with the actual format of the attribute.
Here `vuk::Packed` means that the formats are packed in the buffer, i.e. you have a R32G32B32, then immediately after a R32G32B32, and so on.
If there are multiple interleaved attributes in a buffer, for example it is [position, normal, position, normal], then you can describe this in a very compact way in vuk if the position attribute location and normal attribute location is consecutive: `bind_vertex_buffer(binding, buffer, first_location, vuk::Packed{ vuk::Format::eR32G32B32Sfloat, vuk::Format::eR32G32B32Sfloat })`.
Finally, you can describe holes in your interleaving by using `vuk::Ignore(byte_size)` in the format list for `vuk::Packed`.
If your attribute scheme cannot be described like this, you can also use :cpp:func:`vuk::CommandBuffer::bind_vertex_buffer()` with a manually built `span<VertexInputAttributeDescription>` and computed stride.
Command recording
-----------------
Draws and dispatches can be recorded by calling the appropriate function. Any state changes made will be recorded into the underlying Vulkan command buffer, along with the draw or dispatch.
Error handling
--------------
The CommandBuffer implements "monadic" error handling, because operations that allocate resources might fail. In this case the CommandBuffer is moved into the error state and subsequent calls do not modify the underlying state.
.. doxygenclass:: vuk::CommandBuffer
:members:<file_sep>#pragma once
#include "vuk/Buffer.hpp"
#include "vuk/Image.hpp"
#include "vuk/vuk_fwd.hpp"
#include <compare>
namespace vuk {
struct ImageAttachment {
Image image = {};
ImageView image_view = {};
ImageCreateFlags image_flags = {};
ImageType image_type = ImageType::e2D;
ImageTiling tiling = ImageTiling::eOptimal;
ImageUsageFlags usage = ImageUsageFlagBits::eInfer;
Dimension3D extent = Dimension3D::framebuffer();
Format format = Format::eUndefined;
Samples sample_count = Samples::eInfer;
bool allow_srgb_unorm_mutable = false;
ImageViewCreateFlags image_view_flags = {};
ImageViewType view_type = ImageViewType::eInfer;
ComponentMapping components;
uint32_t base_level = VK_REMAINING_MIP_LEVELS;
uint32_t level_count = VK_REMAINING_MIP_LEVELS;
uint32_t base_layer = VK_REMAINING_ARRAY_LAYERS;
uint32_t layer_count = VK_REMAINING_ARRAY_LAYERS;
bool operator==(const ImageAttachment&) const = default;
static ImageAttachment from_texture(const vuk::Texture& t) {
return ImageAttachment{ .image = t.image.get(),
.image_view = t.view.get(),
.extent = { Sizing::eAbsolute, { t.extent.width, t.extent.height, t.extent.depth } },
.format = t.format,
.sample_count = { t.sample_count },
.base_level = 0,
.level_count = t.level_count,
.base_layer = 0,
.layer_count = t.layer_count };
}
constexpr bool has_concrete_image() const noexcept {
return image != Image{};
}
constexpr bool has_concrete_image_view() const noexcept {
return image_view != ImageView{};
}
constexpr bool may_require_image_view() const noexcept {
return usage == ImageUsageFlagBits::eInfer ||
(usage & (ImageUsageFlagBits::eColorAttachment | ImageUsageFlagBits::eDepthStencilAttachment | ImageUsageFlagBits::eSampled |
ImageUsageFlagBits::eStorage | ImageUsageFlagBits::eInputAttachment)) != ImageUsageFlags{};
}
constexpr bool is_fully_known() const noexcept {
return image_type != ImageType::eInfer && usage != ImageUsageFlagBits::eInfer && extent.sizing != Sizing::eRelative && extent.extent.width != 0 &&
extent.extent.height != 0 && extent.extent.depth != 0 && format != Format::eUndefined && sample_count != Samples::eInfer &&
base_level != VK_REMAINING_MIP_LEVELS && level_count != VK_REMAINING_MIP_LEVELS && base_layer != VK_REMAINING_ARRAY_LAYERS &&
layer_count != VK_REMAINING_ARRAY_LAYERS && (!may_require_image_view() || view_type != ImageViewType::eInfer);
}
};
struct QueueResourceUse {
PipelineStageFlags stages;
AccessFlags access;
ImageLayout layout; // ignored for buffers
DomainFlags domain = DomainFlagBits::eAny;
};
union Subrange {
struct Image {
uint32_t base_layer = 0;
uint32_t base_level = 0;
uint32_t layer_count = VK_REMAINING_ARRAY_LAYERS;
uint32_t level_count = VK_REMAINING_MIP_LEVELS;
constexpr auto operator<=>(const Image& o) const noexcept = default;
} image = {};
struct Buffer {
uint64_t offset = 0;
uint64_t size = VK_WHOLE_SIZE;
constexpr bool operator==(const Buffer& o) const noexcept {
return offset == o.offset && size == o.size;
}
} buffer;
};
} // namespace vuk<file_sep>#include "Cache.hpp"
#include "RenderGraphImpl.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/CommandBuffer.hpp"
#include "vuk/Context.hpp"
#include "vuk/Future.hpp"
#include "vuk/Hash.hpp" // for create
#include "vuk/RenderGraph.hpp"
#include "vuk/Util.hpp"
#include <sstream>
#include <unordered_set>
namespace vuk {
ExecutableRenderGraph::ExecutableRenderGraph(Compiler& rg) : impl(rg.impl) {}
ExecutableRenderGraph::ExecutableRenderGraph(ExecutableRenderGraph&& o) noexcept : impl(std::exchange(o.impl, nullptr)) {}
ExecutableRenderGraph& ExecutableRenderGraph::operator=(ExecutableRenderGraph&& o) noexcept {
impl = std::exchange(o.impl, nullptr);
return *this;
}
ExecutableRenderGraph::~ExecutableRenderGraph() {}
void begin_render_pass(Context& ctx, vuk::RenderPassInfo& rpass, VkCommandBuffer& cbuf, bool use_secondary_command_buffers) {
VkRenderPassBeginInfo rbi{ .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
rbi.renderPass = rpass.handle;
rbi.framebuffer = rpass.framebuffer;
rbi.renderArea = VkRect2D{ vuk::Offset2D{}, vuk::Extent2D{ rpass.fbci.width, rpass.fbci.height } };
rbi.clearValueCount = 0;
ctx.vkCmdBeginRenderPass(cbuf, &rbi, use_secondary_command_buffers ? VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS : VK_SUBPASS_CONTENTS_INLINE);
}
[[nodiscard]] bool resolve_image_barrier(const Context& ctx, VkImageMemoryBarrier2KHR& dep, const AttachmentInfo& bound, vuk::DomainFlagBits current_domain) {
dep.image = bound.attachment.image.image;
// turn base_{layer, level} into absolute values wrt the image
dep.subresourceRange.baseArrayLayer += bound.attachment.base_layer;
dep.subresourceRange.baseMipLevel += bound.attachment.base_level;
// clamp arrays and levels to actual accessible range in image, return false if the barrier would refer to no levels or layers
assert(bound.attachment.layer_count != VK_REMAINING_ARRAY_LAYERS);
if (dep.subresourceRange.layerCount != VK_REMAINING_ARRAY_LAYERS) {
if (dep.subresourceRange.baseArrayLayer + dep.subresourceRange.layerCount > bound.attachment.base_layer + bound.attachment.layer_count) {
int count = static_cast<int32_t>(bound.attachment.layer_count) - (dep.subresourceRange.baseArrayLayer - bound.attachment.base_layer);
if (count < 1) {
return false;
}
dep.subresourceRange.layerCount = static_cast<uint32_t>(count);
}
} else {
if (dep.subresourceRange.baseArrayLayer > bound.attachment.base_layer + bound.attachment.layer_count) {
return false;
}
}
assert(bound.attachment.level_count != VK_REMAINING_MIP_LEVELS);
if (dep.subresourceRange.levelCount != VK_REMAINING_MIP_LEVELS) {
if (dep.subresourceRange.baseMipLevel + dep.subresourceRange.levelCount > bound.attachment.base_level + bound.attachment.level_count) {
int count = static_cast<int32_t>(bound.attachment.level_count) - (dep.subresourceRange.baseMipLevel - bound.attachment.base_level);
if (count < 1)
return false;
dep.subresourceRange.levelCount = static_cast<uint32_t>(count);
}
} else {
if (dep.subresourceRange.baseMipLevel > bound.attachment.base_level + bound.attachment.level_count) {
return false;
}
}
if (dep.srcQueueFamilyIndex != VK_QUEUE_FAMILY_IGNORED) {
assert(dep.dstQueueFamilyIndex != VK_QUEUE_FAMILY_IGNORED);
bool transition = dep.dstQueueFamilyIndex != dep.srcQueueFamilyIndex;
auto src_domain = static_cast<vuk::DomainFlagBits>(dep.srcQueueFamilyIndex);
auto dst_domain = static_cast<vuk::DomainFlagBits>(dep.dstQueueFamilyIndex);
dep.srcQueueFamilyIndex = ctx.domain_to_queue_family_index(static_cast<vuk::DomainFlags>(dep.srcQueueFamilyIndex));
dep.dstQueueFamilyIndex = ctx.domain_to_queue_family_index(static_cast<vuk::DomainFlags>(dep.dstQueueFamilyIndex));
if (dep.srcQueueFamilyIndex == dep.dstQueueFamilyIndex && transition) {
if (dst_domain != current_domain) {
return false; // discard release barriers if they map to the same queue
}
}
}
return true;
}
void ExecutableRenderGraph::fill_render_pass_info(vuk::RenderPassInfo& rpass, const size_t& i, vuk::CommandBuffer& cobuf) {
if (rpass.handle == VK_NULL_HANDLE) {
cobuf.ongoing_render_pass = {};
return;
}
vuk::CommandBuffer::RenderPassInfo rpi;
rpi.render_pass = rpass.handle;
rpi.subpass = (uint32_t)i;
rpi.extent = vuk::Extent2D{ rpass.fbci.width, rpass.fbci.height };
auto& spdesc = rpass.rpci.subpass_descriptions[i];
rpi.color_attachments = std::span<const VkAttachmentReference>(spdesc.pColorAttachments, spdesc.colorAttachmentCount);
rpi.samples = rpass.fbci.sample_count.count;
rpi.depth_stencil_attachment = spdesc.pDepthStencilAttachment;
auto attachments = rpass.attachments.to_span(impl->rp_infos);
for (uint32_t i = 0; i < spdesc.colorAttachmentCount; i++) {
rpi.color_attachment_names[i] = attachments[spdesc.pColorAttachments[i].attachment].attachment_info->name;
}
cobuf.color_blend_attachments.resize(spdesc.colorAttachmentCount);
cobuf.ongoing_render_pass = rpi;
}
void RGCImpl::emit_barriers(Context& ctx,
VkCommandBuffer cbuf,
vuk::DomainFlagBits domain,
RelSpan<VkMemoryBarrier2KHR> mem_bars,
RelSpan<VkImageMemoryBarrier2KHR> im_bars) {
// resolve and compact image barriers in place
auto im_span = im_bars.to_span(image_barriers);
uint32_t imbar_dst_index = 0;
for (auto src_index = 0; src_index < im_bars.size(); src_index++) {
auto dep = im_span[src_index];
int32_t def_pass_idx;
std::memcpy(&def_pass_idx, &dep.pNext, sizeof(def_pass_idx));
dep.pNext = 0;
auto& bound = get_bound_attachment(def_pass_idx);
if (bound.parent_attachment < 0) {
if (!resolve_image_barrier(ctx, dep, get_bound_attachment(bound.parent_attachment), domain)) {
continue;
}
} else {
if (!resolve_image_barrier(ctx, dep, bound, domain)) {
continue;
}
}
im_span[imbar_dst_index++] = dep;
}
auto mem_span = mem_bars.to_span(mem_barriers);
VkDependencyInfoKHR dependency_info{ .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO_KHR,
.memoryBarrierCount = (uint32_t)mem_span.size(),
.pMemoryBarriers = mem_span.data(),
.imageMemoryBarrierCount = imbar_dst_index,
.pImageMemoryBarriers = im_span.data() };
if (mem_bars.size() > 0 || imbar_dst_index > 0) {
ctx.vkCmdPipelineBarrier2KHR(cbuf, &dependency_info);
}
}
Result<SubmitInfo> ExecutableRenderGraph::record_single_submit(Allocator& alloc, std::span<PassInfo*> passes, vuk::DomainFlagBits domain) {
assert(passes.size() > 0);
auto& ctx = alloc.get_context();
SubmitInfo si;
Unique<CommandPool> cpool(alloc);
VkCommandPoolCreateInfo cpci{ VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
cpci.flags = VkCommandPoolCreateFlagBits::VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
cpci.queueFamilyIndex = ctx.domain_to_queue_family_index(domain); // currently queue family idx = queue idx
VUK_DO_OR_RETURN(alloc.allocate_command_pools(std::span{ &*cpool, 1 }, std::span{ &cpci, 1 }));
robin_hood::unordered_set<SwapchainRef> used_swapchains;
Unique<CommandBufferAllocation> hl_cbuf(alloc);
CommandBufferAllocationCreateInfo ci{ .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .command_pool = *cpool };
VUK_DO_OR_RETURN(alloc.allocate_command_buffers(std::span{ &*hl_cbuf, 1 }, std::span{ &ci, 1 }));
si.command_buffers.emplace_back(*hl_cbuf);
VkCommandBuffer cbuf = hl_cbuf->command_buffer;
VkCommandBufferBeginInfo cbi{ .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT };
ctx.vkBeginCommandBuffer(cbuf, &cbi);
uint64_t command_buffer_index = passes[0]->command_buffer_index;
int32_t render_pass_index = -1;
for (size_t i = 0; i < passes.size(); i++) {
auto& pass = passes[i];
for (auto& ref : pass->referenced_swapchains.to_span(impl->swapchain_references)) {
used_swapchains.emplace(impl->get_bound_attachment(ref).swapchain);
}
if (pass->command_buffer_index != command_buffer_index) { // end old cb and start new one
if (auto result = ctx.vkEndCommandBuffer(cbuf); result != VK_SUCCESS) {
return { expected_error, VkException{ result } };
}
VUK_DO_OR_RETURN(alloc.allocate_command_buffers(std::span{ &*hl_cbuf, 1 }, std::span{ &ci, 1 }));
si.command_buffers.emplace_back(*hl_cbuf);
cbuf = hl_cbuf->command_buffer;
VkCommandBufferBeginInfo cbi{ .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT };
ctx.vkBeginCommandBuffer(cbuf, &cbi);
}
// if we had a render pass running, but now it changes
if (pass->render_pass_index != render_pass_index && render_pass_index != -1) {
ctx.vkCmdEndRenderPass(cbuf);
}
if (i > 1) {
// insert post-barriers
impl->emit_barriers(ctx, cbuf, domain, passes[i - 1]->post_memory_barriers, passes[i - 1]->post_image_barriers);
}
// insert pre-barriers
impl->emit_barriers(ctx, cbuf, domain, pass->pre_memory_barriers, pass->pre_image_barriers);
// if render pass is changing and new pass uses one
if (pass->render_pass_index != render_pass_index && pass->render_pass_index != -1) {
begin_render_pass(ctx, impl->rpis[pass->render_pass_index], cbuf, false);
}
render_pass_index = pass->render_pass_index;
for (auto& w : pass->relative_waits.to_span(impl->waits)) {
si.relative_waits.emplace_back(w);
}
for (auto& w : pass->absolute_waits.to_span(impl->absolute_waits)) {
si.absolute_waits.emplace_back(w);
}
CommandBuffer cobuf(*this, ctx, alloc, cbuf);
if (render_pass_index >= 0) {
fill_render_pass_info(impl->rpis[pass->render_pass_index], 0, cobuf);
} else {
cobuf.ongoing_render_pass = {};
}
// propagate signals onto SI
auto pass_fut_signals = pass->future_signals.to_span(impl->future_signals);
si.future_signals.insert(si.future_signals.end(), pass_fut_signals.begin(), pass_fut_signals.end());
if (!pass->qualified_name.is_invalid()) {
ctx.begin_region(cobuf.command_buffer, pass->qualified_name.name);
}
if (pass->pass->execute) {
cobuf.current_pass = pass;
pass->pass->execute(cobuf);
}
if (!pass->qualified_name.is_invalid()) {
ctx.end_region(cobuf.command_buffer);
}
if (auto res = cobuf.result(); !res) {
return res;
}
}
if (render_pass_index != -1) {
ctx.vkCmdEndRenderPass(cbuf);
}
// insert post-barriers
impl->emit_barriers(ctx, cbuf, domain, passes.back()->post_memory_barriers, passes.back()->post_image_barriers);
if (auto result = ctx.vkEndCommandBuffer(cbuf); result != VK_SUCCESS) {
return { expected_error, VkException{ result } };
}
si.used_swapchains.insert(si.used_swapchains.end(), used_swapchains.begin(), used_swapchains.end());
return { expected_value, std::move(si) };
}
Result<SubmitBundle> ExecutableRenderGraph::execute(Allocator& alloc, std::vector<std::pair<SwapchainRef, size_t>> swp_with_index) {
Context& ctx = alloc.get_context();
// bind swapchain attachment images & ivs
for (auto& bound : impl->bound_attachments) {
if (bound.type == AttachmentInfo::Type::eSwapchain && bound.parent_attachment == 0) {
auto it = std::find_if(swp_with_index.begin(), swp_with_index.end(), [boundb = &bound](auto& t) { return t.first == boundb->swapchain; });
bound.attachment.image_view = it->first->image_views[it->second];
bound.attachment.image = it->first->images[it->second];
bound.attachment.extent = Dimension3D::absolute(it->first->extent);
bound.attachment.sample_count = vuk::Samples::e1;
}
}
// pre-inference: which IAs are in which FBs?
for (auto& rp : impl->rpis) {
for (auto& rp_att : rp.attachments.to_span(impl->rp_infos)) {
auto& att = *rp_att.attachment_info;
att.rp_uses.append(impl->attachment_rp_references, &rp);
auto& ia = att.attachment;
ia.image_type = ia.image_type == ImageType::eInfer ? vuk::ImageType::e2D : ia.image_type;
ia.base_layer = ia.base_layer == VK_REMAINING_ARRAY_LAYERS ? 0 : ia.base_layer;
ia.layer_count =
ia.layer_count == VK_REMAINING_ARRAY_LAYERS ? 1 : ia.layer_count; // TODO: this prevents inference later on, so this means we are doing it too early
ia.base_level = ia.base_level == VK_REMAINING_MIP_LEVELS ? 0 : ia.base_level;
if (ia.view_type == ImageViewType::eInfer) {
if (ia.layer_count > 1) {
ia.view_type = ImageViewType::e2DArray;
} else {
ia.view_type = ImageViewType::e2D;
}
}
ia.level_count = 1; // can only render to a single mip level
ia.extent.extent.depth = 1;
// we do an initial IA -> FB, because we won't process complete IAs later, but we need their info
if (ia.sample_count != Samples::eInfer && !rp_att.is_resolve_dst) {
rp.fbci.sample_count = ia.sample_count;
}
if (ia.extent.sizing == Sizing::eAbsolute && ia.extent.extent.width > 0 && ia.extent.extent.height > 0) {
rp.fbci.width = ia.extent.extent.width;
rp.fbci.height = ia.extent.extent.height;
}
// resolve images are always sample count 1
if (rp_att.is_resolve_dst) {
att.attachment.sample_count = Samples::e1;
}
}
}
decltype(impl->ia_inference_rules) ia_resolved_rules;
for (auto& [n, rules] : impl->ia_inference_rules) {
ia_resolved_rules.emplace(impl->resolve_name(n), std::move(rules));
}
decltype(impl->buf_inference_rules) buf_resolved_rules;
for (auto& [n, rules] : impl->buf_inference_rules) {
buf_resolved_rules.emplace(impl->resolve_name(n), std::move(rules));
}
std::vector<std::pair<AttachmentInfo*, IAInferences*>> attis_to_infer;
for (auto& bound : impl->bound_attachments) {
if (bound.type == AttachmentInfo::Type::eInternal && bound.parent_attachment == 0) {
// compute usage if it is to be inferred
if (bound.attachment.usage == ImageUsageFlagBits::eInfer) {
bound.attachment.usage = {};
for (auto& chain : bound.use_chains.to_span(impl->attachment_use_chain_references)) {
bound.attachment.usage |= impl->compute_usage(chain);
}
}
// if there is no image, then we will infer the base mip and layer to be 0
if (!bound.attachment.image) {
bound.attachment.base_layer = 0;
bound.attachment.base_level = 0;
}
if (bound.attachment.image_view == ImageView{}) {
if (bound.attachment.view_type == ImageViewType::eInfer && bound.attachment.layer_count != VK_REMAINING_ARRAY_LAYERS) {
if (bound.attachment.image_type == ImageType::e1D) {
if (bound.attachment.layer_count == 1) {
bound.attachment.view_type = ImageViewType::e1D;
} else {
bound.attachment.view_type = ImageViewType::e1DArray;
}
} else if (bound.attachment.image_type == ImageType::e2D) {
if (bound.attachment.layer_count == 1) {
bound.attachment.view_type = ImageViewType::e2D;
} else {
bound.attachment.view_type = ImageViewType::e2DArray;
}
} else if (bound.attachment.image_type == ImageType::e3D) {
if (bound.attachment.layer_count == 1) {
bound.attachment.view_type = ImageViewType::e3D;
} else {
bound.attachment.view_type = ImageViewType::e2DArray;
}
}
}
}
IAInferences* rules_ptr = nullptr;
auto rules_it = ia_resolved_rules.find(bound.name);
if (rules_it != ia_resolved_rules.end()) {
rules_ptr = &rules_it->second;
}
attis_to_infer.emplace_back(&bound, rules_ptr);
}
}
std::vector<std::pair<BufferInfo*, BufferInferences*>> bufis_to_infer;
for (auto& bound : impl->bound_buffers) {
if (bound.buffer.size != ~(0u))
continue;
BufferInferences* rules_ptr = nullptr;
auto rules_it = buf_resolved_rules.find(bound.name);
if (rules_it != buf_resolved_rules.end()) {
rules_ptr = &rules_it->second;
}
bufis_to_infer.emplace_back(&bound, rules_ptr);
}
InferenceContext inf_ctx{ this };
bool infer_progress = true;
std::stringstream msg;
// we provide an upper bound of 100 inference iterations to catch infinite loops that don't converge to a fixpoint
for (size_t i = 0; i < 100 && !attis_to_infer.empty() && infer_progress; i++) {
infer_progress = false;
for (auto ia_it = attis_to_infer.begin(); ia_it != attis_to_infer.end();) {
auto& atti = *ia_it->first;
auto& ia = atti.attachment;
auto prev = ia;
// infer FB -> IA
if (ia.sample_count == Samples::eInfer || (ia.extent.extent.width == 0 && ia.extent.extent.height == 0) ||
ia.extent.sizing == Sizing::eRelative) { // this IA can potentially take inference from an FB
for (auto* rpi : atti.rp_uses.to_span(impl->attachment_rp_references)) {
auto& fbci = rpi->fbci;
Samples fb_samples = fbci.sample_count;
bool samples_known = fb_samples != Samples::eInfer;
// an extent is known if it is not 0
// 0 sized framebuffers are illegal
Extent3D fb_extent = { fbci.width, fbci.height };
bool extent_known = !(fb_extent.width == 0 || fb_extent.height == 0);
if (samples_known && ia.sample_count == Samples::eInfer) {
ia.sample_count = fb_samples;
}
if (extent_known) {
if (ia.extent.extent.width == 0 && ia.extent.extent.height == 0) {
ia.extent.extent.width = fb_extent.width;
ia.extent.extent.height = fb_extent.height;
} else if (ia.extent.sizing == Sizing::eRelative) {
ia.extent.extent.width = static_cast<uint32_t>(ia.extent._relative.width * fb_extent.width);
ia.extent.extent.height = static_cast<uint32_t>(ia.extent._relative.height * fb_extent.height);
ia.extent.extent.depth = static_cast<uint32_t>(ia.extent._relative.depth * fb_extent.depth);
}
ia.extent.sizing = Sizing::eAbsolute;
}
}
}
// infer custom rule -> IA
if (ia_it->second) {
inf_ctx.prefix = ia_it->second->prefix;
for (auto& rule : ia_it->second->rules) {
rule(inf_ctx, ia);
}
}
if (prev != ia) { // progress made
// check for broken constraints
if (prev.base_layer != ia.base_layer && prev.base_layer != VK_REMAINING_ARRAY_LAYERS) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " base layer was previously known to be " << prev.base_layer << ", but now set to " << ia.base_layer;
return { expected_error, RenderGraphException{ msg.str() } };
}
if (prev.layer_count != ia.layer_count && prev.layer_count != VK_REMAINING_ARRAY_LAYERS) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " layer count was previously known to be " << prev.layer_count << ", but now set to " << ia.layer_count;
return { expected_error, RenderGraphException{ msg.str() } };
}
if (prev.base_level != ia.base_level && prev.base_level != VK_REMAINING_MIP_LEVELS) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " base level was previously known to be " << prev.base_level << ", but now set to " << ia.base_level;
return { expected_error, RenderGraphException{ msg.str() } };
}
if (prev.level_count != ia.level_count && prev.level_count != VK_REMAINING_MIP_LEVELS) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " level count was previously known to be " << prev.level_count << ", but now set to " << ia.level_count;
return { expected_error, RenderGraphException{ msg.str() } };
}
if (prev.format != ia.format && prev.format != Format::eUndefined) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " format was previously known to be " << format_to_sv(prev.format) << ", but now set to " << format_to_sv(ia.format);
return { expected_error, RenderGraphException{ msg.str() } };
}
if (prev.sample_count != ia.sample_count && prev.sample_count != SampleCountFlagBits::eInfer) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " sample count was previously known to be " << static_cast<uint32_t>(prev.sample_count.count) << ", but now set to "
<< static_cast<uint32_t>(ia.sample_count.count);
return { expected_error, RenderGraphException{ msg.str() } };
}
if (prev.extent.extent.width != ia.extent.extent.width && prev.extent.extent.width != 0) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " extent.width was previously known to be " << prev.extent.extent.width << ", but now set to " << ia.extent.extent.width;
return { expected_error, RenderGraphException{ msg.str() } };
}
if (prev.extent.extent.height != ia.extent.extent.height && prev.extent.extent.height != 0) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " extent.height was previously known to be " << prev.extent.extent.height << ", but now set to " << ia.extent.extent.height;
return { expected_error, RenderGraphException{ msg.str() } };
}
if (prev.extent.extent.depth != ia.extent.extent.depth && prev.extent.extent.depth != 0) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " extent.depth was previously known to be " << prev.extent.extent.depth << ", but now set to " << ia.extent.extent.depth;
return { expected_error, RenderGraphException{ msg.str() } };
}
if (ia.may_require_image_view() && prev.view_type != ia.view_type && prev.view_type != ImageViewType::eInfer) {
msg << "Rule broken for attachment[" << atti.name.name.c_str() << "] :\n ";
msg << " view type was previously known to be " << image_view_type_to_sv(prev.view_type) << ", but now set to "
<< image_view_type_to_sv(ia.view_type);
return { expected_error, RenderGraphException{ msg.str() } };
}
infer_progress = true;
// infer IA -> FB
if (ia.sample_count == Samples::eInfer && (ia.extent.extent.width == 0 && ia.extent.extent.height == 0)) { // this IA is not helpful for FB inference
continue;
}
for (auto* rpi : atti.rp_uses.to_span(impl->attachment_rp_references)) {
auto& fbci = rpi->fbci;
Samples fb_samples = fbci.sample_count;
bool samples_known = fb_samples != Samples::eInfer;
// an extent is known if it is not 0
// 0 sized framebuffers are illegal
Extent2D fb_extent = Extent2D{ fbci.width, fbci.height };
bool extent_known = !(fb_extent.width == 0 || fb_extent.height == 0);
if (samples_known && extent_known) {
continue;
}
if (!samples_known && ia.sample_count != Samples::eInfer) {
auto attachments = rpi->attachments.to_span(impl->rp_infos);
auto it = std::find_if(attachments.begin(), attachments.end(), [attip = &atti](auto& rp_att) { return rp_att.attachment_info == attip; });
assert(it != attachments.end());
if (!it->is_resolve_dst) {
fbci.sample_count = ia.sample_count;
}
}
if (ia.extent.sizing == vuk::Sizing::eAbsolute && ia.extent.extent.width > 0 && ia.extent.extent.height > 0) {
fbci.width = ia.extent.extent.width;
fbci.height = ia.extent.extent.height;
}
}
}
if (ia.is_fully_known()) {
ia_it = attis_to_infer.erase(ia_it);
} else {
++ia_it;
}
}
}
for (auto& [atti, iaref] : attis_to_infer) {
msg << "Could not infer attachment [" << atti->name.name.c_str() << "]:\n";
auto& ia = atti->attachment;
if (ia.sample_count == Samples::eInfer) {
msg << "- sample count unknown\n";
}
if (ia.extent.sizing == Sizing::eRelative) {
msg << "- relative sizing could not be resolved\n";
}
if (ia.extent.extent.width == 0) {
msg << "- extent.width unknown\n";
}
if (ia.extent.extent.height == 0) {
msg << "- extent.height unknown\n";
}
if (ia.extent.extent.depth == 0) {
msg << "- extent.depth unknown\n";
}
if (ia.format == Format::eUndefined) {
msg << "- format unknown\n";
}
if (ia.may_require_image_view() && ia.view_type == ImageViewType::eInfer) {
msg << "- view type unknown\n";
}
if (ia.base_layer == VK_REMAINING_ARRAY_LAYERS) {
msg << "- base layer unknown\n";
}
if (ia.layer_count == VK_REMAINING_ARRAY_LAYERS) {
msg << "- layer count unknown\n";
}
if (ia.base_level == VK_REMAINING_MIP_LEVELS) {
msg << "- base level unknown\n";
}
if (ia.level_count == VK_REMAINING_MIP_LEVELS) {
msg << "- level count unknown\n";
}
msg << "\n";
}
if (attis_to_infer.size() > 0) {
return { expected_error, RenderGraphException{ msg.str() } };
}
infer_progress = true;
// we provide an upper bound of 100 inference iterations to catch infinite loops that don't converge to a fixpoint
for (size_t i = 0; i < 100 && !bufis_to_infer.empty() && infer_progress; i++) {
infer_progress = false;
for (auto bufi_it = bufis_to_infer.begin(); bufi_it != bufis_to_infer.end();) {
auto& bufi = *bufi_it->first;
auto& buff = bufi.buffer;
auto prev = buff;
// infer custom rule -> IA
if (bufi_it->second) {
inf_ctx.prefix = bufi_it->second->prefix;
for (auto& rule : bufi_it->second->rules) {
rule(inf_ctx, buff);
}
}
if (prev != buff) { // progress made
// check for broken constraints
if (prev.size != buff.size && prev.size != ~(0u)) {
msg << "Rule broken for buffer[" << bufi.name.name.c_str() << "] :\n ";
msg << " size was previously known to be " << prev.size << ", but now set to " << buff.size;
return { expected_error, RenderGraphException{ msg.str() } };
}
infer_progress = true;
}
if (buff.size != ~(0u)) {
bufi_it = bufis_to_infer.erase(bufi_it);
} else {
++bufi_it;
}
}
}
for (auto& [buff, bufinfs] : bufis_to_infer) {
msg << "Could not infer buffer [" << buff->name.name.c_str() << "]:\n";
if (buff->buffer.size == ~(0u)) {
msg << "- size unknown\n";
}
msg << "\n";
}
if (bufis_to_infer.size() > 0) {
return { expected_error, RenderGraphException{ msg.str() } };
}
// acquire the render passes
for (auto& rp : impl->rpis) {
if (rp.attachments.size() == 0) {
continue;
}
for (auto& attrpinfo : rp.attachments.to_span(impl->rp_infos)) {
attrpinfo.description.format = (VkFormat)attrpinfo.attachment_info->attachment.format;
attrpinfo.description.samples = (VkSampleCountFlagBits)attrpinfo.attachment_info->attachment.sample_count.count;
rp.rpci.attachments.push_back(attrpinfo.description);
}
rp.rpci.attachmentCount = (uint32_t)rp.rpci.attachments.size();
rp.rpci.pAttachments = rp.rpci.attachments.data();
auto result = alloc.allocate_render_passes(std::span{ &rp.handle, 1 }, std::span{ &rp.rpci, 1 });
// drop render pass immediately
if (result) {
alloc.deallocate(std::span{ &rp.handle, 1 });
}
}
// create buffers
for (auto& bound : impl->bound_buffers) {
if (bound.buffer.buffer == VK_NULL_HANDLE) {
BufferCreateInfo bci{ .mem_usage = bound.buffer.memory_usage, .size = bound.buffer.size, .alignment = 1 }; // TODO: alignment?
auto allocator = bound.allocator ? *bound.allocator : alloc;
auto buf = allocate_buffer(allocator, bci);
if (!buf) {
return buf;
}
bound.buffer = **buf;
}
}
// create non-attachment images
for (auto& bound : impl->bound_attachments) {
if (!bound.attachment.image && bound.parent_attachment == 0) {
auto allocator = bound.allocator ? *bound.allocator : alloc;
assert(bound.attachment.usage != ImageUsageFlags{});
auto img = allocate_image(allocator, bound.attachment);
if (!img) {
return img;
}
bound.attachment.image = **img;
ctx.set_name(bound.attachment.image.image, bound.name.name);
}
}
// create framebuffers, create & bind attachments
for (auto& rp : impl->rpis) {
if (rp.attachments.size() == 0)
continue;
auto& ivs = rp.fbci.attachments;
std::vector<VkImageView> vkivs;
Extent2D fb_extent = Extent2D{ rp.fbci.width, rp.fbci.height };
// create internal attachments; bind attachments to fb
std::optional<uint32_t> fb_layer_count;
for (auto& attrpinfo : rp.attachments.to_span(impl->rp_infos)) {
auto& bound = *attrpinfo.attachment_info;
uint32_t base_layer = bound.attachment.base_layer + bound.image_subrange.base_layer;
uint32_t layer_count = bound.image_subrange.layer_count == VK_REMAINING_ARRAY_LAYERS ? bound.attachment.layer_count : bound.image_subrange.layer_count;
assert(base_layer + layer_count <= bound.attachment.base_layer + bound.attachment.layer_count);
fb_layer_count = layer_count;
auto specific_attachment = bound.attachment;
if (bound.parent_attachment < 0) {
specific_attachment = impl->get_bound_attachment(bound.parent_attachment).attachment;
specific_attachment.image_view = {};
}
if (specific_attachment.image_view == ImageView{}) {
specific_attachment.base_layer = base_layer;
if (specific_attachment.view_type == ImageViewType::eCube) {
if (layer_count > 1) {
specific_attachment.view_type = ImageViewType::e2DArray;
} else {
specific_attachment.view_type = ImageViewType::e2D;
}
}
specific_attachment.layer_count = layer_count;
assert(specific_attachment.level_count == 1);
auto allocator = bound.allocator ? *bound.allocator : alloc;
auto iv = allocate_image_view(allocator, specific_attachment);
if (!iv) {
return iv;
}
specific_attachment.image_view = **iv;
auto name = std::string("ImageView: RenderTarget ") + std::string(bound.name.name.to_sv());
ctx.set_name(specific_attachment.image_view.payload, Name(name));
}
ivs.push_back(specific_attachment.image_view);
vkivs.push_back(specific_attachment.image_view.payload);
}
rp.fbci.renderPass = rp.handle;
rp.fbci.pAttachments = &vkivs[0];
rp.fbci.width = fb_extent.width;
rp.fbci.height = fb_extent.height;
assert(fb_extent.width > 0);
assert(fb_extent.height > 0);
rp.fbci.attachmentCount = (uint32_t)vkivs.size();
rp.fbci.layers = *fb_layer_count;
Unique<VkFramebuffer> fb(alloc);
VUK_DO_OR_RETURN(alloc.allocate_framebuffers(std::span{ &*fb, 1 }, std::span{ &rp.fbci, 1 }));
rp.framebuffer = *fb; // queue framebuffer for destruction
}
for (auto& attachment_info : impl->bound_attachments) {
if (attachment_info.attached_future && attachment_info.parent_attachment == 0) {
ImageAttachment att = attachment_info.attachment;
attachment_info.attached_future->result = att;
}
}
for (auto& buffer_info : impl->bound_buffers) {
if (buffer_info.attached_future) {
Buffer buf = buffer_info.buffer;
buffer_info.attached_future->result = buf;
}
}
SubmitBundle sbundle;
auto record_batch = [&alloc, this](std::span<PassInfo*> passes, DomainFlagBits domain) -> Result<SubmitBatch> {
SubmitBatch sbatch{ .domain = domain };
auto partition_it = passes.begin();
while (partition_it != passes.end()) {
auto batch_index = (*partition_it)->batch_index;
auto new_partition_it = std::partition_point(partition_it, passes.end(), [batch_index](PassInfo* rpi) { return rpi->batch_index == batch_index; });
auto partition_span = std::span(partition_it, new_partition_it);
auto si = record_single_submit(alloc, partition_span, domain);
if (!si) {
return si;
}
sbatch.submits.emplace_back(*si);
partition_it = new_partition_it;
}
return { expected_value, sbatch };
};
// record cbufs
// assume that rpis are partitioned wrt batch_index
if (impl->graphics_passes.size() > 0) {
auto batch = record_batch(impl->graphics_passes, DomainFlagBits::eGraphicsQueue);
if (!batch) {
return batch;
}
sbundle.batches.emplace_back(std::move(*batch));
}
if (impl->compute_passes.size() > 0) {
auto batch = record_batch(impl->compute_passes, DomainFlagBits::eComputeQueue);
if (!batch) {
return batch;
}
sbundle.batches.emplace_back(std::move(*batch));
}
if (impl->transfer_passes.size() > 0) {
auto batch = record_batch(impl->transfer_passes, DomainFlagBits::eTransferQueue);
if (!batch) {
return batch;
}
sbundle.batches.emplace_back(std::move(*batch));
}
return { expected_value, std::move(sbundle) };
}
Result<BufferInfo, RenderGraphException> ExecutableRenderGraph::get_resource_buffer(const NameReference& name_ref, PassInfo* pass_info) {
for (auto& r : pass_info->resources.to_span(impl->resources)) {
if (r.type == Resource::Type::eBuffer && r.original_name == name_ref.name.name && r.foreign == name_ref.rg) {
auto& att = impl->get_bound_buffer(r.reference);
return { expected_value, att };
}
}
return { expected_error, errors::make_cbuf_references_undeclared_resource(*pass_info, Resource::Type::eImage, name_ref.name.name) };
}
Result<AttachmentInfo, RenderGraphException> ExecutableRenderGraph::get_resource_image(const NameReference& name_ref, PassInfo* pass_info) {
for (auto& r : pass_info->resources.to_span(impl->resources)) {
if (r.type == Resource::Type::eImage && r.original_name == name_ref.name.name && r.foreign == name_ref.rg) {
auto& att = impl->get_bound_attachment(r.reference);
if (att.parent_attachment < 0) {
return { expected_value, impl->get_bound_attachment(att.parent_attachment) };
}
return { expected_value, att };
}
}
return { expected_error, errors::make_cbuf_references_undeclared_resource(*pass_info, Resource::Type::eImage, name_ref.name.name) };
}
Result<bool, RenderGraphException> ExecutableRenderGraph::is_resource_image_in_general_layout(const NameReference& name_ref, PassInfo* pass_info) {
for (auto& r : pass_info->resources.to_span(impl->resources)) {
if (r.type == Resource::Type::eImage && r.original_name == name_ref.name.name && r.foreign == name_ref.rg) {
return { expected_value, r.promoted_to_general };
}
}
return { expected_error, errors::make_cbuf_references_undeclared_resource(*pass_info, Resource::Type::eImage, name_ref.name.name) };
}
QualifiedName ExecutableRenderGraph::resolve_name(Name name, PassInfo* pass_info) const noexcept {
auto qualified_name = QualifiedName{ pass_info->qualified_name.prefix, name };
return impl->resolve_name(qualified_name);
}
const ImageAttachment& InferenceContext::get_image_attachment(Name name) const {
auto fqname = QualifiedName{ prefix, name };
auto resolved_name = erg->impl->resolve_name(fqname);
auto link = &erg->impl->res_to_links.at(resolved_name); // TODO: no error signaling
while (link->def->pass > 0) {
link = link->prev;
}
return erg->impl->get_bound_attachment(link->def->pass).attachment;
}
const Buffer& InferenceContext::get_buffer(Name name) const {
auto fqname = QualifiedName{ prefix, name };
auto resolved_name = erg->impl->resolve_name(fqname);
auto link = &erg->impl->res_to_links.at(resolved_name); // TODO: no error signaling
while (link->def->pass > 0) {
link = link->prev;
}
return erg->impl->get_bound_buffer(link->def->pass).buffer;
}
} // namespace vuk
<file_sep>#include "example_runner.hpp"
/* 01_triangle
* In this example we will draw a bufferless triangle, the "Hello world" of graphics programming
* For this, we will need to define our pipeline, and then submit a draw.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
vuk::Example x{
// The display name of this example
.name = "01_triangle",
// Setup code, ran once in the beginning
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
// Pipelines are created by filling out a vuk::PipelineCreateInfo
// In this case, we only need the shaders, we don't care about the rest of the state
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/triangle.vert").generic_string()), (root / "examples/triangle.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle.frag").generic_string()), (root / "examples/triangle.frag").generic_string());
// The pipeline is stored with a user give name for simplicity
runner.context->create_named_pipeline("triangle", pci);
},
// Code ran every frame
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
// We start building a rendergraph
vuk::RenderGraph rg("01");
// The framework provides us with an image to render to in "target"
// We attach this to the rendergraph named as "01_triangle"
rg.attach_in("01_triangle", std::move(target));
// The rendergraph is composed of passes (vuk::Pass)
// Each pass declares which resources are used
// And it provides a callback which is executed when this pass is being ran
rg.add_pass({ // For this example, only a color image is needed to write to (our framebuffer)
// The name is declared, and the way it will be used in the pass (color attachment - write)
.resources = { "01_triangle"_image >> vuk::eColorWrite >> "01_triangle_final" },
.execute = [](vuk::CommandBuffer& command_buffer) {
// Here commands are recorded into the command buffer for rendering
// The commands frequently mimick the Vulkan counterpart, with additional sugar
// The additional sugar is enabled by having a complete view of the rendering
// Set the viewport to cover the entire framebuffer
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer());
// Set the scissor area to cover the entire framebuffer
command_buffer.set_scissor(0, vuk::Rect2D::framebuffer());
command_buffer
.set_rasterization({}) // Set the default rasterization state
.set_color_blend("01_triangle", {}) // Set the default color blend state
.bind_graphics_pipeline("triangle") // Recall pipeline for "triangle" and bind
.draw(3, 1, 0, 0); // Draw 3 vertices
} });
// The rendergraph is given to a Future, which takes ownership and binds to the result ("01_triangle_final")
// The example framework takes care of the busywork (submission, presenting)
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "01_triangle_final" };
}
};
REGISTER_EXAMPLE(x);
} // namespace<file_sep>#include "vuk/resources/DeviceLinearResource.hpp"
#include "BufferAllocator.hpp"
#include "RenderPass.hpp"
#include "vuk/Context.hpp"
#include "vuk/Descriptor.hpp"
#include "vuk/Query.hpp"
#include <atomic>
#include <mutex>
#include <numeric>
#include <plf_colony.h>
namespace vuk {
struct DeviceLinearResourceImpl {
Context* ctx;
VkDevice device;
std::vector<VkSemaphore> semaphores;
std::vector<Buffer> buffers;
std::vector<VkFence> fences;
std::vector<CommandBufferAllocation> cmdbuffers_to_free;
std::vector<CommandPool> cmdpools_to_free;
std::vector<VkFramebuffer> framebuffers;
std::vector<Image> images;
std::vector<ImageView> image_views;
std::vector<PersistentDescriptorSet> persistent_descriptor_sets;
std::vector<DescriptorSet> descriptor_sets;
VkDescriptorPool* last_ds_pool;
plf::colony<VkDescriptorPool> ds_pools;
std::vector<TimestampQueryPool> ts_query_pools;
uint64_t query_index = 0;
uint64_t current_ts_pool = 0;
std::vector<TimelineSemaphore> tsemas;
std::vector<VkAccelerationStructureKHR> ass;
BufferLinearAllocator linear_cpu_only;
BufferLinearAllocator linear_cpu_gpu;
BufferLinearAllocator linear_gpu_cpu;
BufferLinearAllocator linear_gpu_only;
DeviceLinearResourceImpl(DeviceResource& upstream) :
ctx(&upstream.get_context()),
device(ctx->device),
linear_cpu_only(upstream, vuk::MemoryUsage::eCPUonly, all_buffer_usage_flags),
linear_cpu_gpu(upstream, vuk::MemoryUsage::eCPUtoGPU, all_buffer_usage_flags),
linear_gpu_cpu(upstream, vuk::MemoryUsage::eGPUtoCPU, all_buffer_usage_flags),
linear_gpu_only(upstream, vuk::MemoryUsage::eGPUonly, all_buffer_usage_flags) {}
};
DeviceLinearResource::DeviceLinearResource(DeviceResource& pstream) : DeviceNestedResource(pstream), impl(new DeviceLinearResourceImpl(pstream)) {}
DeviceLinearResource::~DeviceLinearResource() {
if (impl) {
free();
}
}
DeviceLinearResource::DeviceLinearResource(DeviceLinearResource&& o) : DeviceNestedResource(*o.upstream), impl(std::move(o.impl)) {}
DeviceLinearResource& DeviceLinearResource::operator=(DeviceLinearResource&& o) {
upstream = o.upstream;
impl = std::move(o.impl);
return *this;
}
Result<void, AllocateException> DeviceLinearResource::allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_semaphores(dst, loc));
auto& vec = impl->semaphores;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_semaphores(std::span<const VkSemaphore> src) {} // noop
Result<void, AllocateException> DeviceLinearResource::allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_fences(dst, loc));
auto& vec = impl->fences;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_fences(std::span<const VkFence> src) {} // noop
Result<void, AllocateException> DeviceLinearResource::allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_command_buffers(dst, cis, loc));
auto& vec = impl->cmdbuffers_to_free;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_command_buffers(std::span<const CommandBufferAllocation> src) {} // no-op, deallocated with pools
Result<void, AllocateException>
DeviceLinearResource::allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_command_pools(dst, cis, loc));
auto& vec = impl->cmdpools_to_free;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_command_pools(std::span<const CommandPool> dst) {} // no-op
Result<void, AllocateException>
DeviceLinearResource::allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
Result<Buffer, AllocateException> result{ expected_value };
auto alignment = std::lcm(ci.alignment, get_context().min_buffer_alignment);
if (ci.mem_usage == MemoryUsage::eGPUonly) {
result = impl->linear_gpu_only.allocate_buffer(ci.size, alignment, loc);
} else if (ci.mem_usage == MemoryUsage::eCPUonly) {
result = impl->linear_cpu_only.allocate_buffer(ci.size, alignment, loc);
} else if (ci.mem_usage == MemoryUsage::eCPUtoGPU) {
result = impl->linear_cpu_gpu.allocate_buffer(ci.size, alignment, loc);
} else if (ci.mem_usage == MemoryUsage::eGPUtoCPU) {
result = impl->linear_gpu_cpu.allocate_buffer(ci.size, alignment, loc);
}
if (!result) {
deallocate_buffers({ dst.data(), (uint64_t)i });
return result;
}
dst[i] = result.value();
}
return { expected_value };
}
void DeviceLinearResource::deallocate_buffers(std::span<const Buffer> src) {} // no-op, linear
Result<void, AllocateException>
DeviceLinearResource::allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_framebuffers(dst, cis, loc));
auto& vec = impl->framebuffers;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_framebuffers(std::span<const VkFramebuffer> src) {} // noop
Result<void, AllocateException> DeviceLinearResource::allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_images(dst, cis, loc));
auto& vec = impl->images;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_images(std::span<const Image> src) {} // noop
Result<void, AllocateException>
DeviceLinearResource::allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_image_views(dst, cis, loc));
auto& vec = impl->image_views;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_image_views(std::span<const ImageView> src) {} // noop
Result<void, AllocateException> DeviceLinearResource::allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_persistent_descriptor_sets(dst, cis, loc));
auto& vec = impl->persistent_descriptor_sets;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) {} // noop
Result<void, AllocateException>
DeviceLinearResource::allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_descriptor_sets_with_value(dst, cis, loc));
auto& vec = impl->descriptor_sets;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_descriptor_sets(std::span<const DescriptorSet> src) {} // noop
Result<void, AllocateException>
DeviceLinearResource::allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) {
VkDescriptorPoolCreateInfo dpci{ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
dpci.maxSets = 1000;
std::array<VkDescriptorPoolSize, 12> descriptor_counts = {};
size_t count = get_context().vkCmdBuildAccelerationStructuresKHR ? descriptor_counts.size() : descriptor_counts.size() - 1;
for (size_t i = 0; i < count; i++) {
auto& d = descriptor_counts[i];
d.type = i == 11 ? VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR : VkDescriptorType(i);
d.descriptorCount = 1000;
}
dpci.pPoolSizes = descriptor_counts.data();
dpci.poolSizeCount = (uint32_t)count;
if (impl->ds_pools.size() == 0) {
VkDescriptorPool pool;
VUK_DO_OR_RETURN(upstream->allocate_descriptor_pools({ &pool, 1 }, { &dpci, 1 }, loc));
impl->last_ds_pool = &*impl->ds_pools.emplace(pool);
}
// look at last stored pool
VkDescriptorPool* last_pool = impl->last_ds_pool;
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
// attempt to allocate a set
VkDescriptorSetAllocateInfo dsai = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
dsai.descriptorPool = *last_pool;
dsai.descriptorSetCount = 1;
dsai.pSetLayouts = &ci.layout;
dst[i].layout_info = ci;
auto result = impl->ctx->vkAllocateDescriptorSets(impl->device, &dsai, &dst[i].descriptor_set);
// if we fail, we allocate another pool from upstream
if (result == VK_ERROR_OUT_OF_POOL_MEMORY || result == VK_ERROR_FRAGMENTED_POOL) {
{
VkDescriptorPool pool;
VUK_DO_OR_RETURN(upstream->allocate_descriptor_pools({ &pool, 1 }, { &dpci, 1 }, loc));
last_pool = &*impl->ds_pools.emplace(pool);
}
dsai.descriptorPool = *last_pool;
result = impl->ctx->vkAllocateDescriptorSets(impl->device, &dsai, &dst[i].descriptor_set);
if (result != VK_SUCCESS) {
return { expected_error, AllocateException{ result } };
}
}
}
return { expected_value };
}
Result<void, AllocateException> DeviceLinearResource::allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst,
std::span<const VkQueryPoolCreateInfo> cis,
SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_timestamp_query_pools(dst, cis, loc));
auto& vec = impl->ts_query_pools;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) {} // noop
Result<void, AllocateException>
DeviceLinearResource::allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
if (ci.pool) { // use given pool to allocate query
ci.pool->queries[ci.pool->count++] = ci.query;
dst[i].id = ci.pool->count;
dst[i].pool = ci.pool->pool;
} else { // allocate a pool on demand
if (impl->query_index % TimestampQueryPool::num_queries == 0) {
VkQueryPoolCreateInfo qpci{ VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO };
qpci.queryCount = TimestampQueryPool::num_queries;
qpci.queryType = VK_QUERY_TYPE_TIMESTAMP;
TimestampQueryPool p;
VUK_DO_OR_RETURN(upstream->allocate_timestamp_query_pools(std::span{ &p, 1 }, std::span{ &qpci, 1 }, loc));
auto& vec = impl->ts_query_pools;
vec.emplace_back(p);
impl->current_ts_pool = vec.size() - 1;
}
auto& pool = impl->ts_query_pools[impl->current_ts_pool];
pool.queries[pool.count++] = ci.query;
dst[i].id = pool.count - 1;
dst[i].pool = pool.pool;
impl->query_index++;
}
}
return { expected_value };
}
void DeviceLinearResource::deallocate_timestamp_queries(std::span<const TimestampQuery> src) {} // noop
Result<void, AllocateException> DeviceLinearResource::allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_timeline_semaphores(dst, loc));
auto& vec = impl->tsemas;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceLinearResource::deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) {} // noop
void DeviceLinearResource::wait() {
if (impl->fences.size() > 0) {
if (impl->fences.size() > 64) {
int i = 0;
for (; i < impl->fences.size() - 64; i += 64) {
impl->ctx->vkWaitForFences(impl->device, 64, impl->fences.data() + i, true, UINT64_MAX);
}
impl->ctx->vkWaitForFences(impl->device, (uint32_t)impl->fences.size() - i, impl->fences.data() + i, true, UINT64_MAX);
} else {
impl->ctx->vkWaitForFences(impl->device, (uint32_t)impl->fences.size(), impl->fences.data(), true, UINT64_MAX);
}
}
if (impl->tsemas.size() > 0) {
VkSemaphoreWaitInfo swi{ VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO };
std::vector<VkSemaphore> semas(impl->tsemas.size());
std::vector<uint64_t> values(impl->tsemas.size());
for (uint64_t i = 0; i < impl->tsemas.size(); i++) {
semas[i] = impl->tsemas[i].semaphore;
values[i] = *impl->tsemas[i].value;
}
swi.pSemaphores = semas.data();
swi.pValues = values.data();
swi.semaphoreCount = (uint32_t)impl->tsemas.size();
impl->ctx->vkWaitSemaphores(impl->device, &swi, UINT64_MAX);
}
}
void DeviceLinearResource::free() {
auto& f = *impl;
upstream->deallocate_semaphores(f.semaphores);
upstream->deallocate_fences(f.fences);
upstream->deallocate_command_buffers(f.cmdbuffers_to_free);
for (auto& pool : f.cmdpools_to_free) {
f.ctx->vkResetCommandPool(f.device, pool.command_pool, {});
}
upstream->deallocate_command_pools(f.cmdpools_to_free);
upstream->deallocate_framebuffers(f.framebuffers);
upstream->deallocate_images(f.images);
upstream->deallocate_image_views(f.image_views);
upstream->deallocate_buffers(f.buffers);
upstream->deallocate_persistent_descriptor_sets(f.persistent_descriptor_sets);
upstream->deallocate_descriptor_sets(f.descriptor_sets);
f.ctx->make_timestamp_results_available(f.ts_query_pools);
upstream->deallocate_timestamp_query_pools(f.ts_query_pools);
upstream->deallocate_timeline_semaphores(f.tsemas);
upstream->deallocate_acceleration_structures(f.ass);
for (auto& p : f.ds_pools) {
upstream->deallocate_descriptor_pools({ &p, 1 });
}
}
} // namespace vuk<file_sep>#include "Cache.hpp"
#include "vuk/Context.hpp"
#include "vuk/PipelineInstance.hpp"
#include <plf_colony.h>
#include <robin_hood.h>
#include <shared_mutex>
#include <mutex>
namespace vuk {
template<class T>
struct CacheImpl {
plf::colony<T> pool;
robin_hood::unordered_node_map<create_info_t<T>, typename Cache<T>::LRUEntry> lru_map;
std::shared_mutex cache_mtx;
};
template<class T>
Cache<T>::Cache(void* allocator, create_fn create, destroy_fn destroy) : impl(new CacheImpl<T>()), create(create), destroy(destroy), allocator(allocator) {}
template<class T>
T& Cache<T>::acquire(const create_info_t<T>& ci) {
assert(0);
static T t;
return t;
}
template<class T>
T& Cache<T>::acquire(const create_info_t<T>& ci, uint64_t current_frame) {
std::shared_lock _(impl->cache_mtx);
if (auto it = impl->lru_map.find(ci); it != impl->lru_map.end()) {
it->second.last_use_frame = current_frame;
return *it->second.ptr;
} else {
_.unlock();
std::unique_lock ulock(impl->cache_mtx);
auto pit = impl->pool.emplace(create(allocator, ci));
typename Cache::LRUEntry entry{ &*pit, current_frame };
it = impl->lru_map.emplace(ci, entry).first;
return *it->second.ptr;
}
}
template<class T>
void Cache<T>::collect(uint64_t current_frame, size_t threshold) {
std::unique_lock _(impl->cache_mtx);
for (auto it = impl->lru_map.begin(); it != impl->lru_map.end();) {
auto last_use_frame = it->second.last_use_frame;
if ((int64_t)current_frame - (int64_t)last_use_frame > (int64_t)threshold) {
destroy(allocator, *it->second.ptr);
impl->pool.erase(impl->pool.get_iterator(it->second.ptr));
it = impl->lru_map.erase(it);
} else {
++it;
}
}
}
template<class T>
void Cache<T>::clear() {
std::unique_lock _(impl->cache_mtx);
for (auto it = impl->pool.begin(); it != impl->pool.end(); ++it) {
destroy(allocator, *it);
}
impl->pool.clear();
impl->lru_map.clear();
}
template<>
ShaderModule& Cache<ShaderModule>::acquire(const create_info_t<ShaderModule>& ci) {
std::shared_lock _(impl->cache_mtx);
if (auto it = impl->lru_map.find(ci); it != impl->lru_map.end()) {
if (it->second.load_cnt.load(std::memory_order_relaxed) == 0) { // perform a relaxed load to skip the atomic_wait path
std::atomic_wait(&it->second.load_cnt, 0);
}
return *it->second.ptr;
} else {
_.unlock();
std::unique_lock ulock(impl->cache_mtx);
typename Cache::LRUEntry entry{ nullptr, INT64_MAX };
it = impl->lru_map.emplace(ci, entry).first;
ulock.unlock();
auto pit = impl->pool.emplace(create(allocator, ci));
it->second.ptr = &*pit;
it->second.load_cnt.store(1);
it->second.load_cnt.notify_all();
return *it->second.ptr;
}
}
template<>
PipelineBaseInfo& Cache<PipelineBaseInfo>::acquire(const create_info_t<PipelineBaseInfo>& ci) {
std::shared_lock _(impl->cache_mtx);
if (auto it = impl->lru_map.find(ci); it != impl->lru_map.end()) {
return *it->second.ptr;
} else {
_.unlock();
std::unique_lock ulock(impl->cache_mtx);
auto pit = impl->pool.emplace(create(allocator, ci));
typename Cache::LRUEntry entry{ &*pit, INT64_MAX };
it = impl->lru_map.emplace(ci, entry).first;
return *it->second.ptr;
}
}
template<>
DescriptorSetLayoutAllocInfo& Cache<DescriptorSetLayoutAllocInfo>::acquire(const create_info_t<DescriptorSetLayoutAllocInfo>& ci) {
std::shared_lock _(impl->cache_mtx);
if (auto it = impl->lru_map.find(ci); it != impl->lru_map.end()) {
return *it->second.ptr;
} else {
_.unlock();
std::unique_lock ulock(impl->cache_mtx);
auto pit = impl->pool.emplace(create(allocator, ci));
typename Cache::LRUEntry entry{ &*pit, INT64_MAX };
it = impl->lru_map.emplace(ci, entry).first;
return *it->second.ptr;
}
}
template<>
VkPipelineLayout& Cache<VkPipelineLayout>::acquire(const create_info_t<VkPipelineLayout>& ci) {
std::shared_lock _(impl->cache_mtx);
if (auto it = impl->lru_map.find(ci); it != impl->lru_map.end()) {
return *it->second.ptr;
} else {
_.unlock();
std::unique_lock ulock(impl->cache_mtx);
auto pit = impl->pool.emplace(create(allocator, ci));
typename Cache::LRUEntry entry{ &*pit, INT64_MAX };
it = impl->lru_map.emplace(ci, entry).first;
return *it->second.ptr;
}
}
// unfortunately, we need to manage extended_data lifetime here
template<>
GraphicsPipelineInfo& Cache<GraphicsPipelineInfo>::acquire(const create_info_t<GraphicsPipelineInfo>& ci, uint64_t current_frame) {
std::shared_lock _(impl->cache_mtx);
if (auto it = impl->lru_map.find(ci); it != impl->lru_map.end()) {
it->second.last_use_frame = current_frame;
if (it->second.load_cnt.load(std::memory_order_relaxed) == 0) { // perform a relaxed load to skip the atomic_wait path
std::atomic_wait(&it->second.load_cnt, 0);
}
return *it->second.ptr;
} else {
_.unlock();
auto ci_copy = ci;
if (!ci_copy.is_inline()) {
ci_copy.extended_data = new std::byte[ci_copy.extended_size];
memcpy(ci_copy.extended_data, ci.extended_data, ci_copy.extended_size);
}
std::unique_lock ulock(impl->cache_mtx);
typename Cache::LRUEntry entry{ nullptr, current_frame };
it = impl->lru_map.emplace(ci_copy, entry).first;
auto pit = impl->pool.emplace(create(allocator, ci_copy));
ulock.unlock();
it->second.ptr = &*pit;
it->second.load_cnt.store(1);
it->second.load_cnt.notify_all();
return *it->second.ptr;
}
}
template<>
void Cache<GraphicsPipelineInfo>::collect(uint64_t current_frame, size_t threshold) {
std::unique_lock _(impl->cache_mtx);
for (auto it = impl->lru_map.begin(); it != impl->lru_map.end();) {
auto last_use_frame = it->second.last_use_frame;
if ((int64_t)current_frame - (int64_t)last_use_frame > (int64_t)threshold) {
destroy(allocator, *it->second.ptr);
if (!it->first.is_inline()) {
delete it->first.extended_data;
}
impl->pool.erase(impl->pool.get_iterator(it->second.ptr));
it = impl->lru_map.erase(it);
} else {
++it;
}
}
}
template<class T>
std::optional<T> Cache<T>::remove(const create_info_t<T>& ci) {
std::unique_lock _(impl->cache_mtx);
auto it = impl->lru_map.find(ci);
if (it != impl->lru_map.end()) {
auto res = std::move(*it->second.ptr);
impl->pool.erase(impl->pool.get_iterator(it->second.ptr));
impl->lru_map.erase(it);
return res;
}
return {};
}
template<class T>
void Cache<T>::remove_ptr(const T* ptr) {
std::unique_lock _(impl->cache_mtx);
for (auto it = impl->lru_map.begin(); it != impl->lru_map.end(); ++it) {
if (ptr == it->second.ptr) {
impl->pool.erase(impl->pool.get_iterator(it->second.ptr));
impl->lru_map.erase(it);
return;
}
}
}
template<class T>
Cache<T>::~Cache() {
for (auto& v : impl->pool) {
destroy(allocator, v);
}
delete impl;
}
template class Cache<vuk::GraphicsPipelineInfo>;
template class Cache<vuk::PipelineBaseInfo>;
template class Cache<vuk::ComputePipelineInfo>;
template class Cache<vuk::RayTracingPipelineInfo>;
template class Cache<VkRenderPass>;
template class Cache<vuk::Sampler>;
template class Cache<VkPipelineLayout>;
template class Cache<vuk::DescriptorSetLayoutAllocInfo>;
template class Cache<vuk::ShaderModule>;
template struct CacheImpl<vuk::ShaderModule>;
template class Cache<vuk::ImageWithIdentity>;
template class Cache<vuk::ImageView>;
template class Cache<vuk::DescriptorPool>;
} // namespace vuk<file_sep>#pragma once
namespace vuk {
template<class T>
struct create_info;
template<class T>
using create_info_t = typename create_info<T>::type;
} // namespace vuk
<file_sep>#pragma once
#include "../examples/glfw.hpp"
#include "../examples/utils.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/CommandBuffer.hpp"
#include "vuk/Context.hpp"
#include "vuk/RenderGraph.hpp"
#include "vuk/SampledImage.hpp"
#include "vuk/resources/DeviceFrameResource.hpp"
#include <VkBootstrap.h>
#include <backends/imgui_impl_glfw.h>
#include <functional>
#include <optional>
#include <stdio.h>
#include <string>
#include <string_view>
#include <vector>
namespace vuk {
struct BenchRunner;
struct CaseBase {
std::string_view label;
std::vector<std::string_view> subcase_labels;
std::vector<std::function<RenderGraph(BenchRunner&, vuk::Allocator&, Query, Query)>> subcases;
std::vector<std::vector<double>> timings;
std::vector<std::vector<float>> binned;
std::vector<uint32_t> last_stage_ran;
std::vector<uint32_t> runs_required;
std::vector<double> est_mean;
std::vector<double> est_variance;
std::vector<std::pair<double, double>> min_max;
std::vector<double> mean;
std::vector<double> variance;
};
struct BenchBase {
std::string_view name;
std::function<void(BenchRunner&, vuk::Allocator&)> setup;
std::function<void(BenchRunner&, vuk::Allocator&)> gui;
std::function<void(BenchRunner&, vuk::Allocator&)> cleanup;
std::function<CaseBase&(unsigned)> get_case;
size_t num_cases;
};
template<class... Args>
struct Bench {
BenchBase base;
using Params = std::tuple<Args...>;
struct Case : CaseBase {
template<class F>
Case(std::string_view label, F&& subcase_template) : CaseBase{ label } {
std::apply(
[this, subcase_template](auto&&... ts) {
(subcases.emplace_back([=](BenchRunner& runner, vuk::Allocator& frame_allocator, Query start, Query end) {
return subcase_template(runner, frame_allocator, start, end, ts);
}),
...);
(subcase_labels.emplace_back(ts.description), ...);
timings.resize(sizeof...(Args));
runs_required.resize(sizeof...(Args));
mean.resize(sizeof...(Args));
variance.resize(sizeof...(Args));
est_mean.resize(sizeof...(Args));
est_variance.resize(sizeof...(Args));
last_stage_ran.resize(sizeof...(Args));
min_max.resize(sizeof...(Args));
binned.resize(sizeof...(Args));
},
Params{});
}
};
std::vector<Case> cases;
};
} // namespace vuk
namespace vuk {
struct BenchRunner {
VkDevice device;
VkPhysicalDevice physical_device;
VkQueue graphics_queue;
std::optional<Context> context;
std::optional<DeviceSuperFrameResource> xdev_rf_alloc;
std::optional<Allocator> global;
vuk::SwapchainRef swapchain;
GLFWwindow* window;
VkSurfaceKHR surface;
vkb::Instance vkbinstance;
vkb::Device vkbdevice;
util::ImGuiData imgui_data;
plf::colony<vuk::SampledImage> sampled_images;
Query start, end;
unsigned current_case = 0;
unsigned current_subcase = 0;
unsigned current_stage = 0;
unsigned num_runs = 0;
BenchBase* bench;
BenchRunner();
void setup() {
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForVulkan(window, true);
start = context->create_timestamp_query();
end = context->create_timestamp_query();
{ imgui_data = util::ImGui_ImplVuk_Init(*global); }
bench->setup(*this, *global);
}
void render();
void cleanup() {
context->wait_idle();
if (bench->cleanup) {
bench->cleanup(*this, *global);
}
}
~BenchRunner() {
imgui_data.font_texture.view.reset();
imgui_data.font_texture.image.reset();
xdev_rf_alloc.reset();
context.reset();
vkDestroySurfaceKHR(vkbinstance.instance, surface, nullptr);
destroy_window_glfw(window);
vkb::destroy_device(vkbdevice);
vkb::destroy_instance(vkbinstance);
}
static BenchRunner& get_runner() {
static BenchRunner runner;
return runner;
}
};
} // namespace vuk
namespace util {
struct Register {
template<class... Args>
Register(vuk::Bench<Args...>& x) {
vuk::BenchRunner::get_runner().bench = &x.base;
vuk::BenchRunner::get_runner().bench->get_case = [&x](unsigned i) -> vuk::CaseBase& {
return x.cases[i];
};
vuk::BenchRunner::get_runner().bench->num_cases = x.cases.size();
}
};
} // namespace util
#define CONCAT_IMPL(x, y) x##y
#define MACRO_CONCAT(x, y) CONCAT_IMPL(x, y)
#define REGISTER_BENCH(x) util::Register MACRO_CONCAT(_reg_, __LINE__)(x)
<file_sep>#pragma once
#include <VkBootstrap.h>
#include <fstream>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <imgui.h>
#include <plf_colony.h>
#include <sstream>
#include <string_view>
#include <utility>
#include <vector>
#include <vuk/Context.hpp>
#include <vuk/Swapchain.hpp>
#include <vuk/Types.hpp>
#include <vuk/vuk_fwd.hpp>
namespace vuk {
struct Pass;
struct RenderGraph;
} // namespace vuk
namespace util {
struct Vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec3 tangent;
glm::vec3 bitangent;
glm::vec2 uv_coordinates;
};
using Mesh = std::pair<std::vector<Vertex>, std::vector<unsigned>>;
inline Mesh generate_cube() {
// clang-format off
return Mesh(std::vector<Vertex> {
// back
Vertex{ {-1, -1, -1}, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, {1, 1} }, Vertex{ {1, 1, -1}, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, {0, 0} },
Vertex{ {1, -1, -1}, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, {0, 1} }, Vertex{ {1, 1, -1}, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, {0, 0} },
Vertex{ {-1, -1, -1}, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, {1, 1} }, Vertex{ {-1, 1, -1}, {0, 0, -1}, {-1, 0, 0}, {0, 1, 0}, {1, 0} },
// front
Vertex{ {-1, -1, 1}, {0, 0, 1}, {1, 0.0, 0}, {0, 1, 0}, {0, 1} }, Vertex{ {1, -1, 1}, {0, 0, 1},{1, 0.0, 0}, {0, 1, 0}, {1, 1} },
Vertex{ {1, 1, 1}, {0, 0, 1}, {1, 0.0, 0}, {0, 1, 0}, {1, 0} }, Vertex{ {1, 1, 1}, {0, 0, 1}, {1, 0.0, 0}, {0, 1, 0}, {1, 0} },
Vertex{ {-1, 1, 1}, {0, 0, 1}, {1, 0.0, 0}, {0, 1, 0}, {0, 0} }, Vertex{ {-1, -1, 1}, {0, 0, 1}, {1, 0.0, 0}, {0, 1, 0}, {0, 1} },
// left
Vertex{ {-1, 1, -1}, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 0} }, Vertex{ {-1, -1, -1}, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1} },
Vertex{ {-1, 1, 1}, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, {1, 0} }, Vertex{ {-1, -1, -1}, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1} },
Vertex{ {-1, -1, 1}, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, {1, 1} }, Vertex{ {-1, 1, 1}, {-1, 0, 0}, {0, 0, 1}, {0, 1, 0}, {1, 0} },
// right
Vertex{ {1, 1, 1}, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, {0, 0} }, Vertex{ {1, -1, -1}, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, {1, 1} },
Vertex{ {1, 1, -1}, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, {1, 0} }, Vertex{ {1, -1, -1}, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, {1, 1} },
Vertex{ {1, 1, 1}, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, {0, 0} }, Vertex{ {1, -1, 1}, {1, 0, 0}, {0, 0, -1}, {0, 1, 0}, {0, 1} },
// bottom
Vertex{ {-1, -1, -1}, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, {0, 1} }, Vertex{ {1, -1, -1}, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, {1, 1} },
Vertex{ {1, -1, 1}, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, {1, 0} }, Vertex{ {1, -1, 1}, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, {1, 0} },
Vertex{ {-1, -1, 1}, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, {0, 0} }, Vertex{ {-1, -1, -1}, {0, -1, 0}, {1, 0, 0}, {0, 0, 1}, {0, 1} },
// top
Vertex{ {-1, 1, -1}, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, {0, 0} }, Vertex{ {1, 1, 1}, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, {1, 1} },
Vertex{ {1, 1, -1}, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, {1, 0} }, Vertex{ {1, 1, 1}, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, {1, 1} },
Vertex{ {-1, 1, -1}, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, {0, 0} }, Vertex{ {-1, 1, 1}, {0, 1, 0}, {1, 0, 0}, {0, 0, -1}, {0, 1} } },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35 });
// clang-format on
}
inline vuk::Swapchain make_swapchain(vkb::Device vkbdevice, std::optional<VkSwapchainKHR> old_swapchain) {
vkb::SwapchainBuilder swb(vkbdevice);
swb.set_desired_format(vuk::SurfaceFormatKHR{ vuk::Format::eR8G8B8A8Srgb, vuk::ColorSpaceKHR::eSrgbNonlinear });
swb.add_fallback_format(vuk::SurfaceFormatKHR{ vuk::Format::eB8G8R8A8Srgb, vuk::ColorSpaceKHR::eSrgbNonlinear });
swb.set_desired_present_mode((VkPresentModeKHR)vuk::PresentModeKHR::eImmediate);
swb.set_image_usage_flags(VkImageUsageFlagBits::VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VkImageUsageFlagBits::VK_IMAGE_USAGE_TRANSFER_DST_BIT);
if (old_swapchain) {
swb.set_old_swapchain(*old_swapchain);
}
auto vkswapchain = swb.build();
vuk::Swapchain sw{};
auto images = *vkswapchain->get_images();
auto views = *vkswapchain->get_image_views();
for (auto& i : images) {
sw.images.push_back(vuk::Image{ i, nullptr });
}
for (auto& i : views) {
sw.image_views.emplace_back();
sw.image_views.back().payload = i;
}
sw.extent = vuk::Extent2D{ vkswapchain->extent.width, vkswapchain->extent.height };
sw.format = vuk::Format(vkswapchain->image_format);
sw.surface = vkbdevice.surface;
sw.swapchain = vkswapchain->swapchain;
return sw;
}
struct ImGuiData {
vuk::Texture font_texture;
vuk::SamplerCreateInfo font_sci;
std::unique_ptr<vuk::SampledImage> font_si;
};
ImGuiData ImGui_ImplVuk_Init(vuk::Allocator& allocator);
vuk::Future ImGui_ImplVuk_Render(vuk::Allocator& allocator,
vuk::Future target,
ImGuiData& data,
ImDrawData* draw_data,
const plf::colony<vuk::SampledImage>& sampled_images);
inline std::string read_entire_file(const std::string& path) {
std::ostringstream buf;
std::ifstream input(path.c_str());
assert(input);
buf << input.rdbuf();
return buf.str();
}
inline std::vector<uint32_t> read_spirv(const std::string& path) {
std::ostringstream buf;
std::ifstream input(path.c_str(), std::ios::ate | std::ios::binary);
assert(input);
size_t file_size = (size_t)input.tellg();
std::vector<uint32_t> buffer(file_size / sizeof(uint32_t));
input.seekg(0);
input.read(reinterpret_cast<char*>(buffer.data()), file_size);
return buffer;
}
} // namespace util<file_sep>#pragma once
#include "vuk/Config.hpp"
#include "vuk/Exception.hpp"
#include "vuk/FixedVector.hpp"
#include "vuk/Image.hpp"
#include "vuk/PipelineInstance.hpp"
#include "vuk/Query.hpp"
#include "vuk/Result.hpp"
#include "vuk/Types.hpp"
#include "vuk/vuk_fwd.hpp"
#include <optional>
#include <utility>
namespace vuk {
class Context;
struct Ignore {
Ignore(size_t bytes) : format(Format::eUndefined), bytes((uint32_t)bytes) {}
Ignore(Format format) : format(format) {}
Format format;
uint32_t bytes = 0;
uint32_t to_size();
};
struct FormatOrIgnore {
FormatOrIgnore(Format format);
FormatOrIgnore(Ignore ign);
bool ignore;
Format format;
uint32_t size;
};
struct Packed {
Packed() {}
Packed(std::initializer_list<FormatOrIgnore> ilist) : list(ilist) {}
fixed_vector<FormatOrIgnore, VUK_MAX_ATTRIBUTES> list;
};
struct DrawIndexedIndirectCommand {
uint32_t indexCount = {};
uint32_t instanceCount = {};
uint32_t firstIndex = {};
int32_t vertexOffset = {};
uint32_t firstInstance = {};
operator VkDrawIndexedIndirectCommand const&() const noexcept {
return *reinterpret_cast<const VkDrawIndexedIndirectCommand*>(this);
}
operator VkDrawIndexedIndirectCommand&() noexcept {
return *reinterpret_cast<VkDrawIndexedIndirectCommand*>(this);
}
bool operator==(DrawIndexedIndirectCommand const& rhs) const noexcept {
return (indexCount == rhs.indexCount) && (instanceCount == rhs.instanceCount) && (firstIndex == rhs.firstIndex) && (vertexOffset == rhs.vertexOffset) &&
(firstInstance == rhs.firstInstance);
}
bool operator!=(DrawIndexedIndirectCommand const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(sizeof(DrawIndexedIndirectCommand) == sizeof(VkDrawIndexedIndirectCommand), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<DrawIndexedIndirectCommand>::value, "struct wrapper is not a standard layout!");
struct ImageSubresourceLayers {
ImageAspectFlags aspectMask = {};
uint32_t mipLevel = 0;
uint32_t baseArrayLayer = 0;
uint32_t layerCount = 1;
operator VkImageSubresourceLayers const&() const noexcept {
return *reinterpret_cast<const VkImageSubresourceLayers*>(this);
}
operator VkImageSubresourceLayers&() noexcept {
return *reinterpret_cast<VkImageSubresourceLayers*>(this);
}
bool operator==(ImageSubresourceLayers const& rhs) const noexcept {
return (aspectMask == rhs.aspectMask) && (mipLevel == rhs.mipLevel) && (baseArrayLayer == rhs.baseArrayLayer) && (layerCount == rhs.layerCount);
}
bool operator!=(ImageSubresourceLayers const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(sizeof(ImageSubresourceLayers) == sizeof(VkImageSubresourceLayers), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<ImageSubresourceLayers>::value, "struct wrapper is not a standard layout!");
struct ImageBlit {
ImageSubresourceLayers srcSubresource = {};
std::array<Offset3D, 2> srcOffsets = {};
ImageSubresourceLayers dstSubresource = {};
std::array<Offset3D, 2> dstOffsets = {};
operator VkImageBlit const&() const noexcept {
return *reinterpret_cast<const VkImageBlit*>(this);
}
operator VkImageBlit&() noexcept {
return *reinterpret_cast<VkImageBlit*>(this);
}
bool operator==(ImageBlit const& rhs) const noexcept {
return (srcSubresource == rhs.srcSubresource) && (srcOffsets == rhs.srcOffsets) && (dstSubresource == rhs.dstSubresource) &&
(dstOffsets == rhs.dstOffsets);
}
bool operator!=(ImageBlit const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(sizeof(ImageBlit) == sizeof(VkImageBlit), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<ImageBlit>::value, "struct wrapper is not a standard layout!");
struct BufferImageCopy {
VkDeviceSize bufferOffset = {};
uint32_t bufferRowLength = {};
uint32_t bufferImageHeight = {};
ImageSubresourceLayers imageSubresource = {};
Offset3D imageOffset = {};
Extent3D imageExtent = {};
operator VkBufferImageCopy const&() const noexcept {
return *reinterpret_cast<const VkBufferImageCopy*>(this);
}
operator VkBufferImageCopy&() noexcept {
return *reinterpret_cast<VkBufferImageCopy*>(this);
}
bool operator==(BufferImageCopy const& rhs) const noexcept {
return (bufferOffset == rhs.bufferOffset) && (bufferRowLength == rhs.bufferRowLength) && (bufferImageHeight == rhs.bufferImageHeight) &&
(imageSubresource == rhs.imageSubresource) && (imageOffset == rhs.imageOffset) && (imageExtent == rhs.imageExtent);
}
bool operator!=(BufferImageCopy const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(sizeof(BufferImageCopy) == sizeof(VkBufferImageCopy), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<BufferImageCopy>::value, "struct wrapper is not a standard layout!");
struct ExecutableRenderGraph;
struct ImageAttachment;
struct PassInfo;
struct Query;
class Allocator;
class CommandBuffer {
protected:
friend struct RenderGraph;
friend struct ExecutableRenderGraph;
ExecutableRenderGraph* rg = nullptr;
Context& ctx;
Allocator* allocator;
CommandBufferAllocation command_buffer_allocation;
VkCommandBuffer command_buffer;
struct RenderPassInfo {
VkRenderPass render_pass;
uint32_t subpass;
Extent2D extent;
SampleCountFlagBits samples;
VkAttachmentReference const* depth_stencil_attachment;
std::array<QualifiedName, VUK_MAX_COLOR_ATTACHMENTS> color_attachment_names;
std::span<const VkAttachmentReference> color_attachments;
};
std::optional<RenderPassInfo> ongoing_render_pass;
PassInfo* current_pass = nullptr;
Result<void> current_error = { expected_value };
// Pipeline state
// Enabled dynamic state
DynamicStateFlags dynamic_state_flags = {};
// Current & next graphics & compute pipelines
PipelineBaseInfo* next_pipeline = nullptr;
PipelineBaseInfo* next_compute_pipeline = nullptr;
PipelineBaseInfo* next_ray_tracing_pipeline = nullptr;
std::optional<GraphicsPipelineInfo> current_graphics_pipeline;
std::optional<ComputePipelineInfo> current_compute_pipeline;
std::optional<RayTracingPipelineInfo> current_ray_tracing_pipeline;
// Input assembly & fixed-function attributes
PrimitiveTopology topology = PrimitiveTopology::eTriangleList;
Bitset<VUK_MAX_ATTRIBUTES> set_attribute_descriptions = {};
VertexInputAttributeDescription attribute_descriptions[VUK_MAX_ATTRIBUTES];
Bitset<VUK_MAX_ATTRIBUTES> set_binding_descriptions = {};
VkVertexInputBindingDescription binding_descriptions[VUK_MAX_ATTRIBUTES];
// Specialization constant support
struct SpecEntry {
bool is_double;
std::byte data[sizeof(double)];
};
std::unordered_map<uint32_t, SpecEntry> spec_map_entries; // constantID -> SpecEntry
// Individual pipeline states
std::optional<PipelineRasterizationStateCreateInfo> rasterization_state;
std::optional<PipelineDepthStencilStateCreateInfo> depth_stencil_state;
std::optional<PipelineRasterizationConservativeStateCreateInfo> conservative_state;
bool broadcast_color_blend_attachment_0 = false;
Bitset<VUK_MAX_COLOR_ATTACHMENTS> set_color_blend_attachments = {};
fixed_vector<PipelineColorBlendAttachmentState, VUK_MAX_COLOR_ATTACHMENTS> color_blend_attachments;
std::optional<std::array<float, 4>> blend_constants;
float line_width = 1.0f;
fixed_vector<VkViewport, VUK_MAX_VIEWPORTS> viewports;
fixed_vector<VkRect2D, VUK_MAX_SCISSORS> scissors;
// Push constants
unsigned char push_constant_buffer[VUK_MAX_PUSHCONSTANT_SIZE];
fixed_vector<VkPushConstantRange, VUK_MAX_PUSHCONSTANT_RANGES> pcrs;
// Descriptor sets
DescriptorSetStrategyFlags ds_strategy_flags = {};
Bitset<VUK_MAX_SETS> sets_used = {};
VkDescriptorSetLayout set_layouts_used[VUK_MAX_SETS] = {};
Bitset<VUK_MAX_SETS> sets_to_bind = {};
SetBinding set_bindings[VUK_MAX_SETS] = {};
Bitset<VUK_MAX_SETS> persistent_sets_to_bind = {};
std::pair<VkDescriptorSet, VkDescriptorSetLayout> persistent_sets[VUK_MAX_SETS] = {};
// for rendergraph
CommandBuffer(ExecutableRenderGraph& rg, Context& ctx, Allocator& allocator, VkCommandBuffer cb);
CommandBuffer(ExecutableRenderGraph& rg, Context& ctx, Allocator& allocator, VkCommandBuffer cb, std::optional<RenderPassInfo> ongoing);
public:
/// @brief Retrieve parent context
Context& get_context() {
return ctx;
}
VkCommandBuffer get_underlying() const {
return command_buffer;
}
/// @brief Retrieve information about the current renderpass
const RenderPassInfo& get_ongoing_render_pass() const;
/// @brief Retrieve Buffer attached to given name
/// @return the attached Buffer or RenderGraphException
Result<Buffer> get_resource_buffer(Name resource_name) const;
/// @brief Retrieve Buffer attached to given NameReference
/// @return the attached Buffer or RenderGraphException
Result<Buffer> get_resource_buffer(const NameReference& resource_name_reference) const;
/// @brief Retrieve Image attached to given name
/// @return the attached Image or RenderGraphException
Result<Image> get_resource_image(Name resource_name) const;
/// @brief Retrieve ImageView attached to given name
/// @return the attached ImageView or RenderGraphException
Result<ImageView> get_resource_image_view(Name resource_name) const;
/// @brief Retrieve ImageAttachment attached to given name
/// @return the attached ImageAttachment or RenderGraphException
Result<ImageAttachment> get_resource_image_attachment(Name resource_name) const;
/// @brief Retrieve ImageAttachment attached to given NameReference
/// @return the attached ImageAttachment or RenderGraphException
Result<ImageAttachment> get_resource_image_attachment(const NameReference& resource_name_reference) const;
// command buffer state setting
// when a state is set it is persistent for a pass (similar to Vulkan dynamic state) - see documentation
/// @brief Set the strategy for allocating and updating ephemeral descriptor sets
/// @param ds_strategy_flags Mask of strategy options
///
/// The default strategy is taken from the context when entering a new Pass
CommandBuffer& set_descriptor_set_strategy(DescriptorSetStrategyFlags ds_strategy_flags);
/// @brief Set mask of dynamic state in CommandBuffer
/// @param dynamic_state_flags Mask of states (flag set = dynamic, flag clear = static)
CommandBuffer& set_dynamic_state(DynamicStateFlags dynamic_state_flags);
/// @brief Set the viewport transformation for the specified viewport index
/// @param index viewport index to modify
/// @param vp Viewport to be set
CommandBuffer& set_viewport(unsigned index, Viewport vp);
/// @brief Set the viewport transformation for the specified viewport index from a rect
/// @param index viewport index to modify
/// @param area Rect2D extents of the Viewport
/// @param min_depth Minimum depth of Viewport
/// @param max_depth Maximum depth of Viewport
CommandBuffer& set_viewport(unsigned index, Rect2D area, float min_depth = 0.f, float max_depth = 1.f);
/// @brief Set the scissor for the specified scissor index from a rect
/// @param index scissor index to modify
/// @param area Rect2D extents of the scissor
CommandBuffer& set_scissor(unsigned index, Rect2D area);
/// @brief Set the rasterization state
CommandBuffer& set_rasterization(PipelineRasterizationStateCreateInfo rasterization_state);
/// @brief Set the depth/stencil state
CommandBuffer& set_depth_stencil(PipelineDepthStencilStateCreateInfo depth_stencil_state);
/// @brief Set the conservative rasterization state
CommandBuffer& set_conservative(PipelineRasterizationConservativeStateCreateInfo conservative_state);
/// @brief Set one color blend state to use for all color attachments
CommandBuffer& broadcast_color_blend(PipelineColorBlendAttachmentState color_blend_state);
/// @brief Set one color blend preset to use for all color attachments
CommandBuffer& broadcast_color_blend(BlendPreset blend_preset);
/// @brief Set color blend state for a specific color attachment
/// @param color_attachment the Name of the color_attachment to set the blend state for
/// @param color_blend_state PipelineColorBlendAttachmentState to use
CommandBuffer& set_color_blend(Name color_attachment, PipelineColorBlendAttachmentState color_blend_state);
/// @brief Set color blend preset for a specific color attachment
/// @param color_attachment the Name of the color_attachment to set the blend preset for
/// @param blend_preset BlendPreset to use
CommandBuffer& set_color_blend(Name color_attachment, BlendPreset blend_preset);
/// @brief Set blend constants
CommandBuffer& set_blend_constants(std::array<float, 4> blend_constants);
/// @brief Bind a graphics pipeline for subsequent draws
/// @param pipeline_base pointer to a pipeline base to bind
CommandBuffer& bind_graphics_pipeline(PipelineBaseInfo* pipeline_base);
/// @brief Bind a named graphics pipeline for subsequent draws
/// @param named_pipeline graphics pipeline name
CommandBuffer& bind_graphics_pipeline(Name named_pipeline);
/// @brief Bind a compute pipeline for subsequent dispatches
/// @param pipeline_base pointer to a pipeline base to bind
CommandBuffer& bind_compute_pipeline(PipelineBaseInfo* pipeline_base);
/// @brief Bind a named graphics pipeline for subsequent dispatches
/// @param named_pipeline compute pipeline name
CommandBuffer& bind_compute_pipeline(Name named_pipeline);
/// @brief Bind a ray tracing pipeline for subsequent draws
/// @param pipeline_base pointer to a pipeline base to bind
CommandBuffer& bind_ray_tracing_pipeline(PipelineBaseInfo* pipeline_base);
/// @brief Bind a named ray tracing pipeline for subsequent draws
/// @param named_pipeline graphics pipeline name
CommandBuffer& bind_ray_tracing_pipeline(Name named_pipeline);
/// @brief Set specialization constants for the command buffer
/// @param constant_id ID of the constant. All stages form a single namespace for IDs.
/// @param value Value of the specialization constant
CommandBuffer& specialize_constants(uint32_t constant_id, bool value);
/// @brief Set specialization constants for the command buffer
/// @param constant_id ID of the constant. All stages form a single namespace for IDs.
/// @param value Value of the specialization constant
CommandBuffer& specialize_constants(uint32_t constant_id, uint32_t value);
/// @brief Set specialization constants for the command buffer
/// @param constant_id ID of the constant. All stages form a single namespace for IDs.
/// @param value Value of the specialization constant
CommandBuffer& specialize_constants(uint32_t constant_id, int32_t value);
/// @brief Set specialization constants for the command buffer
/// @param constant_id ID of the constant. All stages form a single namespace for IDs.
/// @param value Value of the specialization constant
CommandBuffer& specialize_constants(uint32_t constant_id, float value);
/// @brief Set specialization constants for the command buffer
/// @param constant_id ID of the constant. All stages form a single namespace for IDs.
/// @param value Value of the specialization constant
CommandBuffer& specialize_constants(uint32_t constant_id, double value);
/// @brief Set primitive topology
CommandBuffer& set_primitive_topology(PrimitiveTopology primitive_topology);
/// @brief Binds an index buffer with the given type
/// @param buffer The buffer to be bound
/// @param type The index type in the buffer
CommandBuffer& bind_index_buffer(const Buffer& buffer, IndexType type);
/// @brief Binds an index buffer from a Resource with the given type
/// @param resource_name The Name of the Resource to be bound
/// @param type The index type in the buffer
CommandBuffer& bind_index_buffer(Name resource_name, IndexType type);
/// @brief Binds a vertex buffer to the given binding point and configures attributes sourced from this buffer based on a packed format list, the attribute
/// locations are offset with first_location
/// @param binding The binding point of the buffer
/// @param buffer The buffer to be bound
/// @param first_location First location assigned to the attributes
/// @param format_list List of formats packed in buffer to generate attributes from
CommandBuffer& bind_vertex_buffer(unsigned binding, const Buffer& buffer, unsigned first_location, Packed format_list);
/// @brief Binds a vertex buffer from a Resource to the given binding point and configures attributes sourced from this buffer based on a packed format
/// list, the attribute locations are offset with first_location
/// @param binding The binding point of the buffer
/// @param resource_name The Name of the Resource to be bound
/// @param first_location First location assigned to the attributes
/// @param format_list List of formats packed in buffer to generate attributes from
CommandBuffer& bind_vertex_buffer(unsigned binding, Name resource_name, unsigned first_location, Packed format_list);
/// @brief Binds a vertex buffer to the given binding point and configures attributes sourced from this buffer based on a span of attribute descriptions and
/// stride
/// @param binding The binding point of the buffer
/// @param buffer The buffer to be bound
/// @param attribute_descriptions Attributes that are sourced from this buffer
/// @param stride Stride of a vertex sourced from this buffer
CommandBuffer&
bind_vertex_buffer(unsigned binding, const Buffer& buffer, std::span<VertexInputAttributeDescription> attribute_descriptions, uint32_t stride);
/// @brief Binds a vertex buffer from a Resource to the given binding point and configures attributes sourced from this buffer based on a span of attribute
/// descriptions and stride
/// @param binding The binding point of the buffer
/// @param resource_name The Name of the Resource to be bound
/// @param attribute_descriptions Attributes that are sourced from this buffer
/// @param stride Stride of a vertex sourced from this buffer
CommandBuffer& bind_vertex_buffer(unsigned binding, Name resource_name, std::span<VertexInputAttributeDescription> attribute_descriptions, uint32_t stride);
/// @brief Update push constants for the specified stages with bytes
/// @param stages Pipeline stages that can see the updated bytes
/// @param offset Offset into the push constant buffer
/// @param data Pointer to data to be copied into push constants
/// @param size Size of data
CommandBuffer& push_constants(ShaderStageFlags stages, size_t offset, void* data, size_t size);
/// @brief Update push constants for the specified stages with a span of values
/// @tparam T type of values
/// @param stages Pipeline stages that can see the updated bytes
/// @param offset Offset into the push constant buffer
/// @param span Values to write
template<class T>
CommandBuffer& push_constants(ShaderStageFlags stages, size_t offset, std::span<T> span);
/// @brief Update push constants for the specified stages with a single value
/// @tparam T type of value
/// @param stages Pipeline stages that can see the updated bytes
/// @param offset Offset into the push constant buffer
/// @param value Value to write
template<class T>
CommandBuffer& push_constants(ShaderStageFlags stages, size_t offset, T value);
/// @brief Bind a persistent descriptor set to the command buffer
/// @param set The set bind index to be used
/// @param desc_set The persistent descriptor set to be bound
CommandBuffer& bind_persistent(unsigned set, PersistentDescriptorSet& desc_set);
/// @brief Bind a buffer to the command buffer
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the buffer to
/// @param buffer The buffer to be bound
CommandBuffer& bind_buffer(unsigned set, unsigned binding, const Buffer& buffer);
/// @brief Bind a buffer to the command buffer from a Resource
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the buffer to
/// @param resource_name The Name of the Resource to be bound
CommandBuffer& bind_buffer(unsigned set, unsigned binding, Name resource_name);
/// @brief Bind an image to the command buffer
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the image to
/// @param image_view The ImageView to bind
/// @param layout layout of the image when the affected draws execute
CommandBuffer& bind_image(unsigned set, unsigned binding, ImageView image_view, ImageLayout layout = ImageLayout::eReadOnlyOptimalKHR);
/// @brief Bind an image to the command buffer
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the image to
/// @param image The ImageAttachment to bind
/// @param layout layout of the image when the affected draws execute
CommandBuffer& bind_image(unsigned set, unsigned binding, const ImageAttachment& image, ImageLayout layout = ImageLayout::eReadOnlyOptimalKHR);
/// @brief Bind an image to the command buffer from a Resource
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the image to
/// @param resource_name The Name of the Resource to be bound
CommandBuffer& bind_image(unsigned set, unsigned binding, Name resource_name);
/// @brief Bind a sampler to the command buffer from a Resource
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the sampler to
/// @param sampler_create_info Parameters of the sampler
CommandBuffer& bind_sampler(unsigned set, unsigned binding, SamplerCreateInfo sampler_create_info);
/// @brief Allocate some CPUtoGPU memory and bind it as a buffer. Return a pointer to the mapped memory.
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the buffer to
/// @param size Amount of memory to allocate
/// @return pointer to the mapped host-visible memory. Null pointer if the command buffer has errored out previously or the allocation failed
void* _map_scratch_buffer(unsigned set, unsigned binding, size_t size);
/// @brief Allocate some typed CPUtoGPU memory and bind it as a buffer. Return a pointer to the mapped memory.
/// @tparam T Type of the uniform to write
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the buffer to
/// @return pointer to the mapped host-visible memory. Null pointer if the command buffer has errored out previously or the allocation failed
template<class T>
T* map_scratch_buffer(unsigned set, unsigned binding);
/// @brief Bind a sampler to the command buffer from a Resource
/// @param set The set bind index to be used
/// @param binding The descriptor binding to bind the sampler to
/// @param sampler_create_info Parameters of the sampler
CommandBuffer& bind_acceleration_structure(unsigned set, unsigned binding, VkAccelerationStructureKHR tlas);
/// @brief Issue a non-indexed draw
/// @param vertex_count Number of vertices to draw
/// @param instance_count Number of instances to draw
/// @param first_vertex Index of the first vertex to draw
/// @param first_instance Index of the first instance to draw
CommandBuffer& draw(size_t vertex_count, size_t instance_count, size_t first_vertex, size_t first_instance);
/// @brief Isuse an indexed draw
/// @param index_count Number of vertices to draw
/// @param instance_count Number of instances to draw
/// @param first_index Index of the first index in the index buffer
/// @param vertex_offset value added to the vertex index before indexing into the vertex buffer(s)
/// @param first_instance Index of the first instance to draw
CommandBuffer& draw_indexed(size_t index_count, size_t instance_count, size_t first_index, int32_t vertex_offset, size_t first_instance);
/// @brief Issue an indirect indexed draw
/// @param command_count Number of indirect commands to be used
/// @param indirect_buffer Buffer of indirect commands
CommandBuffer& draw_indexed_indirect(size_t command_count, const Buffer& indirect_buffer);
/// @brief Issue an indirect indexed draw
/// @param command_count Number of indirect commands to be used
/// @param indirect_resource_name The Name of the Resource to use as indirect buffer
CommandBuffer& draw_indexed_indirect(size_t command_count, Name indirect_resource_name);
/// @brief Issue an indirect indexed draw
/// @param commands Indirect commands to be uploaded and used for this draw
CommandBuffer& draw_indexed_indirect(std::span<DrawIndexedIndirectCommand> commands);
/// @brief Issue an indirect indexed draw with count
/// @param max_command_count Upper limit of commands that can be drawn
/// @param indirect_buffer Buffer of indirect commands
/// @param count_buffer Buffer of command count
CommandBuffer& draw_indexed_indirect_count(size_t max_command_count, const Buffer& indirect_buffer, const Buffer& count_buffer);
/// @brief Issue an indirect indexed draw with count
/// @param max_command_count Upper limit of commands that can be drawn
/// @param indirect_resource_name The Name of the Resource to use as indirect buffer
/// @param count_resource_name The Name of the Resource to use as count buffer
CommandBuffer& draw_indexed_indirect_count(size_t max_command_count, Name indirect_resource_name, Name count_resource_name);
/// @brief Issue a compute dispatch
/// @param group_count_x Number of groups on the x-axis
/// @param group_count_y Number of groups on the y-axis
/// @param group_count_z Number of groups on the z-axis
CommandBuffer& dispatch(size_t group_count_x, size_t group_count_y = 1, size_t group_count_z = 1);
/// @brief Perform a dispatch while specifying the minimum invocation count
/// Actual invocation count will be rounded up to be a multiple of local_size_{x,y,z}
/// @param invocation_count_x Number of invocations on the x-axis
/// @param invocation_count_y Number of invocations on the y-axis
/// @param invocation_count_z Number of invocations on the z-axis
CommandBuffer& dispatch_invocations(size_t invocation_count_x, size_t invocation_count_y = 1, size_t invocation_count_z = 1);
/// @brief Perform a dispatch with invocations per pixel
/// The number of invocations per pixel can be scaled in all dimensions
/// If the scale is == 1, then 1 invocations will be dispatched per pixel
/// If the scale is larger than 1, then more invocations will be dispatched than pixels
/// If the scale is smaller than 1, then fewer invocations will be dispatched than pixels
/// Actual invocation count will be rounded up to be a multiple of local_size_{x,y,z} after scaling
/// Width corresponds to the x-axis, height to the y-axis and depth to the z-axis
/// @param name Name of the Image Resource to use for extents
/// @param invocations_per_pixel_scale_x Invocation count scale in x-axis
/// @param invocations_per_pixel_scale_y Invocation count scale in y-axis
/// @param invocations_per_pixel_scale_z Invocation count scale in z-axis
CommandBuffer& dispatch_invocations_per_pixel(Name name,
float invocations_per_pixel_scale_x = 1.f,
float invocations_per_pixel_scale_y = 1.f,
float invocations_per_pixel_scale_z = 1.f);
/// @brief Perform a dispatch with invocations per pixel
/// The number of invocations per pixel can be scaled in all dimensions
/// If the scale is == 1, then 1 invocations will be dispatched per pixel
/// If the scale is larger than 1, then more invocations will be dispatched than pixels
/// If the scale is smaller than 1, then fewer invocations will be dispatched than pixels
/// Actual invocation count will be rounded up to be a multiple of local_size_{x,y,z} after scaling
/// Width corresponds to the x-axis, height to the y-axis and depth to the z-axis
/// @param ia ImageAttachment to use for extents
/// @param invocations_per_pixel_scale_x Invocation count scale in x-axis
/// @param invocations_per_pixel_scale_y Invocation count scale in y-axis
/// @param invocations_per_pixel_scale_z Invocation count scale in z-axis
CommandBuffer& dispatch_invocations_per_pixel(ImageAttachment& ia,
float invocations_per_pixel_scale_x = 1.f,
float invocations_per_pixel_scale_y = 1.f,
float invocations_per_pixel_scale_z = 1.f);
/// @brief Perform a dispatch with invocations per buffer element
/// Actual invocation count will be rounded up to be a multiple of local_size_{x,y,z}
/// The number of invocations per element can be scaled
/// If the scale is == 1, then 1 invocations will be dispatched per element
/// If the scale is larger than 1, then more invocations will be dispatched than element
/// If the scale is smaller than 1, then fewer invocations will be dispatched than element
/// The dispatch will be sized only on the x-axis
/// @param name Name of the Buffer Resource to use for calculating element count
/// @param element_size Size of one element
/// @param invocations_per_element_scale Invocation count scale
CommandBuffer& dispatch_invocations_per_element(Name name, size_t element_size, float invocations_per_element_scale = 1.f);
/// @brief Perform a dispatch with invocations per buffer element
/// Actual invocation count will be rounded up to be a multiple of local_size_{x,y,z}
/// The number of invocations per element can be scaled
/// If the scale is == 1, then 1 invocations will be dispatched per element
/// If the scale is larger than 1, then more invocations will be dispatched than element
/// If the scale is smaller than 1, then fewer invocations will be dispatched than element
/// The dispatch will be sized only on the x-axis
/// @param buffer Buffer to use for calculating element count
/// @param element_size Size of one element
/// @param invocations_per_element_scale Invocation count scale
CommandBuffer& dispatch_invocations_per_element(Buffer& buffer, size_t element_size, float invocations_per_element_scale = 1.f);
/// @brief Issue an indirect compute dispatch
/// @param indirect_buffer Buffer of workgroup counts
CommandBuffer& dispatch_indirect(const Buffer& indirect_buffer);
/// @brief Issue an indirect compute dispatch
/// @param indirect_resource_name The Name of the Resource to use as indirect buffer
CommandBuffer& dispatch_indirect(Name indirect_resource_name);
/// @brief Perform ray trace query with a ray tracing pipeline
/// @param width width of the ray trace query dimensions
/// @param height height of the ray trace query dimensions
/// @param depth depth of the ray trace query dimensions
CommandBuffer& trace_rays(size_t width, size_t height, size_t depth);
/// @brief Build acceleration structures
CommandBuffer& build_acceleration_structures(uint32_t info_count,
const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos);
// commands for render pass-less command buffers
/// @brief Clear an image
/// @param src the Name of the Resource to be cleared
/// @param clear_value value to clear with
CommandBuffer& clear_image(Name src, Clear clear_value);
/// @brief Resolve an image
/// @param src the Name of the multisampled Resource
/// @param dst the Name of the singlesampled Resource
CommandBuffer& resolve_image(Name src, Name dst);
/// @brief Perform an image blit
/// @param src the Name of the source Resource
/// @param dst the Name of the destination Resource
/// @param region parameters of the blit
/// @param filter Filter to use if the src and dst extents differ
CommandBuffer& blit_image(Name src, Name dst, ImageBlit region, Filter filter);
/// @brief Copy a buffer resource into an image resource
/// @param src the Name of the source Resource
/// @param dst the Name of the destination Resource
/// @param copy_params parameters of the copy
CommandBuffer& copy_buffer_to_image(Name src, Name dst, BufferImageCopy copy_params);
/// @brief Copy an image resource into a buffer resource
/// @param src the Name of the source Resource
/// @param dst the Name of the destination Resource
/// @param copy_params parameters of the copy
CommandBuffer& copy_image_to_buffer(Name src, Name dst, BufferImageCopy copy_params);
/// @brief Copy between two buffer resource
/// @param src the Name of the source Resource
/// @param dst the Name of the destination Resource
/// @param size number of bytes to copy (VK_WHOLE_SIZE to copy the entire "src" buffer)
CommandBuffer& copy_buffer(Name src, Name dst, size_t size);
/// @brief Copy between two Buffers
/// @param src the source Buffer
/// @param dst the destination Buffer
/// @param size number of bytes to copy (VK_WHOLE_SIZE to copy the entire "src" buffer)
CommandBuffer& copy_buffer(const Buffer& src, const Buffer& dst, size_t size);
/// @brief Fill a buffer with a fixed value
/// @param dst the Name of the destination Resource
/// @param size number of bytes to fill
/// @param data the 4 byte value to fill with
CommandBuffer& fill_buffer(Name dst, size_t size, uint32_t data);
/// @brief Fill a buffer with a fixed value
/// @param dst the destination Buffer
/// @param size number of bytes to fill
/// @param data the 4 byte value to fill with
CommandBuffer& fill_buffer(const Buffer& dst, size_t size, uint32_t data);
/// @brief Fill a buffer with a host values
/// @param dst the Name of the destination Resource
/// @param size number of bytes to fill
/// @param data pointer to host values
CommandBuffer& update_buffer(Name dst, size_t size, void* data);
/// @brief Fill a buffer with a host values
/// @param dst the destination Buffer
/// @param size number of bytes to fill
/// @param data pointer to host values
CommandBuffer& update_buffer(const Buffer& dst, size_t size, void* data);
// explicit synchronisation
/// @brief Issue a memory barrier
/// @param src_access previous Access
/// @param dst_access subsequent Access
CommandBuffer& memory_barrier(Access src_access, Access dst_access);
/// @brief Issue an image barrier for an image resource
/// @param resource_name the Name of the image Resource
/// @param src_access previous Access
/// @param dst_access subsequent Access
/// @param base_level base mip level affected by the barrier
/// @param level_count number of mip levels affected by the barrier
CommandBuffer&
image_barrier(Name resource_name, Access src_access, Access dst_access, uint32_t base_level = 0, uint32_t level_count = VK_REMAINING_MIP_LEVELS);
// queries
/// @brief Write a timestamp to given Query
/// @param query the Query to hold the result
/// @param stage the pipeline stage where the timestamp should latch the earliest
CommandBuffer& write_timestamp(Query query, PipelineStageFlagBits stage = PipelineStageFlagBits::eBottomOfPipe);
// error handling
[[nodiscard]] Result<void> result();
// explicit command buffer access
/// @brief Bind all pending compute state and return a raw VkCommandBuffer for direct access
[[nodiscard]] VkCommandBuffer bind_compute_state();
/// @brief Bind all pending graphics state and return a raw VkCommandBuffer for direct access
[[nodiscard]] VkCommandBuffer bind_graphics_state();
/// @brief Bind all pending ray tracing state and return a raw VkCommandBuffer for direct access
[[nodiscard]] VkCommandBuffer bind_ray_tracing_state();
protected:
enum class PipeType { eGraphics, eCompute, eRayTracing };
[[nodiscard]] bool _bind_state(PipeType pipe_type);
[[nodiscard]] bool _bind_compute_pipeline_state();
[[nodiscard]] bool _bind_graphics_pipeline_state();
[[nodiscard]] bool _bind_ray_tracing_pipeline_state();
CommandBuffer& specialize_constants(uint32_t constant_id, void* data, size_t size);
};
template<class T>
inline CommandBuffer& CommandBuffer::push_constants(ShaderStageFlags stages, size_t offset, std::span<T> span) {
return push_constants(stages, offset, (void*)span.data(), sizeof(T) * span.size());
}
template<class T>
inline CommandBuffer& CommandBuffer::push_constants(ShaderStageFlags stages, size_t offset, T value) {
return push_constants(stages, offset, (void*)&value, sizeof(T));
}
inline CommandBuffer& CommandBuffer::specialize_constants(uint32_t constant_id, bool value) {
return specialize_constants(constant_id, (uint32_t)value);
}
inline CommandBuffer& CommandBuffer::specialize_constants(uint32_t constant_id, uint32_t value) {
return specialize_constants(constant_id, (void*)&value, sizeof(uint32_t));
}
inline CommandBuffer& CommandBuffer::specialize_constants(uint32_t constant_id, int32_t value) {
return specialize_constants(constant_id, (void*)&value, sizeof(int32_t));
}
inline CommandBuffer& CommandBuffer::specialize_constants(uint32_t constant_id, float value) {
return specialize_constants(constant_id, (void*)&value, sizeof(float));
}
inline CommandBuffer& CommandBuffer::specialize_constants(uint32_t constant_id, double value) {
return specialize_constants(constant_id, (void*)&value, sizeof(double));
}
template<class T>
inline T* CommandBuffer::map_scratch_buffer(unsigned set, unsigned binding) {
return static_cast<T*>(_map_scratch_buffer(set, binding, sizeof(T)));
}
/// @brief RAII utility for creating a timed scope on the GPU
struct TimedScope {
TimedScope(CommandBuffer& cbuf, Query a, Query b) : cbuf(cbuf), a(a), b(b) {
cbuf.write_timestamp(a, PipelineStageFlagBits::eBottomOfPipe);
}
~TimedScope() {
cbuf.write_timestamp(b, PipelineStageFlagBits::eBottomOfPipe);
}
CommandBuffer& cbuf;
Query a;
Query b;
};
} // namespace vuk
<file_sep>#pragma once
#include <source_location>
namespace vuk {
/// @cond INTERNAL
#ifndef __cpp_consteval
struct source_location {
uint_least32_t line_{};
uint_least32_t column_{};
const char* file = "";
const char* function = "";
[[nodiscard]] constexpr source_location() noexcept = default;
[[nodiscard]] static source_location current(const uint_least32_t line_ = __builtin_LINE(),
const uint_least32_t column_ = __builtin_COLUMN(),
const char* const file_ = __builtin_FILE(),
const char* const function_ = __builtin_FUNCTION()) noexcept {
source_location result;
result.line_ = line_;
result.column_ = column_;
result.file = file_;
result.function = function_;
return result;
}
[[nodiscard]] constexpr uint_least32_t line() const noexcept {
return line_;
}
[[nodiscard]] constexpr uint_least32_t column() const noexcept {
return line_;
}
[[nodiscard]] constexpr const char* file_name() const noexcept {
return file;
}
[[nodiscard]] constexpr const char* function_name() const noexcept {
return function;
}
};
struct SourceLocationAtFrame {
source_location location;
uint64_t absolute_frame;
};
#else
struct SourceLocationAtFrame {
std::source_location location;
uint64_t absolute_frame;
};
using source_location = std::source_location;
#endif
} // namespace vuk
/// @cond INTERNAL
#define VUK_HERE_AND_NOW() \
SourceLocationAtFrame { \
vuk::source_location::current(), (uint64_t)-1LL \
}
/// @endcond<file_sep>#pragma once
#include <array>
#include <optional>
#include <span>
#include <string_view>
#include <vector>
#include "vuk/Allocator.hpp"
#include "vuk/Buffer.hpp"
#include "vuk/Image.hpp"
#include "vuk/Swapchain.hpp"
#include "vuk_fwd.hpp"
#include "vuk/SourceLocation.hpp"
namespace std {
class mutex;
class recursive_mutex;
} // namespace std
namespace vuk {
/// @brief Parameters used for creating a Context
struct ContextCreateParameters {
/// @brief Vulkan instance
VkInstance instance;
/// @brief Vulkan device
VkDevice device;
/// @brief Vulkan physical device
VkPhysicalDevice physical_device;
/// @brief Optional graphics queue
VkQueue graphics_queue = VK_NULL_HANDLE;
/// @brief Optional graphics queue family index
uint32_t graphics_queue_family_index = VK_QUEUE_FAMILY_IGNORED;
/// @brief Optional compute queue
VkQueue compute_queue = VK_NULL_HANDLE;
/// @brief Optional compute queue family index
uint32_t compute_queue_family_index = VK_QUEUE_FAMILY_IGNORED;
/// @brief Optional transfer queue
VkQueue transfer_queue = VK_NULL_HANDLE;
/// @brief Optional transfer queue family index
uint32_t transfer_queue_family_index = VK_QUEUE_FAMILY_IGNORED;
#define VUK_X(name) PFN_##name name = nullptr;
#define VUK_Y(name) PFN_##name name = nullptr;
/// @brief User provided function pointers. If you want dynamic loading, you must set vkGetInstanceProcAddr & vkGetDeviceProcAddr
struct FunctionPointers {
PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = nullptr;
PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr = nullptr;
#include "vuk/VulkanPFNRequired.hpp"
#include "vuk/VulkanPFNOptional.hpp"
} pointers;
#undef VUK_X
#undef VUK_Y
/// @brief Allow vuk to load missing required and optional function pointers dynamically
/// If this is false, then you must fill in all required function pointers
bool allow_dynamic_loading_of_vk_function_pointers = true;
};
/// @brief Abstraction of a device queue in Vulkan
struct Queue {
Queue(PFN_vkQueueSubmit fn1, PFN_vkQueueSubmit2KHR fn2, VkQueue queue, uint32_t queue_family_index, TimelineSemaphore ts);
~Queue();
Queue(const Queue&) = delete;
Queue& operator=(const Queue&) = delete;
Queue(Queue&&) noexcept;
Queue& operator=(Queue&&) noexcept;
TimelineSemaphore& get_submit_sync();
std::recursive_mutex& get_queue_lock();
Result<void> submit(std::span<VkSubmitInfo> submit_infos, VkFence fence);
Result<void> submit(std::span<VkSubmitInfo2KHR> submit_infos, VkFence fence);
struct QueueImpl* impl;
};
class Context : public ContextCreateParameters::FunctionPointers {
public:
/// @brief Create a new Context
/// @param params Vulkan parameters initialized beforehand
Context(ContextCreateParameters params);
~Context();
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
Context(Context&&) noexcept;
Context& operator=(Context&&) noexcept;
// Vulkan instance, device and queues
VkInstance instance;
VkDevice device;
VkPhysicalDevice physical_device;
uint32_t graphics_queue_family_index;
uint32_t compute_queue_family_index;
uint32_t transfer_queue_family_index;
std::optional<Queue> dedicated_graphics_queue;
std::optional<Queue> dedicated_compute_queue;
std::optional<Queue> dedicated_transfer_queue;
Queue* graphics_queue = nullptr;
Queue* compute_queue = nullptr;
Queue* transfer_queue = nullptr;
// Vulkan properties
VkPhysicalDeviceProperties physical_device_properties;
VkPhysicalDeviceRayTracingPipelinePropertiesKHR rt_properties{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR };
VkPhysicalDeviceAccelerationStructurePropertiesKHR as_properties{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_PROPERTIES_KHR };
size_t min_buffer_alignment;
// Debug functions
/// @brief If debug utils is available and debug names & markers are supported
bool debug_enabled() const;
/// @brief Set debug name for Texture
void set_name(const Texture&, Name name);
/// @brief Set debug name for object
template<class T>
void set_name(const T& t, Name name);
/// @brief Add debug region to command buffer
/// @param name Name of the region
/// @param color Display color of the region
void begin_region(const VkCommandBuffer&, Name name, std::array<float, 4> color = { 1, 1, 1, 1 });
/// @brief End debug region in command buffer
void end_region(const VkCommandBuffer&);
// Pipeline management
/// Internal pipeline cache to use
VkPipelineCache vk_pipeline_cache = VK_NULL_HANDLE;
/// @brief Create a pipeline base that can be recalled by name
void create_named_pipeline(Name name, PipelineBaseCreateInfo pbci);
/// @brief Recall name pipeline base
PipelineBaseInfo* get_named_pipeline(Name name);
PipelineBaseInfo* get_pipeline(const PipelineBaseCreateInfo& pbci);
/// @brief Reflect given pipeline base
Program get_pipeline_reflection_info(const PipelineBaseCreateInfo& pbci);
/// @brief Explicitly compile give ShaderSource into a ShaderModule
ShaderModule compile_shader(ShaderSource source, std::string path);
/// @brief Load a Vulkan pipeline cache
bool load_pipeline_cache(std::span<std::byte> data);
/// @brief Retrieve the current Vulkan pipeline cache
std::vector<std::byte> save_pipeline_cache();
// Allocator support
/// @brief Return an allocator over the direct resource - resources will be allocated from the Vulkan runtime
/// @return The resource
DeviceVkResource& get_vk_resource();
Texture allocate_texture(Allocator& allocator, ImageCreateInfo ici, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
// Swapchain management
/// @brief Add a swapchain to be managed by the Context
/// @return Reference to the new swapchain that can be used during presentation
SwapchainRef add_swapchain(Swapchain);
/// @brief Remove a swapchain that is managed by the Context
/// the swapchain is not destroyed
void remove_swapchain(SwapchainRef);
// Frame management
/// @brief Retrieve the current frame count
uint64_t get_frame_count() const;
/// @brief Advance internal counter used for caching and garbage collect caches
void next_frame();
/// @brief Wait for the device to become idle. Useful for only a few synchronisation events, like resizing or shutting down.
Result<void> wait_idle();
Result<void> submit_graphics(std::span<VkSubmitInfo>, VkFence);
Result<void> submit_transfer(std::span<VkSubmitInfo>, VkFence);
Result<void> submit_graphics(std::span<VkSubmitInfo2KHR>);
Result<void> submit_transfer(std::span<VkSubmitInfo2KHR>);
Result<void> wait_for_domains(std::span<std::pair<DomainFlags, uint64_t>> queue_waits);
// Query functionality
/// @brief Create a timestamp query to record timing information
Query create_timestamp_query();
/// @brief Checks if a timestamp query is available
/// @param q the Query to check
/// @return true if the timestamp is available
bool is_timestamp_available(Query q);
/// @brief Retrieve a timestamp if available
/// @param q the Query to check
/// @return the timestamp value if it was available, null optional otherwise
std::optional<uint64_t> retrieve_timestamp(Query q);
/// @brief Retrive a duration if available
/// @param q1 the start timestamp Query
/// @param q2 the end timestamp Query
/// @return the duration in seconds if both timestamps were available, null optional otherwise
std::optional<double> retrieve_duration(Query q1, Query q2);
/// @brief Retrieve results from `TimestampQueryPool`s and make them available to retrieve_timestamp and retrieve_duration
Result<void> make_timestamp_results_available(std::span<const TimestampQueryPool> pools);
// Caches
/// @brief Acquire a cached sampler
Sampler acquire_sampler(const SamplerCreateInfo& cu, uint64_t absolute_frame);
/// @brief Acquire a cached descriptor pool
struct DescriptorPool& acquire_descriptor_pool(const struct DescriptorSetLayoutAllocInfo& dslai, uint64_t absolute_frame);
/// @brief Force collection of caches
void collect(uint64_t frame);
// Persistent descriptor sets
Unique<PersistentDescriptorSet> create_persistent_descriptorset(Allocator& allocator, struct DescriptorSetLayoutCreateInfo dslci, unsigned num_descriptors);
Unique<PersistentDescriptorSet> create_persistent_descriptorset(Allocator& allocator, const PipelineBaseInfo& base, unsigned set, unsigned num_descriptors);
Unique<PersistentDescriptorSet> create_persistent_descriptorset(Allocator& allocator, const PersistentDescriptorSetCreateInfo&);
// Misc.
/// @brief Descriptor set strategy to use by default, can be overridden on the CommandBuffer
DescriptorSetStrategyFlags default_descriptor_set_strategy = {};
/// @brief Retrieve a unique uint64_t value
uint64_t get_unique_handle_id();
/// @brief Create a wrapped handle type (eg. a ImageView) from an externally sourced Vulkan handle
/// @tparam T Vulkan handle type to wrap
/// @param payload Vulkan handle to wrap
/// @return The wrapped handle.
template<class T>
Handle<T> wrap(T payload);
Queue& domain_to_queue(DomainFlags) const;
uint32_t domain_to_queue_index(DomainFlags) const;
uint32_t domain_to_queue_family_index(DomainFlags) const;
private:
struct ContextImpl* impl;
friend struct ContextImpl;
// internal functions
void destroy(const struct DescriptorPool& dp);
void destroy(const ShaderModule& sm);
void destroy(const DescriptorSetLayoutAllocInfo& ds);
void destroy(const VkPipelineLayout& pl);
void destroy(const DescriptorSet&);
void destroy(const Sampler& sa);
void destroy(const PipelineBaseInfo& pbi);
ShaderModule create(const struct ShaderModuleCreateInfo& cinfo);
PipelineBaseInfo create(const struct PipelineBaseCreateInfo& cinfo);
VkPipelineLayout create(const struct PipelineLayoutCreateInfo& cinfo);
DescriptorSetLayoutAllocInfo create(const struct DescriptorSetLayoutCreateInfo& cinfo);
DescriptorPool create(const struct DescriptorSetLayoutAllocInfo& cinfo);
Sampler create(const struct SamplerCreateInfo& cinfo);
};
template<class T>
Handle<T> Context::wrap(T payload) {
return { { get_unique_handle_id() }, payload };
}
template<class T>
void Context::set_name(const T& t, Name name) {
if (!debug_enabled())
return;
VkDebugUtilsObjectNameInfoEXT info = { .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT };
info.pObjectName = name.c_str();
if constexpr (std::is_same_v<T, VkImage>) {
info.objectType = VK_OBJECT_TYPE_IMAGE;
} else if constexpr (std::is_same_v<T, VkImageView>) {
info.objectType = VK_OBJECT_TYPE_IMAGE_VIEW;
} else if constexpr (std::is_same_v<T, VkShaderModule>) {
info.objectType = VK_OBJECT_TYPE_SHADER_MODULE;
} else if constexpr (std::is_same_v<T, VkPipeline>) {
info.objectType = VK_OBJECT_TYPE_PIPELINE;
} else if constexpr (std::is_same_v<T, VkBuffer>) {
info.objectType = VK_OBJECT_TYPE_BUFFER;
}
info.objectHandle = reinterpret_cast<uint64_t>(t);
this->vkSetDebugUtilsObjectNameEXT(device, &info);
}
} // namespace vuk
#include "vuk/Exception.hpp"
// utility functions
namespace vuk {
struct ExecutableRenderGraph;
struct SingleSwapchainRenderBundle {
SwapchainRef swapchain;
uint32_t image_index;
VkSemaphore present_ready;
VkSemaphore render_complete;
VkResult acquire_result;
};
/// @brief Compile & link given `RenderGraph`s, then execute them into API VkCommandBuffers, then submit them to queues
/// @param allocator Allocator to use for submission resources
/// @param rendergraphs `RenderGraph`s for compilation
Result<void> link_execute_submit(Allocator& allocator, Compiler& compiler, std::span<std::shared_ptr<struct RenderGraph>> rendergraphs);
/// @brief Execute given `ExecutableRenderGraph`s into API VkCommandBuffers, then submit them to queues
/// @param allocator Allocator to use for submission resources
/// @param executable_rendergraphs `ExecutableRenderGraph`s for execution
/// @param swapchains_with_indexes Swapchains references by the rendergraphs
/// @param present_rdy Semaphore used to gate device-side execution
/// @param render_complete Semaphore used to gate presentation
Result<void> execute_submit(Allocator& allocator,
std::span<std::pair<Allocator*, ExecutableRenderGraph*>> executable_rendergraphs,
std::vector<std::pair<SwapchainRef, size_t>> swapchains_with_indexes,
VkSemaphore present_rdy,
VkSemaphore render_complete);
/// @brief Execute given `ExecutableRenderGraph` into API VkCommandBuffers, then submit them to queues, presenting to a single swapchain
/// @param allocator Allocator to use for submission resources
/// @param executable_rendergraph `ExecutableRenderGraph`s for execution
/// @param swapchain Swapchain referenced by the rendergraph
Result<VkResult> execute_submit_and_present_to_one(Allocator& allocator, ExecutableRenderGraph&& executable_rendergraph, SwapchainRef swapchain);
/// @brief Execute given `ExecutableRenderGraph` into API VkCommandBuffers, then submit them to queues, then blocking-wait for the submission to complete
/// @param allocator Allocator to use for submission resources
/// @param executable_rendergraph `ExecutableRenderGraph`s for execution
Result<void> execute_submit_and_wait(Allocator& allocator, ExecutableRenderGraph&& executable_rendergraph);
struct RenderGraphCompileOptions;
Result<SingleSwapchainRenderBundle> acquire_one(Allocator& allocator, SwapchainRef swapchain);
Result<SingleSwapchainRenderBundle> acquire_one(Context& ctx, SwapchainRef swapchain, VkSemaphore present_ready, VkSemaphore render_complete);
Result<SingleSwapchainRenderBundle> execute_submit(Allocator& allocator, ExecutableRenderGraph&& rg, SingleSwapchainRenderBundle&& bundle);
Result<VkResult> present_to_one(Context& ctx, SingleSwapchainRenderBundle&& bundle);
Result<VkResult> present(Allocator& allocator, Compiler& compiler, SwapchainRef swapchain, Future&& future, RenderGraphCompileOptions = {});
struct SampledImage make_sampled_image(ImageView iv, SamplerCreateInfo sci);
struct SampledImage make_sampled_image(struct NameReference n, SamplerCreateInfo sci);
struct SampledImage make_sampled_image(struct NameReference n, ImageViewCreateInfo ivci, SamplerCreateInfo sci);
} // namespace vuk<file_sep>#pragma once
#include "../src/CreateInfo.hpp"
#include "vuk/Config.hpp"
#include "vuk/vuk_fwd.hpp"
#include <cstring>
#include <string>
#include <vector>
namespace spirv_cross {
struct SPIRType;
class Compiler;
}; // namespace spirv_cross
namespace vuk {
enum class ShaderSourceLanguage { eGlsl, eHlsl, eSpirv };
/// @brief Specifies the HLSL Shader Stage for a given HLSL shader.
enum class HlslShaderStage {
/// @brief Will infer the Shader Stage from the filename.
eInferred,
eVertex,
ePixel,
eCompute,
eGeometry,
eMesh,
eHull,
eDomain,
eAmplification
};
/// @brief Wrapper over either a GLSL, HLSL, or SPIR-V source
struct ShaderSource {
ShaderSource() = default;
ShaderSource(const ShaderSource& o) noexcept {
data = o.data;
if (!data.empty()) {
data_ptr = data.data();
} else {
data_ptr = o.data_ptr;
}
size = o.size;
language = o.language;
hlsl_stage = o.hlsl_stage;
}
ShaderSource& operator=(const ShaderSource& o) noexcept {
data = o.data;
if (!data.empty()) {
data_ptr = data.data();
} else {
data_ptr = o.data_ptr;
}
language = o.language;
size = o.size;
hlsl_stage = o.hlsl_stage;
return *this;
}
ShaderSource(ShaderSource&& o) noexcept {
data = std::move(o.data);
if (!data.empty()) {
data_ptr = data.data();
} else {
data_ptr = o.data_ptr;
}
size = o.size;
language = o.language;
hlsl_stage = o.hlsl_stage;
}
ShaderSource& operator=(ShaderSource&& o) noexcept {
data = std::move(o.data);
if (!data.empty()) {
data_ptr = data.data();
} else {
data_ptr = o.data_ptr;
}
size = o.size;
language = o.language;
hlsl_stage = o.hlsl_stage;
return *this;
}
#if VUK_USE_SHADERC
static ShaderSource glsl(std::string_view source) {
ShaderSource shader;
shader.data.resize(idivceil(source.size() + 1, sizeof(uint32_t)));
memcpy(shader.data.data(), source.data(), source.size() * sizeof(std::string_view::value_type));
shader.data_ptr = shader.data.data();
shader.size = shader.data.size();
shader.language = ShaderSourceLanguage::eGlsl;
return shader;
}
#endif
#if VUK_USE_DXC
static ShaderSource hlsl(std::string_view source, HlslShaderStage stage = HlslShaderStage::eInferred) {
ShaderSource shader;
shader.data.resize(idivceil(source.size() + 1, sizeof(uint32_t)));
memcpy(shader.data.data(), source.data(), source.size() * sizeof(std::string_view::value_type));
shader.data_ptr = shader.data.data();
shader.language = ShaderSourceLanguage::eHlsl;
shader.hlsl_stage = HlslShaderStage::eInferred;
return shader;
}
#endif
static ShaderSource spirv(std::vector<uint32_t> source) {
ShaderSource shader;
shader.data = std::move(source);
shader.data_ptr = shader.data.data();
shader.size = shader.data.size();
shader.language = ShaderSourceLanguage::eSpirv;
return shader;
}
static ShaderSource spirv(const uint32_t* source, size_t size) {
ShaderSource shader;
shader.data_ptr = source;
shader.size = size;
shader.language = ShaderSourceLanguage::eSpirv;
return shader;
}
const char* as_c_str() const {
return reinterpret_cast<const char*>(data_ptr);
}
const uint32_t* as_spirv() const {
return data_ptr;
}
const uint32_t* data_ptr = nullptr;
size_t size = 0;
std::vector<uint32_t> data;
ShaderSourceLanguage language;
HlslShaderStage hlsl_stage;
};
inline bool operator==(const ShaderSource& a, const ShaderSource& b) noexcept {
bool basics = a.language == b.language && a.size == b.size;
if (!basics) {
return false;
}
if (a.data_ptr == b.data_ptr) {
return true;
}
return memcmp(a.data_ptr, b.data_ptr, a.size) == 0;
}
struct ShaderModuleCreateInfo {
ShaderSource source;
std::string filename;
std::vector<std::pair<std::string, std::string>> defines;
bool operator==(const ShaderModuleCreateInfo& o) const noexcept {
return source == o.source && defines == o.defines;
}
};
} // namespace vuk
<file_sep>#pragma once
#include "vuk/Config.hpp"
#include <array>
namespace vuk {
enum class PrimitiveTopology {
ePointList = VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
eLineList = VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
eLineStrip = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
eTriangleList = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
eTriangleStrip = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
eTriangleFan = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN,
eLineListWithAdjacency = VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
eLineStripWithAdjacency = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
eTriangleListWithAdjacency = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
eTriangleStripWithAdjacency = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
ePatchList = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST
};
enum class BlendFactor {
eZero = VK_BLEND_FACTOR_ZERO,
eOne = VK_BLEND_FACTOR_ONE,
eSrcColor = VK_BLEND_FACTOR_SRC_COLOR,
eOneMinusSrcColor = VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR,
eDstColor = VK_BLEND_FACTOR_DST_COLOR,
eOneMinusDstColor = VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR,
eSrcAlpha = VK_BLEND_FACTOR_SRC_ALPHA,
eOneMinusSrcAlpha = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
eDstAlpha = VK_BLEND_FACTOR_DST_ALPHA,
eOneMinusDstAlpha = VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA,
eConstantColor = VK_BLEND_FACTOR_CONSTANT_COLOR,
eOneMinusConstantColor = VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR,
eConstantAlpha = VK_BLEND_FACTOR_CONSTANT_ALPHA,
eOneMinusConstantAlpha = VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA,
eSrcAlphaSaturate = VK_BLEND_FACTOR_SRC_ALPHA_SATURATE,
eSrc1Color = VK_BLEND_FACTOR_SRC1_COLOR,
eOneMinusSrc1Color = VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR,
eSrc1Alpha = VK_BLEND_FACTOR_SRC1_ALPHA,
eOneMinusSrc1Alpha = VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA
};
enum class BlendOp {
eAdd = VK_BLEND_OP_ADD,
eSubtract = VK_BLEND_OP_SUBTRACT,
eReverseSubtract = VK_BLEND_OP_REVERSE_SUBTRACT,
eMin = VK_BLEND_OP_MIN,
eMax = VK_BLEND_OP_MAX,
/*eZeroEXT = VK_BLEND_OP_ZERO_EXT,
eSrcEXT = VK_BLEND_OP_SRC_EXT,
eDstEXT = VK_BLEND_OP_DST_EXT,
eSrcOverEXT = VK_BLEND_OP_SRC_OVER_EXT,
eDstOverEXT = VK_BLEND_OP_DST_OVER_EXT,
eSrcInEXT = VK_BLEND_OP_SRC_IN_EXT,
eDstInEXT = VK_BLEND_OP_DST_IN_EXT,
eSrcOutEXT = VK_BLEND_OP_SRC_OUT_EXT,
eDstOutEXT = VK_BLEND_OP_DST_OUT_EXT,
eSrcAtopEXT = VK_BLEND_OP_SRC_ATOP_EXT,
eDstAtopEXT = VK_BLEND_OP_DST_ATOP_EXT,
eXorEXT = VK_BLEND_OP_XOR_EXT,
eMultiplyEXT = VK_BLEND_OP_MULTIPLY_EXT,
eScreenEXT = VK_BLEND_OP_SCREEN_EXT,
eOverlayEXT = VK_BLEND_OP_OVERLAY_EXT,
eDarkenEXT = VK_BLEND_OP_DARKEN_EXT,
eLightenEXT = VK_BLEND_OP_LIGHTEN_EXT,
eColordodgeEXT = VK_BLEND_OP_COLORDODGE_EXT,
eColorburnEXT = VK_BLEND_OP_COLORBURN_EXT,
eHardlightEXT = VK_BLEND_OP_HARDLIGHT_EXT,
eSoftlightEXT = VK_BLEND_OP_SOFTLIGHT_EXT,
eDifferenceEXT = VK_BLEND_OP_DIFFERENCE_EXT,
eExclusionEXT = VK_BLEND_OP_EXCLUSION_EXT,
eInvertEXT = VK_BLEND_OP_INVERT_EXT,
eInvertRgbEXT = VK_BLEND_OP_INVERT_RGB_EXT,
eLineardodgeEXT = VK_BLEND_OP_LINEARDODGE_EXT,
eLinearburnEXT = VK_BLEND_OP_LINEARBURN_EXT,
eVividlightEXT = VK_BLEND_OP_VIVIDLIGHT_EXT,
eLinearlightEXT = VK_BLEND_OP_LINEARLIGHT_EXT,
ePinlightEXT = VK_BLEND_OP_PINLIGHT_EXT,
eHardmixEXT = VK_BLEND_OP_HARDMIX_EXT,
eHslHueEXT = VK_BLEND_OP_HSL_HUE_EXT,
eHslSaturationEXT = VK_BLEND_OP_HSL_SATURATION_EXT,
eHslColorEXT = VK_BLEND_OP_HSL_COLOR_EXT,
eHslLuminosityEXT = VK_BLEND_OP_HSL_LUMINOSITY_EXT,
ePlusEXT = VK_BLEND_OP_PLUS_EXT,
ePlusClampedEXT = VK_BLEND_OP_PLUS_CLAMPED_EXT,
ePlusClampedAlphaEXT = VK_BLEND_OP_PLUS_CLAMPED_ALPHA_EXT,
ePlusDarkerEXT = VK_BLEND_OP_PLUS_DARKER_EXT,
eMinusEXT = VK_BLEND_OP_MINUS_EXT,
eMinusClampedEXT = VK_BLEND_OP_MINUS_CLAMPED_EXT,
eContrastEXT = VK_BLEND_OP_CONTRAST_EXT,
eInvertOvgEXT = VK_BLEND_OP_INVERT_OVG_EXT,
eRedEXT = VK_BLEND_OP_RED_EXT,
eGreenEXT = VK_BLEND_OP_GREEN_EXT,
eBlueEXT = VK_BLEND_OP_BLUE_EXT*/
};
enum class BlendPreset { eOff, eAlphaBlend, ePremultipliedAlphaBlend };
enum class PolygonMode {
eFill = VK_POLYGON_MODE_FILL,
eLine = VK_POLYGON_MODE_LINE,
ePoint = VK_POLYGON_MODE_POINT,
// eFillRectangleNV = VK_POLYGON_MODE_FILL_RECTANGLE_NV
};
enum class CullModeFlagBits : VkCullModeFlags {
eNone = VK_CULL_MODE_NONE,
eFront = VK_CULL_MODE_FRONT_BIT,
eBack = VK_CULL_MODE_BACK_BIT,
eFrontAndBack = VK_CULL_MODE_FRONT_AND_BACK
};
enum class FrontFace { eCounterClockwise = VK_FRONT_FACE_COUNTER_CLOCKWISE, eClockwise = VK_FRONT_FACE_CLOCKWISE };
using CullModeFlags = Flags<CullModeFlagBits>;
struct PipelineRasterizationStateCreateInfo {
bool operator==(PipelineRasterizationStateCreateInfo const& rhs) const noexcept {
return (depthClampEnable == rhs.depthClampEnable) && (rasterizerDiscardEnable == rhs.rasterizerDiscardEnable) && (polygonMode == rhs.polygonMode) &&
(cullMode == rhs.cullMode) && (frontFace == rhs.frontFace) && (depthBiasEnable == rhs.depthBiasEnable) &&
(depthBiasConstantFactor == rhs.depthBiasConstantFactor) && (depthBiasClamp == rhs.depthBiasClamp) &&
(depthBiasSlopeFactor == rhs.depthBiasSlopeFactor) && (lineWidth == rhs.lineWidth);
}
bool operator!=(PipelineRasterizationStateCreateInfo const& rhs) const noexcept {
return !operator==(rhs);
}
Bool32 depthClampEnable = {};
Bool32 rasterizerDiscardEnable = {};
PolygonMode polygonMode = PolygonMode::eFill;
CullModeFlags cullMode = {};
FrontFace frontFace = FrontFace::eCounterClockwise;
Bool32 depthBiasEnable = {};
float depthBiasConstantFactor = {};
float depthBiasClamp = {};
float depthBiasSlopeFactor = {};
float lineWidth = {};
};
enum class ColorComponentFlagBits : VkColorComponentFlags {
eR = VK_COLOR_COMPONENT_R_BIT,
eG = VK_COLOR_COMPONENT_G_BIT,
eB = VK_COLOR_COMPONENT_B_BIT,
eA = VK_COLOR_COMPONENT_A_BIT
};
using ColorComponentFlags = Flags<ColorComponentFlagBits>;
inline constexpr ColorComponentFlags operator|(ColorComponentFlagBits bit0, ColorComponentFlagBits bit1) noexcept {
return (ColorComponentFlags)bit0 | bit1;
}
inline constexpr ColorComponentFlags operator&(ColorComponentFlagBits bit0, ColorComponentFlagBits bit1) noexcept {
return (ColorComponentFlags)bit0 & bit1;
}
inline constexpr ColorComponentFlags operator^(ColorComponentFlagBits bit0, ColorComponentFlagBits bit1) noexcept {
return (ColorComponentFlags)bit0 ^ bit1;
}
struct PipelineColorBlendAttachmentState {
bool operator==(PipelineColorBlendAttachmentState const& rhs) const noexcept {
return (blendEnable == rhs.blendEnable) && (srcColorBlendFactor == rhs.srcColorBlendFactor) && (dstColorBlendFactor == rhs.dstColorBlendFactor) &&
(colorBlendOp == rhs.colorBlendOp) && (srcAlphaBlendFactor == rhs.srcAlphaBlendFactor) && (dstAlphaBlendFactor == rhs.dstAlphaBlendFactor) &&
(alphaBlendOp == rhs.alphaBlendOp) && (colorWriteMask == rhs.colorWriteMask);
}
bool operator!=(PipelineColorBlendAttachmentState const& rhs) const noexcept {
return !operator==(rhs);
}
Bool32 blendEnable = {};
BlendFactor srcColorBlendFactor = BlendFactor::eZero;
BlendFactor dstColorBlendFactor = BlendFactor::eZero;
BlendOp colorBlendOp = BlendOp::eAdd;
BlendFactor srcAlphaBlendFactor = BlendFactor::eZero;
BlendFactor dstAlphaBlendFactor = BlendFactor::eZero;
BlendOp alphaBlendOp = BlendOp::eAdd;
ColorComponentFlags colorWriteMask =
vuk::ColorComponentFlagBits::eR | vuk::ColorComponentFlagBits::eG | vuk::ColorComponentFlagBits::eB | vuk::ColorComponentFlagBits::eA;
};
enum class LogicOp {
eClear = VK_LOGIC_OP_CLEAR,
eAnd = VK_LOGIC_OP_AND,
eAndReverse = VK_LOGIC_OP_AND_REVERSE,
eCopy = VK_LOGIC_OP_COPY,
eAndInverted = VK_LOGIC_OP_AND_INVERTED,
eNoOp = VK_LOGIC_OP_NO_OP,
eXor = VK_LOGIC_OP_XOR,
eOr = VK_LOGIC_OP_OR,
eNor = VK_LOGIC_OP_NOR,
eEquivalent = VK_LOGIC_OP_EQUIVALENT,
eInvert = VK_LOGIC_OP_INVERT,
eOrReverse = VK_LOGIC_OP_OR_REVERSE,
eCopyInverted = VK_LOGIC_OP_COPY_INVERTED,
eOrInverted = VK_LOGIC_OP_OR_INVERTED,
eNand = VK_LOGIC_OP_NAND,
eSet = VK_LOGIC_OP_SET
};
struct PipelineColorBlendStateCreateInfo {
bool operator==(PipelineColorBlendStateCreateInfo const& rhs) const noexcept {
return (logicOpEnable == rhs.logicOpEnable) && (logicOp == rhs.logicOp) && (attachmentCount == rhs.attachmentCount) &&
(pAttachments == rhs.pAttachments) && (blendConstants == rhs.blendConstants);
}
bool operator!=(PipelineColorBlendStateCreateInfo const& rhs) const noexcept {
return !operator==(rhs);
}
Bool32 logicOpEnable = {};
LogicOp logicOp = LogicOp::eClear;
uint32_t attachmentCount = {};
const vuk::PipelineColorBlendAttachmentState* pAttachments = {};
std::array<float, 4> blendConstants = {};
};
enum class StencilOp {
eKeep = VK_STENCIL_OP_KEEP,
eZero = VK_STENCIL_OP_ZERO,
eReplace = VK_STENCIL_OP_REPLACE,
eIncrementAndClamp = VK_STENCIL_OP_INCREMENT_AND_CLAMP,
eDecrementAndClamp = VK_STENCIL_OP_DECREMENT_AND_CLAMP,
eInvert = VK_STENCIL_OP_INVERT,
eIncrementAndWrap = VK_STENCIL_OP_INCREMENT_AND_WRAP,
eDecrementAndWrap = VK_STENCIL_OP_DECREMENT_AND_WRAP
};
struct StencilOpState {
operator VkStencilOpState const&() const noexcept {
return *reinterpret_cast<const VkStencilOpState*>(this);
}
operator VkStencilOpState&() noexcept {
return *reinterpret_cast<VkStencilOpState*>(this);
}
bool operator==(StencilOpState const& rhs) const noexcept {
return (failOp == rhs.failOp) && (passOp == rhs.passOp) && (depthFailOp == rhs.depthFailOp) && (compareOp == rhs.compareOp) &&
(compareMask == rhs.compareMask) && (writeMask == rhs.writeMask) && (reference == rhs.reference);
}
bool operator!=(StencilOpState const& rhs) const noexcept {
return !operator==(rhs);
}
StencilOp failOp = StencilOp::eKeep;
StencilOp passOp = StencilOp::eKeep;
StencilOp depthFailOp = StencilOp::eKeep;
CompareOp compareOp = CompareOp::eNever;
uint32_t compareMask = {};
uint32_t writeMask = {};
uint32_t reference = {};
};
static_assert(sizeof(StencilOpState) == sizeof(VkStencilOpState), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<StencilOpState>::value, "struct wrapper is not a standard layout!");
struct PipelineDepthStencilStateCreateInfo {
bool operator==(PipelineDepthStencilStateCreateInfo const& rhs) const noexcept {
return (depthTestEnable == rhs.depthTestEnable) && (depthWriteEnable == rhs.depthWriteEnable) && (depthCompareOp == rhs.depthCompareOp) &&
(depthBoundsTestEnable == rhs.depthBoundsTestEnable) && (stencilTestEnable == rhs.stencilTestEnable) && (front == rhs.front) &&
(back == rhs.back) && (minDepthBounds == rhs.minDepthBounds) && (maxDepthBounds == rhs.maxDepthBounds);
}
bool operator!=(PipelineDepthStencilStateCreateInfo const& rhs) const noexcept {
return !operator==(rhs);
}
Bool32 depthTestEnable = {};
Bool32 depthWriteEnable = {};
CompareOp depthCompareOp = CompareOp::eNever;
Bool32 depthBoundsTestEnable = {};
Bool32 stencilTestEnable = {};
StencilOpState front = {};
StencilOpState back = {};
float minDepthBounds = {};
float maxDepthBounds = {};
};
enum class ConservativeRasterizationMode {
eDisabled = VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT,
eOverestimate = VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT,
eUnderestimate = VK_CONSERVATIVE_RASTERIZATION_MODE_UNDERESTIMATE_EXT
};
struct PipelineRasterizationConservativeStateCreateInfo {
bool operator==(PipelineRasterizationConservativeStateCreateInfo const& rhs) const noexcept {
return (mode == rhs.mode) && (overestimationAmount == rhs.overestimationAmount);
}
bool operator!=(PipelineRasterizationConservativeStateCreateInfo const& rhs) const noexcept {
return !operator==(rhs);
}
ConservativeRasterizationMode mode = ConservativeRasterizationMode::eDisabled;
float overestimationAmount = {};
};
struct VertexInputAttributeDescription {
bool operator==(VertexInputAttributeDescription const& rhs) const noexcept {
return (location == rhs.location) && (binding == rhs.binding) && (format == rhs.format) && (offset == rhs.offset);
}
bool operator!=(VertexInputAttributeDescription const& rhs) const noexcept {
return !operator==(rhs);
}
uint32_t location = {};
uint32_t binding = {};
Format format = Format::eUndefined;
uint32_t offset = {};
};
enum class DynamicStateFlagBits : uint64_t {
eNone = 0,
eViewport = 1 << 0,
eScissor = 1 << 1,
eLineWidth = 1 << 2,
eDepthBias = 1 << 3,
eBlendConstants = 1 << 4,
eDepthBounds = 1 << 5,
// additional dynamic state to implement:
/*eStencilCompareMask = 1 << 6,
eStencilWriteMask = 1 << 7,
eStencilReference = 1 << 8,
eViewportWScalingNV = 1 << 9,
eDiscardRectangleEXT = 1 << 10,
eSampleLocationsEXT = 1 << 11,
eRaytracingPipelineStackSizeKHR = 1 << 12,
eViewportShadingRatePaletteNV = 1 << 13,
eViewportCoarseSampleOrderNV = 1 << 14,
eExclusiveScissorNV = 1 << 15,
eFragmentShadingRateKHR = 1 << 16,
eLineStippleEXT = 1 << 17,
eCullModeEXT = 1 << 18,
eFrontFaceEXT = 1 << 19,
ePrimitiveTopologyEXT = 1 << 20,
eViewportWithCountEXT = 1 << 21,
eScissorWithCountEXT = 1 << 22,
eVertexInputBindingStrideEXT = 1 << 23,
eDepthTestEnableEXT = 1 << 24,
eDepthWriteEnableEXT = 1 << 25,
eDepthCompareOpEXT = 1 << 26,
eStencilTestEnableEXT = 1 << 27,
eStencilOpEXT = 1 << 28,
eVertexInputEXT = 1 << 29,
ePatchControlPointsEXT = 1 << 30,
eRasterizerDiscardEnableEXT = 1 << 31,
eDepthBiasEnableEXT = 1Ui64 << 32,
eLogicOpEXT = 1Ui64 << 33,
ePrimitiveRestartEnableEXT = 1Ui64 << 34,
eColorWriteEnableEXT = 1Ui64 << 35*/
};
using DynamicStateFlags = Flags<DynamicStateFlagBits>;
inline constexpr DynamicStateFlags operator|(DynamicStateFlagBits bit0, DynamicStateFlagBits bit1) noexcept {
return (DynamicStateFlags)bit0 | bit1;
}
inline constexpr DynamicStateFlags operator&(DynamicStateFlagBits bit0, DynamicStateFlagBits bit1) noexcept {
return (DynamicStateFlags)bit0 & bit1;
}
inline constexpr DynamicStateFlags operator^(DynamicStateFlagBits bit0, DynamicStateFlagBits bit1) noexcept {
return (DynamicStateFlags)bit0 ^ bit1;
}
}; // namespace vuk
inline bool operator==(VkPushConstantRange const& lhs, VkPushConstantRange const& rhs) noexcept {
return (lhs.stageFlags == rhs.stageFlags) && (lhs.offset == rhs.offset) && (lhs.size == rhs.size);
}
<file_sep>#include "vuk/resources/DeviceFrameResource.hpp"
#include "BufferAllocator.hpp"
#include "Cache.hpp"
#include "RenderPass.hpp"
#include "vuk/Context.hpp"
#include "vuk/Descriptor.hpp"
#include "vuk/PipelineInstance.hpp"
#include "vuk/Query.hpp"
#include <atomic>
#include <mutex>
#include <numeric>
#include <plf_colony.h>
#include <shared_mutex>
namespace vuk {
struct DeviceSuperFrameResourceImpl {
DeviceSuperFrameResource* sfr;
std::shared_mutex new_frame_mutex;
std::atomic<uint64_t> frame_counter;
std::atomic<uint64_t> local_frame;
std::unique_ptr<char[]> frames_storage;
DeviceFrameResource* frames;
plf::colony<DeviceMultiFrameResource> multi_frames;
std::mutex command_pool_mutex;
std::array<std::vector<VkCommandPool>, 3> command_pools;
std::mutex ds_pool_mutex;
std::vector<VkDescriptorPool> ds_pools;
std::mutex images_mutex;
std::unordered_map<ImageCreateInfo, uint32_t> image_identity;
Cache<ImageWithIdentity> image_cache;
Cache<ImageView> image_view_cache;
Cache<GraphicsPipelineInfo> graphics_pipeline_cache;
Cache<ComputePipelineInfo> compute_pipeline_cache;
Cache<RayTracingPipelineInfo> ray_tracing_pipeline_cache;
Cache<VkRenderPass> render_pass_cache;
BufferSubAllocator suballocators[4];
DeviceSuperFrameResourceImpl(DeviceSuperFrameResource& sfr, size_t frames_in_flight) :
sfr(&sfr),
image_cache(
this,
+[](void* allocator, const CachedImageIdentifier& cii) {
ImageWithIdentity i;
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->allocate_images({ &i.image, 1 }, { &cii.ici, 1 }, {}); // TODO: dropping error
return i;
},
+[](void* allocator, const ImageWithIdentity& i) {
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->deallocate_images({ &i.image, 1 });
}),
image_view_cache(
this,
+[](void* allocator, const CompressedImageViewCreateInfo& civci) {
ImageView iv;
ImageViewCreateInfo ivci = static_cast<ImageViewCreateInfo>(civci);
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->allocate_image_views({ &iv, 1 }, { &ivci, 1 }, {}); // TODO: dropping error
return iv;
},
+[](void* allocator, const ImageView& iv) {
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->deallocate_image_views({ &iv, 1 });
}),
graphics_pipeline_cache(
this,
+[](void* allocator, const GraphicsPipelineInstanceCreateInfo& ci) {
GraphicsPipelineInfo dst;
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->allocate_graphics_pipelines({ &dst, 1 }, { &ci, 1 }, {});
return dst;
},
+[](void* allocator, const GraphicsPipelineInfo& v) {
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->deallocate_graphics_pipelines({ &v, 1 });
}),
compute_pipeline_cache(
this,
+[](void* allocator, const ComputePipelineInstanceCreateInfo& ci) {
ComputePipelineInfo dst;
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->allocate_compute_pipelines({ &dst, 1 }, { &ci, 1 }, {});
return dst;
},
+[](void* allocator, const ComputePipelineInfo& v) {
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->deallocate_compute_pipelines({ &v, 1 });
}),
ray_tracing_pipeline_cache(
this,
+[](void* allocator, const RayTracingPipelineInstanceCreateInfo& ci) {
RayTracingPipelineInfo dst;
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->allocate_ray_tracing_pipelines({ &dst, 1 }, { &ci, 1 }, {});
return dst;
},
+[](void* allocator, const RayTracingPipelineInfo& v) {
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->deallocate_ray_tracing_pipelines({ &v, 1 });
}),
render_pass_cache(
this,
+[](void* allocator, const RenderPassCreateInfo& ci) {
VkRenderPass dst;
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->allocate_render_passes({ &dst, 1 }, { &ci, 1 }, {});
return dst;
},
+[](void* allocator, const VkRenderPass& v) {
reinterpret_cast<DeviceSuperFrameResourceImpl*>(allocator)->sfr->deallocate_render_passes({ &v, 1 });
}),
suballocators{ { *sfr.upstream, vuk::MemoryUsage::eGPUonly, all_buffer_usage_flags, 64 * 1024 * 1024 },
{ *sfr.upstream, vuk::MemoryUsage::eCPUonly, all_buffer_usage_flags, 64 * 1024 * 1024 },
{ *sfr.upstream, vuk::MemoryUsage::eCPUtoGPU, all_buffer_usage_flags, 64 * 1024 * 1024 },
{ *sfr.upstream, vuk::MemoryUsage::eGPUtoCPU, all_buffer_usage_flags, 64 * 1024 * 1024 } } {
frames_storage = std::unique_ptr<char[]>(new char[sizeof(DeviceFrameResource) * frames_in_flight]);
for (uint64_t i = 0; i < frames_in_flight; i++) {
new (frames_storage.get() + i * sizeof(DeviceFrameResource)) DeviceFrameResource(sfr.get_context().device, sfr);
}
frames = reinterpret_cast<DeviceFrameResource*>(frames_storage.get());
}
};
struct DeviceFrameResourceImpl {
Context* ctx;
std::mutex sema_mutex;
std::vector<VkSemaphore> semaphores;
std::mutex buf_mutex;
std::vector<Buffer> buffers;
std::mutex fence_mutex;
std::vector<VkFence> fences;
std::mutex cbuf_mutex;
std::vector<CommandBufferAllocation> cmdbuffers_to_free;
std::vector<CommandPool> cmdpools_to_free;
std::mutex framebuffer_mutex;
std::vector<VkFramebuffer> framebuffers;
std::mutex images_mutex;
std::vector<Image> images;
std::mutex image_views_mutex;
std::vector<ImageView> image_views;
std::mutex pds_mutex;
std::vector<PersistentDescriptorSet> persistent_descriptor_sets;
std::mutex ds_mutex;
std::vector<DescriptorSet> descriptor_sets;
std::atomic<VkDescriptorPool*> last_ds_pool;
plf::colony<VkDescriptorPool> ds_pools;
std::vector<VkDescriptorPool> ds_pools_to_destroy;
// only for use via SuperframeAllocator
std::mutex buffers_mutex;
std::vector<Buffer> buffer_gpus;
std::vector<TimestampQueryPool> ts_query_pools;
std::mutex query_pool_mutex;
std::mutex ts_query_mutex;
uint64_t query_index = 0;
uint64_t current_ts_pool = 0;
std::mutex tsema_mutex;
std::vector<TimelineSemaphore> tsemas;
std::mutex as_mutex;
std::vector<VkAccelerationStructureKHR> ass;
std::mutex swapchain_mutex;
std::vector<VkSwapchainKHR> swapchains;
std::mutex pipelines_mutex;
std::vector<GraphicsPipelineInfo> graphics_pipes;
std::vector<ComputePipelineInfo> compute_pipes;
std::vector<RayTracingPipelineInfo> ray_tracing_pipes;
std::mutex render_passes_mutex;
std::vector<VkRenderPass> render_passes;
BufferLinearAllocator linear_cpu_only;
BufferLinearAllocator linear_cpu_gpu;
BufferLinearAllocator linear_gpu_cpu;
BufferLinearAllocator linear_gpu_only;
DeviceFrameResourceImpl(VkDevice device, DeviceSuperFrameResource& upstream) :
ctx(&upstream.get_context()),
linear_cpu_only(upstream, vuk::MemoryUsage::eCPUonly, all_buffer_usage_flags),
linear_cpu_gpu(upstream, vuk::MemoryUsage::eCPUtoGPU, all_buffer_usage_flags),
linear_gpu_cpu(upstream, vuk::MemoryUsage::eGPUtoCPU, all_buffer_usage_flags),
linear_gpu_only(upstream, vuk::MemoryUsage::eGPUonly, all_buffer_usage_flags) {}
};
DeviceFrameResource::DeviceFrameResource(VkDevice device, DeviceSuperFrameResource& pstream) :
DeviceNestedResource(static_cast<DeviceResource&>(pstream)),
device(device),
impl(new DeviceFrameResourceImpl(device, pstream)) {}
Result<void, AllocateException> DeviceFrameResource::allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_semaphores(dst, loc));
std::unique_lock _(impl->sema_mutex);
auto& vec = impl->semaphores;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_semaphores(std::span<const VkSemaphore> src) {} // noop
Result<void, AllocateException> DeviceFrameResource::allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_fences(dst, loc));
std::unique_lock _(impl->fence_mutex);
auto& vec = impl->fences;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_fences(std::span<const VkFence> src) {} // noop
Result<void, AllocateException> DeviceFrameResource::allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_command_buffers(dst, cis, loc));
std::unique_lock _(impl->cbuf_mutex);
auto& vec = impl->cmdbuffers_to_free;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_command_buffers(std::span<const CommandBufferAllocation> src) {} // no-op, deallocated with pools
Result<void, AllocateException>
DeviceFrameResource::allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_command_pools(dst, cis, loc));
std::unique_lock _(impl->cbuf_mutex);
auto& vec = impl->cmdpools_to_free;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_command_pools(std::span<const CommandPool> dst) {} // no-op
Result<void, AllocateException>
DeviceFrameResource::allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
Result<Buffer, AllocateException> result{ expected_value };
auto alignment = std::lcm(ci.alignment, get_context().min_buffer_alignment);
if (ci.mem_usage == MemoryUsage::eGPUonly) {
result = impl->linear_gpu_only.allocate_buffer(ci.size, alignment, loc);
} else if (ci.mem_usage == MemoryUsage::eCPUonly) {
result = impl->linear_cpu_only.allocate_buffer(ci.size, alignment, loc);
} else if (ci.mem_usage == MemoryUsage::eCPUtoGPU) {
result = impl->linear_cpu_gpu.allocate_buffer(ci.size, alignment, loc);
} else if (ci.mem_usage == MemoryUsage::eGPUtoCPU) {
result = impl->linear_gpu_cpu.allocate_buffer(ci.size, alignment, loc);
}
if (!result) {
deallocate_buffers({ dst.data(), (uint64_t)i });
return result;
}
dst[i] = result.value();
}
return { expected_value };
}
void DeviceFrameResource::deallocate_buffers(std::span<const Buffer> src) {} // no-op, linear
Result<void, AllocateException>
DeviceFrameResource::allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_framebuffers(dst, cis, loc));
std::unique_lock _(impl->framebuffer_mutex);
auto& vec = impl->framebuffers;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_framebuffers(std::span<const VkFramebuffer> src) {} // noop
Result<void, AllocateException> DeviceFrameResource::allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(static_cast<DeviceSuperFrameResource*>(upstream)->allocate_cached_images(dst, cis, loc));
return { expected_value };
}
void DeviceFrameResource::deallocate_images(std::span<const Image> src) {} // noop
Result<void, AllocateException>
DeviceFrameResource::allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(static_cast<DeviceSuperFrameResource*>(upstream)->allocate_cached_image_views(dst, cis, loc));
return { expected_value };
}
void DeviceFrameResource::deallocate_image_views(std::span<const ImageView> src) {} // noop
Result<void, AllocateException> DeviceFrameResource::allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_persistent_descriptor_sets(dst, cis, loc));
std::unique_lock _(impl->pds_mutex);
auto& vec = impl->persistent_descriptor_sets;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) {} // noop
Result<void, AllocateException>
DeviceFrameResource::allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_descriptor_sets_with_value(dst, cis, loc));
std::unique_lock _(impl->ds_mutex);
auto& vec = impl->descriptor_sets;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_descriptor_sets(std::span<const DescriptorSet> src) {} // noop
Result<void, AllocateException>
DeviceFrameResource::allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) {
VkDescriptorPoolCreateInfo dpci{ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
dpci.maxSets = 1000;
std::array<VkDescriptorPoolSize, 12> descriptor_counts = {};
size_t count = get_context().vkCmdBuildAccelerationStructuresKHR ? descriptor_counts.size() : descriptor_counts.size() - 1;
for (size_t i = 0; i < count; i++) {
auto& d = descriptor_counts[i];
d.type = i == 11 ? VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR : VkDescriptorType(i);
d.descriptorCount = 1000;
}
dpci.pPoolSizes = descriptor_counts.data();
dpci.poolSizeCount = (uint32_t)count;
if (impl->ds_pools.size() == 0) {
std::unique_lock _(impl->ds_mutex);
if (impl->ds_pools.size() == 0) { // this assures only 1 thread gets to do this
VkDescriptorPool pool;
VUK_DO_OR_RETURN(upstream->allocate_descriptor_pools({ &pool, 1 }, { &dpci, 1 }, loc));
impl->last_ds_pool = &*impl->ds_pools.emplace(pool);
}
}
// look at last stored pool
VkDescriptorPool* last_pool = impl->last_ds_pool.load();
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
// attempt to allocate a set
VkDescriptorSetAllocateInfo dsai = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
dsai.descriptorPool = *last_pool;
dsai.descriptorSetCount = 1;
dsai.pSetLayouts = &ci.layout;
dst[i].layout_info = ci;
auto result = impl->ctx->vkAllocateDescriptorSets(device, &dsai, &dst[i].descriptor_set);
// if we fail, we allocate another pool from upstream
if (result == VK_ERROR_OUT_OF_POOL_MEMORY ||
result == VK_ERROR_FRAGMENTED_POOL) { // we potentially run this from multiple threads which results in additional pool allocs
{
std::unique_lock _(impl->ds_mutex);
VkDescriptorPool pool;
VUK_DO_OR_RETURN(upstream->allocate_descriptor_pools({ &pool, 1 }, { &dpci, 1 }, loc));
last_pool = &*impl->ds_pools.emplace(pool);
}
dsai.descriptorPool = *last_pool;
result = impl->ctx->vkAllocateDescriptorSets(device, &dsai, &dst[i].descriptor_set);
if (result != VK_SUCCESS) {
return { expected_error, AllocateException{ result } };
}
}
}
return { expected_value };
}
Result<void, AllocateException> DeviceFrameResource::allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst,
std::span<const VkQueryPoolCreateInfo> cis,
SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_timestamp_query_pools(dst, cis, loc));
std::unique_lock _(impl->query_pool_mutex);
auto& vec = impl->ts_query_pools;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) {} // noop
Result<void, AllocateException>
DeviceFrameResource::allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) {
std::unique_lock _(impl->ts_query_mutex);
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
if (ci.pool) { // use given pool to allocate query
ci.pool->queries[ci.pool->count++] = ci.query;
dst[i].id = ci.pool->count;
dst[i].pool = ci.pool->pool;
} else { // allocate a pool on demand
std::unique_lock _(impl->query_pool_mutex);
if (impl->query_index % TimestampQueryPool::num_queries == 0) {
VkQueryPoolCreateInfo qpci{ VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO };
qpci.queryCount = TimestampQueryPool::num_queries;
qpci.queryType = VK_QUERY_TYPE_TIMESTAMP;
TimestampQueryPool p;
VUK_DO_OR_RETURN(upstream->allocate_timestamp_query_pools(std::span{ &p, 1 }, std::span{ &qpci, 1 }, loc));
auto& vec = impl->ts_query_pools;
vec.emplace_back(p);
impl->current_ts_pool = vec.size() - 1;
}
auto& pool = impl->ts_query_pools[impl->current_ts_pool];
pool.queries[pool.count++] = ci.query;
dst[i].id = pool.count - 1;
dst[i].pool = pool.pool;
impl->query_index++;
}
}
return { expected_value };
}
void DeviceFrameResource::deallocate_timestamp_queries(std::span<const TimestampQuery> src) {} // noop
Result<void, AllocateException> DeviceFrameResource::allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(upstream->allocate_timeline_semaphores(dst, loc));
std::unique_lock _(impl->tsema_mutex);
auto& vec = impl->tsemas;
vec.insert(vec.end(), dst.begin(), dst.end());
return { expected_value };
}
void DeviceFrameResource::deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) {} // noop
void DeviceFrameResource::deallocate_swapchains(std::span<const VkSwapchainKHR> src) {
std::scoped_lock _(impl->swapchain_mutex);
auto& vec = impl->swapchains;
vec.insert(vec.end(), src.begin(), src.end());
}
Result<void, AllocateException> DeviceFrameResource::allocate_graphics_pipelines(std::span<GraphicsPipelineInfo> dst,
std::span<const GraphicsPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
auto& sfr = *static_cast<DeviceSuperFrameResource*>(upstream);
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
dst[i] = sfr.impl->graphics_pipeline_cache.acquire(ci, construction_frame);
}
return { expected_value };
}
void DeviceFrameResource::deallocate_graphics_pipelines(std::span<const GraphicsPipelineInfo> src) {}
Result<void, AllocateException> DeviceFrameResource::allocate_compute_pipelines(std::span<ComputePipelineInfo> dst,
std::span<const ComputePipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
auto& sfr = *static_cast<DeviceSuperFrameResource*>(upstream);
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
dst[i] = sfr.impl->compute_pipeline_cache.acquire(ci, construction_frame);
}
return { expected_value };
}
void DeviceFrameResource::deallocate_compute_pipelines(std::span<const ComputePipelineInfo> src) {}
Result<void, AllocateException> DeviceFrameResource::allocate_ray_tracing_pipelines(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
auto& sfr = *static_cast<DeviceSuperFrameResource*>(upstream);
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
dst[i] = sfr.impl->ray_tracing_pipeline_cache.acquire(ci, construction_frame);
}
return { expected_value };
}
void DeviceFrameResource::deallocate_ray_tracing_pipelines(std::span<const RayTracingPipelineInfo> src) {}
Result<void, AllocateException>
DeviceFrameResource::allocate_render_passes(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc) {
auto& sfr = *static_cast<DeviceSuperFrameResource*>(upstream);
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
dst[i] = sfr.impl->render_pass_cache.acquire(ci, construction_frame);
}
return { expected_value };
}
void DeviceFrameResource::deallocate_render_passes(std::span<const VkRenderPass> src) {}
void DeviceFrameResource::wait() {
if (impl->fences.size() > 0) {
if (impl->fences.size() > 64) {
int i = 0;
for (; i < impl->fences.size() - 64; i += 64) {
impl->ctx->vkWaitForFences(device, 64, impl->fences.data() + i, true, UINT64_MAX);
}
impl->ctx->vkWaitForFences(device, (uint32_t)impl->fences.size() - i, impl->fences.data() + i, true, UINT64_MAX);
} else {
impl->ctx->vkWaitForFences(device, (uint32_t)impl->fences.size(), impl->fences.data(), true, UINT64_MAX);
}
}
if (impl->tsemas.size() > 0) {
VkSemaphoreWaitInfo swi{ VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO };
std::vector<VkSemaphore> semas(impl->tsemas.size());
std::vector<uint64_t> values(impl->tsemas.size());
for (uint64_t i = 0; i < impl->tsemas.size(); i++) {
semas[i] = impl->tsemas[i].semaphore;
values[i] = *impl->tsemas[i].value;
}
swi.pSemaphores = semas.data();
swi.pValues = values.data();
swi.semaphoreCount = (uint32_t)impl->tsemas.size();
impl->ctx->vkWaitSemaphores(device, &swi, UINT64_MAX);
}
}
DeviceMultiFrameResource::DeviceMultiFrameResource(VkDevice device, DeviceSuperFrameResource& upstream, uint32_t frame_lifetime) :
DeviceFrameResource(device, upstream),
frame_lifetime(frame_lifetime),
remaining_lifetime(frame_lifetime),
multiframe_id((uint32_t)(construction_frame % frame_lifetime)) {}
Result<void, AllocateException>
DeviceMultiFrameResource::allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) {
VUK_DO_OR_RETURN(static_cast<DeviceSuperFrameResource*>(upstream)->allocate_cached_images(dst, cis, loc));
return { expected_value };
}
DeviceSuperFrameResource::DeviceSuperFrameResource(Context& ctx, uint64_t frames_in_flight) :
DeviceNestedResource(ctx.get_vk_resource()),
frames_in_flight(frames_in_flight),
direct(static_cast<DeviceVkResource*>(upstream)),
impl(new DeviceSuperFrameResourceImpl(*this, frames_in_flight)) {}
DeviceSuperFrameResource::DeviceSuperFrameResource(DeviceResource& upstream, uint64_t frames_in_flight) :
DeviceNestedResource(upstream),
frames_in_flight(frames_in_flight),
direct(dynamic_cast<DeviceVkResource*>(this->upstream)),
impl(new DeviceSuperFrameResourceImpl(*this, frames_in_flight)) {}
void DeviceSuperFrameResource::deallocate_semaphores(std::span<const VkSemaphore> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->sema_mutex);
auto& vec = get_last_frame().impl->semaphores;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_fences(std::span<const VkFence> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->fence_mutex);
auto& vec = f.impl->fences;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_command_buffers(std::span<const CommandBufferAllocation> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->cbuf_mutex);
auto& vec = f.impl->cmdbuffers_to_free;
vec.insert(vec.end(), src.begin(), src.end());
}
Result<void, AllocateException>
DeviceSuperFrameResource::allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) {
std::scoped_lock _(impl->command_pool_mutex);
assert(cis.size() == dst.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
auto& source = impl->command_pools[ci.queueFamilyIndex];
if (source.size() > 0) {
dst[i] = { source.back(), ci.queueFamilyIndex };
source.pop_back();
} else {
VUK_DO_OR_RETURN(upstream->allocate_command_pools(std::span{ &dst[i], 1 }, std::span{ &ci, 1 }, loc));
}
}
return { expected_value };
}
void DeviceSuperFrameResource::deallocate_command_pools(std::span<const CommandPool> src) {
std::scoped_lock _(impl->command_pool_mutex);
for (auto& p : src) {
impl->command_pools[p.queue_family_index].push_back(p.command_pool);
}
}
void DeviceSuperFrameResource::deallocate_buffers(std::span<const Buffer> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->buffers_mutex);
auto& vec = f.impl->buffer_gpus;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_framebuffers(std::span<const VkFramebuffer> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->framebuffer_mutex);
auto& vec = f.impl->framebuffers;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_images(std::span<const Image> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->images_mutex);
auto& vec = f.impl->images;
vec.insert(vec.end(), src.begin(), src.end());
}
Result<void, AllocateException>
DeviceSuperFrameResource::allocate_cached_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) {
std::unique_lock _(impl->images_mutex);
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
auto index = impl->image_identity[ci]++;
CachedImageIdentifier iici = { ci, index, 0 };
dst[i] = impl->image_cache.acquire(iici, impl->frame_counter).image;
}
return { expected_value };
}
Result<void, AllocateException>
DeviceSuperFrameResource::allocate_cached_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
CompressedImageViewCreateInfo civci(ci);
dst[i] = impl->image_view_cache.acquire(civci, impl->frame_counter);
}
return { expected_value };
}
Result<void, AllocateException>
DeviceSuperFrameResource::allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
auto& alloc = impl->suballocators[(int)ci.mem_usage - 1];
auto alignment = std::lcm(ci.alignment, get_context().min_buffer_alignment);
auto res = alloc.allocate_buffer(ci.size, alignment, loc);
if (!res) {
deallocate_buffers({ dst.data(), (uint64_t)i });
return res;
}
dst[i] = *res;
}
return { expected_value };
}
void DeviceSuperFrameResource::deallocate_image_views(std::span<const ImageView> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->image_views_mutex);
auto& vec = f.impl->image_views;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->pds_mutex);
auto& vec = f.impl->persistent_descriptor_sets;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_descriptor_sets(std::span<const DescriptorSet> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->ds_mutex);
auto& vec = f.impl->descriptor_sets;
vec.insert(vec.end(), src.begin(), src.end());
}
Result<void, AllocateException> DeviceSuperFrameResource::allocate_descriptor_pools(std::span<VkDescriptorPool> dst,
std::span<const VkDescriptorPoolCreateInfo> cis,
SourceLocationAtFrame loc) {
std::scoped_lock _(impl->ds_pool_mutex);
assert(cis.size() == dst.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
auto& source = impl->ds_pools;
if (source.size() > 0) {
dst[i] = source.back();
source.pop_back();
} else {
VUK_DO_OR_RETURN(upstream->allocate_descriptor_pools(std::span{ &dst[i], 1 }, std::span{ &ci, 1 }, loc));
}
}
return { expected_value };
}
void DeviceSuperFrameResource::deallocate_descriptor_pools(std::span<const VkDescriptorPool> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->ds_mutex);
auto& vec = f.impl->ds_pools_to_destroy;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->query_pool_mutex);
auto& vec = f.impl->ts_query_pools;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_timestamp_queries(std::span<const TimestampQuery> src) {} // noop
void DeviceSuperFrameResource::deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->tsema_mutex);
auto& vec = f.impl->tsemas;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_acceleration_structures(std::span<const VkAccelerationStructureKHR> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->as_mutex);
auto& vec = f.impl->ass;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_swapchains(std::span<const VkSwapchainKHR> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->swapchain_mutex);
auto& vec = f.impl->swapchains;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_graphics_pipelines(std::span<const GraphicsPipelineInfo> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->pipelines_mutex);
auto& vec = f.impl->graphics_pipes;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_compute_pipelines(std::span<const ComputePipelineInfo> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->pipelines_mutex);
auto& vec = f.impl->compute_pipes;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_ray_tracing_pipelines(std::span<const RayTracingPipelineInfo> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->pipelines_mutex);
auto& vec = f.impl->ray_tracing_pipes;
vec.insert(vec.end(), src.begin(), src.end());
}
void DeviceSuperFrameResource::deallocate_render_passes(std::span<const VkRenderPass> src) {
std::shared_lock _s(impl->new_frame_mutex);
auto& f = get_last_frame();
std::unique_lock _(f.impl->render_passes_mutex);
auto& vec = f.impl->render_passes;
vec.insert(vec.end(), src.begin(), src.end());
}
DeviceFrameResource& DeviceSuperFrameResource::get_last_frame() {
return impl->frames[impl->frame_counter.load() % frames_in_flight];
}
DeviceFrameResource& DeviceSuperFrameResource::get_next_frame() {
std::unique_lock _s(impl->new_frame_mutex);
impl->frame_counter++;
impl->local_frame = impl->frame_counter % frames_in_flight;
// handle FrameResource
auto& f = impl->frames[impl->local_frame];
f.wait();
deallocate_frame(f);
f.construction_frame = impl->frame_counter.load();
// handle MultiFrameResources
for (auto it = impl->multi_frames.begin(); it != impl->multi_frames.end();) {
auto& multi_frame = *it;
multi_frame.remaining_lifetime--;
if (multi_frame.remaining_lifetime == 0) {
multi_frame.wait();
deallocate_frame(multi_frame);
it = impl->multi_frames.erase(it);
} else {
++it;
}
}
impl->image_identity.clear();
_s.unlock();
// garbage collect caches
impl->image_cache.collect(impl->frame_counter, 16);
impl->image_view_cache.collect(impl->frame_counter, 16);
impl->graphics_pipeline_cache.collect(impl->frame_counter, 16);
impl->compute_pipeline_cache.collect(impl->frame_counter, 16);
impl->ray_tracing_pipeline_cache.collect(impl->frame_counter, 16);
impl->render_pass_cache.collect(impl->frame_counter, 16);
return f;
}
DeviceMultiFrameResource& DeviceSuperFrameResource::get_multiframe_allocator(uint32_t frame_lifetime_count) {
std::unique_lock _s(impl->new_frame_mutex);
auto it = impl->multi_frames.emplace(DeviceMultiFrameResource(get_context().device, *this, frame_lifetime_count));
return *it;
}
template<class T>
void DeviceSuperFrameResource::deallocate_frame(T& frame) {
auto& f = *frame.impl;
upstream->deallocate_semaphores(f.semaphores);
upstream->deallocate_fences(f.fences);
upstream->deallocate_command_buffers(f.cmdbuffers_to_free);
for (auto& pool : f.cmdpools_to_free) {
direct->ctx->vkResetCommandPool(get_context().device, pool.command_pool, {});
}
deallocate_command_pools(f.cmdpools_to_free);
for (Buffer& buf : f.buffer_gpus) {
impl->suballocators[(int)buf.memory_usage - 1].deallocate_buffer(buf);
}
upstream->deallocate_framebuffers(f.framebuffers);
upstream->deallocate_images(f.images);
upstream->deallocate_image_views(f.image_views);
upstream->deallocate_persistent_descriptor_sets(f.persistent_descriptor_sets);
upstream->deallocate_descriptor_sets(f.descriptor_sets);
get_context().make_timestamp_results_available(f.ts_query_pools);
upstream->deallocate_timestamp_query_pools(f.ts_query_pools);
upstream->deallocate_timeline_semaphores(f.tsemas);
upstream->deallocate_acceleration_structures(f.ass);
upstream->deallocate_swapchains(f.swapchains);
upstream->deallocate_buffers(f.buffers);
for (auto& p : f.ds_pools) {
direct->ctx->vkResetDescriptorPool(get_context().device, p, {});
impl->ds_pools.push_back(p);
}
upstream->deallocate_descriptor_pools(f.ds_pools_to_destroy);
upstream->deallocate_graphics_pipelines(f.graphics_pipes);
upstream->deallocate_compute_pipelines(f.compute_pipes);
upstream->deallocate_ray_tracing_pipelines(f.ray_tracing_pipes);
upstream->deallocate_render_passes(f.render_passes);
f.semaphores.clear();
f.fences.clear();
f.buffer_gpus.clear();
f.cmdbuffers_to_free.clear();
f.cmdpools_to_free.clear();
f.ds_pools.clear();
if (direct) {
if (frame.construction_frame % 16 == 0) {
f.linear_cpu_only.trim();
f.linear_cpu_gpu.trim();
f.linear_gpu_cpu.trim();
f.linear_gpu_only.trim();
}
f.linear_cpu_only.reset();
f.linear_cpu_gpu.reset();
f.linear_gpu_cpu.reset();
f.linear_gpu_only.reset();
}
f.framebuffers.clear();
f.images.clear();
f.image_views.clear();
f.persistent_descriptor_sets.clear();
f.descriptor_sets.clear();
f.ts_query_pools.clear();
f.query_index = 0;
f.tsemas.clear();
f.ass.clear();
f.swapchains.clear();
f.buffers.clear();
f.ds_pools_to_destroy.clear();
f.graphics_pipes.clear();
f.compute_pipes.clear();
f.ray_tracing_pipes.clear();
f.render_passes.clear();
}
void DeviceSuperFrameResource::force_collect() {
impl->image_cache.collect(impl->frame_counter, 0);
impl->image_view_cache.collect(impl->frame_counter, 0);
impl->graphics_pipeline_cache.collect(impl->frame_counter, 0);
impl->compute_pipeline_cache.collect(impl->frame_counter, 0);
impl->ray_tracing_pipeline_cache.collect(impl->frame_counter, 0);
impl->render_pass_cache.collect(impl->frame_counter, 0);
}
DeviceSuperFrameResource::~DeviceSuperFrameResource() {
impl->image_cache.clear();
impl->image_view_cache.clear();
impl->graphics_pipeline_cache.clear();
impl->compute_pipeline_cache.clear();
impl->ray_tracing_pipeline_cache.clear();
impl->render_pass_cache.clear();
for (auto i = 0; i < frames_in_flight; i++) {
auto lframe = (impl->frame_counter + i) % frames_in_flight;
auto& f = impl->frames[lframe];
f.wait();
// free the resources manually, because we are destroying the individual FAs
f.impl->linear_cpu_gpu.free();
f.impl->linear_gpu_cpu.free();
f.impl->linear_cpu_only.free();
f.impl->linear_gpu_only.free();
}
for (auto i = 0; i < frames_in_flight; i++) {
auto lframe = (impl->frame_counter + i) % frames_in_flight;
auto& f = impl->frames[lframe];
deallocate_frame(f);
f.DeviceFrameResource::~DeviceFrameResource();
}
for (uint32_t i = 0; i < (uint32_t)impl->command_pools.size(); i++) {
for (auto& cpool : impl->command_pools[i]) {
CommandPool p{ cpool, i };
upstream->deallocate_command_pools(std::span{ &p, 1 });
}
}
for (auto& p : impl->ds_pools) {
direct->deallocate_descriptor_pools(std::span{ &p, 1 });
}
delete impl;
}
} // namespace vuk<file_sep>#include "vuk/Allocator.hpp"
#include "RenderPass.hpp"
#include "vuk/Context.hpp"
#include "vuk/Exception.hpp"
#include "vuk/Query.hpp"
#include "vuk/resources/DeviceFrameResource.hpp"
#include "vuk/resources/DeviceVkResource.hpp"
#include <numeric>
#include <string>
#include <utility>
namespace vuk {
/****Allocator impls *****/
Result<void, AllocateException> Allocator::allocate(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) {
return device_resource->allocate_semaphores(dst, loc);
}
Result<void, AllocateException> Allocator::allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) {
return device_resource->allocate_semaphores(dst, loc);
}
void Allocator::deallocate(std::span<const VkSemaphore> src) {
device_resource->deallocate_semaphores(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<VkFence> dst, SourceLocationAtFrame loc) {
return device_resource->allocate_fences(dst, loc);
}
Result<void, AllocateException> Allocator::allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) {
return device_resource->allocate_fences(dst, loc);
}
void Allocator::deallocate(std::span<const VkFence> src) {
device_resource->deallocate_fences(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_command_pools(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_command_pools(dst, cis, loc);
}
void Allocator::deallocate(std::span<const CommandPool> src) {
device_resource->deallocate_command_pools(src);
}
Result<void, AllocateException>
Allocator::allocate(std::span<CommandBufferAllocation> dst, std::span<const CommandBufferAllocationCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_command_buffers(dst, cis, loc);
}
Result<void, AllocateException> Allocator::allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc) {
return device_resource->allocate_command_buffers(dst, cis, loc);
}
void Allocator::deallocate(std::span<const CommandBufferAllocation> src) {
device_resource->deallocate_command_buffers(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_buffers(dst, cis, loc);
}
Result<void, AllocateException> Allocator::allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_buffers(dst, cis, loc);
}
void Allocator::deallocate(std::span<const Buffer> src) {
device_resource->deallocate_buffers(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_framebuffers(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_framebuffers(dst, cis, loc);
}
void Allocator::deallocate(std::span<const VkFramebuffer> src) {
device_resource->deallocate_framebuffers(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_images(dst, cis, loc);
}
Result<void, AllocateException> Allocator::allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_images(dst, cis, loc);
}
void Allocator::deallocate(std::span<const Image> src) {
device_resource->deallocate_images(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_image_views(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_image_views(dst, cis, loc);
}
void Allocator::deallocate(std::span<const ImageView> src) {
device_resource->deallocate_image_views(src);
}
Result<void, AllocateException>
Allocator::allocate(std::span<PersistentDescriptorSet> dst, std::span<const PersistentDescriptorSetCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_persistent_descriptor_sets(dst, cis, loc);
}
Result<void, AllocateException> Allocator::allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) {
return device_resource->allocate_persistent_descriptor_sets(dst, cis, loc);
}
void Allocator::deallocate(std::span<const PersistentDescriptorSet> src) {
device_resource->deallocate_persistent_descriptor_sets(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_descriptor_sets_with_value(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_descriptor_sets_with_value(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_descriptor_sets(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_descriptor_sets(dst, cis, loc);
}
void Allocator::deallocate(std::span<const DescriptorSet> src) {
device_resource->deallocate_descriptor_sets(src);
}
Result<void, AllocateException>
Allocator::allocate(std::span<TimestampQueryPool> dst, std::span<const VkQueryPoolCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_timestamp_query_pools(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst, std::span<const VkQueryPoolCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_timestamp_query_pools(dst, cis, loc);
}
void Allocator::deallocate(std::span<const TimestampQueryPool> src) {
device_resource->deallocate_timestamp_query_pools(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_timestamp_queries(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_timestamp_queries(dst, cis, loc);
}
void Allocator::deallocate(std::span<const TimestampQuery> src) {
device_resource->deallocate_timestamp_queries(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) {
return device_resource->allocate_timeline_semaphores(dst, loc);
}
Result<void, AllocateException> Allocator::allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) {
return device_resource->allocate_timeline_semaphores(dst, loc);
}
void Allocator::deallocate(std::span<const TimelineSemaphore> src) {
device_resource->deallocate_timeline_semaphores(src);
}
Result<void, AllocateException>
Allocator::allocate(std::span<VkAccelerationStructureKHR> dst, std::span<const VkAccelerationStructureCreateInfoKHR> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_acceleration_structures(dst, cis, loc);
}
Result<void, AllocateException> Allocator::allocate_acceleration_structures(std::span<VkAccelerationStructureKHR> dst,
std::span<const VkAccelerationStructureCreateInfoKHR> cis,
SourceLocationAtFrame loc) {
return device_resource->allocate_acceleration_structures(dst, cis, loc);
}
void Allocator::deallocate(std::span<const VkAccelerationStructureKHR> src) {
device_resource->deallocate_acceleration_structures(src);
}
void Allocator::deallocate(std::span<const VkSwapchainKHR> src) {
device_resource->deallocate_swapchains(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<GraphicsPipelineInfo> dst, std::span<const GraphicsPipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_graphics_pipelines(dst, cis, loc);
}
Result<void, AllocateException> Allocator::allocate_graphics_pipelines(std::span<GraphicsPipelineInfo> dst,
std::span<const GraphicsPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
return device_resource->allocate_graphics_pipelines(dst, cis, loc);
}
void Allocator::deallocate(std::span<const GraphicsPipelineInfo> src) {
device_resource->deallocate_graphics_pipelines(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<ComputePipelineInfo> dst,
std::span<const ComputePipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_compute_pipelines(dst, cis, loc);
}
Result<void, AllocateException> Allocator::allocate_compute_pipelines(std::span<ComputePipelineInfo> dst,
std::span<const ComputePipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
return device_resource->allocate_compute_pipelines(dst, cis, loc);
}
void Allocator::deallocate(std::span<const ComputePipelineInfo> src) {
device_resource->deallocate_compute_pipelines(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_ray_tracing_pipelines(dst, cis, loc);
}
Result<void, AllocateException> Allocator::allocate_ray_tracing_pipelines(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
return device_resource->allocate_ray_tracing_pipelines(dst, cis, loc);
}
void Allocator::deallocate(std::span<const RayTracingPipelineInfo> src) {
device_resource->deallocate_ray_tracing_pipelines(src);
}
Result<void, AllocateException> Allocator::allocate(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_render_passes(dst, cis, loc);
}
Result<void, AllocateException>
Allocator::allocate_render_passes(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc) {
return device_resource->allocate_render_passes(dst, cis, loc);
}
void Allocator::deallocate(std::span<const VkRenderPass> src) {
device_resource->deallocate_render_passes(src);
}
} // namespace vuk
<file_sep>#include "RenderGraphUtil.hpp"
#include "RenderGraphImpl.hpp"
#include "vuk/RenderGraph.hpp"
#include <fmt/format.h>
namespace vuk {
namespace detail {
ImageResourceInputOnly ImageResource::operator>>(Access ia) {
return { name, ia };
}
Resource ImageResourceInputOnly::operator>>(Name out) {
return { name, Resource::Type::eImage, ba, out };
}
ImageResourceInputOnly::operator Resource() {
if (!is_write_access(ba)) { // do not produce a name by default it is read-only
return operator>>(Name{});
}
return operator>>(name.append("+"));
}
BufferResourceInputOnly BufferResource::operator>>(Access ba) {
return { name, ba };
}
Resource BufferResourceInputOnly::operator>>(Name out) {
return { name, Resource::Type::eBuffer, ba, out };
}
BufferResourceInputOnly::operator Resource() {
if (!is_write_access(ba)) { // do not produce a name by default it is read-only
return operator>>(Name{});
}
return operator>>(name.append("+"));
}
} // namespace detail
// implement MapProxy for relevant types
// implement MapProxy for attachment
using MP2 = MapProxy<QualifiedName, const AttachmentInfo&>;
using MPI2 = ConstMapIterator<QualifiedName, const AttachmentInfo&>;
using M2 = robin_hood::unordered_flat_map<QualifiedName, AttachmentInfo>;
template<>
MP2::const_iterator MP2::cbegin() const noexcept {
auto& map = *reinterpret_cast<M2*>(_map);
return MP2::const_iterator(new M2::const_iterator(map.cbegin()));
}
template<>
MP2::const_iterator MP2::cend() const noexcept {
auto& map = *reinterpret_cast<M2*>(_map);
return MP2::const_iterator(new M2::const_iterator(map.cend()));
}
template<>
MP2::const_iterator MP2::find(QualifiedName key) const noexcept {
auto& map = *reinterpret_cast<M2*>(_map);
return MP2::const_iterator(new M2::const_iterator(map.find(key)));
}
template<>
size_t MP2::size() const noexcept {
auto& map = *reinterpret_cast<M2*>(_map);
return map.size();
}
template<>
MPI2::~ConstMapIterator() {
delete reinterpret_cast<M2::const_iterator*>(_iter);
}
template<>
MPI2::ConstMapIterator(const MPI2& other) noexcept {
*reinterpret_cast<M2::const_iterator*>(_iter) = *reinterpret_cast<M2::iterator*>(other._iter);
}
template<>
MPI2::reference MPI2::operator*() noexcept {
const auto& iter = *reinterpret_cast<M2::const_iterator const*>(_iter);
return { iter->first, iter->second };
}
template<>
MPI2& MPI2::operator++() noexcept {
reinterpret_cast<M2::iterator*>(_iter)->operator++();
return *this;
}
template<>
bool MPI2::operator==(MPI2 const& other) const noexcept {
return *reinterpret_cast<M2::iterator const*>(_iter) == *reinterpret_cast<M2::iterator const*>(other._iter);
}
// implement MapProxy for attachment
using MP3 = MapProxy<QualifiedName, const BufferInfo&>;
using MPI3 = ConstMapIterator<QualifiedName, const BufferInfo&>;
using M3 = robin_hood::unordered_flat_map<QualifiedName, BufferInfo>;
template<>
MP3::const_iterator MP3::cbegin() const noexcept {
auto& map = *reinterpret_cast<M3*>(_map);
return MP3::const_iterator(new M3::const_iterator(map.cbegin()));
}
template<>
MP3::const_iterator MP3::cend() const noexcept {
auto& map = *reinterpret_cast<M3*>(_map);
return MP3::const_iterator(new M3::const_iterator(map.cend()));
}
template<>
MP3::const_iterator MP3::find(QualifiedName key) const noexcept {
auto& map = *reinterpret_cast<M3*>(_map);
return MP3::const_iterator(new M3::const_iterator(map.find(key)));
}
template<>
size_t MP3::size() const noexcept {
auto& map = *reinterpret_cast<M3*>(_map);
return map.size();
}
template<>
MPI3::~ConstMapIterator() {
delete reinterpret_cast<M3::const_iterator*>(_iter);
}
template<>
MPI3::ConstMapIterator(const MPI3& other) noexcept {
*reinterpret_cast<M3::const_iterator*>(_iter) = *reinterpret_cast<M3::iterator*>(other._iter);
}
template<>
MPI3::reference MPI3::operator*() noexcept {
const auto& iter = *reinterpret_cast<M3::const_iterator const*>(_iter);
return { iter->first, iter->second };
}
template<>
MPI3& MPI3::operator++() noexcept {
reinterpret_cast<M3::iterator*>(_iter)->operator++();
return *this;
}
template<>
bool MPI3::operator==(MPI3 const& other) const noexcept {
return *reinterpret_cast<M3::iterator const*>(_iter) == *reinterpret_cast<M3::iterator const*>(other._iter);
}
namespace errors {
std::string format_source_location(PassInfo& pass_info) {
return fmt::format("{}({})", pass_info.pass->source.file_name(), pass_info.pass->source.line());
}
RenderGraphException make_unattached_resource_exception(PassInfo& pass_info, Resource& resource) {
const char* type = resource.type == Resource::Type::eBuffer ? "buffer" : "image";
std::string message =
fmt::format("{}: Pass <{}> references {} <{}>, which was never attached.\n(did you forget an attach_* call?).",
format_source_location(pass_info),
pass_info.pass->name.c_str(),
type,
resource.name.name.c_str());
return RenderGraphException(std::move(message));
}
RenderGraphException make_cbuf_references_unknown_resource(PassInfo& pass_info, Resource::Type res_type, Name name) {
const char* type = res_type == Resource::Type::eBuffer ? "buffer" : "image";
std::string message = fmt::format("{}: Pass <{}> has attempted to reference {} <{}>, but this name is not known to the rendergraph.",
format_source_location(pass_info),
pass_info.pass->name.c_str(),
type,
name.c_str());
return RenderGraphException(std::move(message));
}
RenderGraphException make_cbuf_references_undeclared_resource(PassInfo& pass_info, Resource::Type res_type, Name name) {
const char* type = res_type == Resource::Type::eBuffer ? "buffer" : "image";
std::string message = fmt::format("{}: In pass <{}>, attempted to bind {} <{}>, but this pass did not declare this name for use.",
format_source_location(pass_info),
pass_info.pass->name.c_str(),
type,
name.c_str());
return RenderGraphException(std::move(message));
}
} // namespace errors
} // namespace vuk
<file_sep>#include "vuk/CommandBuffer.hpp"
#include "RenderGraphUtil.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/Context.hpp"
#include "vuk/RenderGraph.hpp"
#include <cmath>
#define VUK_EARLY_RET() \
if (!current_error) { \
return *this; \
}
// hand-inlined versions of the most common bitset ops, because if these are not inlined, the overhead is terrible
#define VUK_SB_SET(bitset, pos, value) \
if constexpr (decltype(bitset)::n_words == 1) { \
if (value) { \
bitset.words[0] |= 1ULL << pos; \
} else { \
bitset.words[0] &= ~(1ULL << pos); \
} \
} else { \
bitset.set(pos, value); \
}
#define VUK_SB_COUNT(bitset, dst) \
if constexpr (decltype(bitset)::n_words == 1) { \
using T = uint64_t; \
uint64_t v = bitset.words[0]; \
v = v - ((v >> 1) & (T) ~(T)0 / 3); \
v = (v & (T) ~(T)0 / 15 * 3) + ((v >> 2) & (T) ~(T)0 / 15 * 3); \
v = (v + (v >> 4)) & (T) ~(T)0 / 255 * 15; \
dst = (T)(v * ((T) ~(T)0 / 255)) >> (sizeof(T) - 1) * CHAR_BIT; \
} else { \
dst = bitset.count(); \
}
#define VUK_SB_TEST(bitset, pos, dst) \
if constexpr (decltype(bitset)::n_words == 1) { \
dst = bitset.words[0] & 1ULL << pos; \
} else { \
dst = bitset.test(pos); \
}
namespace vuk {
uint32_t Ignore::to_size() {
if (bytes != 0)
return bytes;
return format_to_texel_block_size(format);
}
FormatOrIgnore::FormatOrIgnore(Format format) : ignore(false), format(format), size(format_to_texel_block_size(format)) {}
FormatOrIgnore::FormatOrIgnore(Ignore ign) : ignore(true), format(ign.format), size(ign.to_size()) {}
// for rendergraph
CommandBuffer::CommandBuffer(ExecutableRenderGraph& rg, Context& ctx, Allocator& allocator, VkCommandBuffer cb) :
rg(&rg),
ctx(ctx),
allocator(&allocator),
command_buffer(cb),
ds_strategy_flags(ctx.default_descriptor_set_strategy) {}
CommandBuffer::CommandBuffer(ExecutableRenderGraph& rg, Context& ctx, Allocator& allocator, VkCommandBuffer cb, std::optional<RenderPassInfo> ongoing) :
rg(&rg),
ctx(ctx),
allocator(&allocator),
command_buffer(cb),
ongoing_render_pass(ongoing),
ds_strategy_flags(ctx.default_descriptor_set_strategy) {}
const CommandBuffer::RenderPassInfo& CommandBuffer::get_ongoing_render_pass() const {
return ongoing_render_pass.value();
}
Result<Buffer> CommandBuffer::get_resource_buffer(Name n) const {
assert(rg);
auto res = rg->get_resource_buffer(NameReference::direct(n), current_pass);
if (!res) {
return { expected_error, res.error() };
}
return { expected_value, res->buffer };
}
Result<Buffer> CommandBuffer::get_resource_buffer(const NameReference& n) const {
assert(rg);
auto res = rg->get_resource_buffer(n, current_pass);
if (!res) {
return { expected_error, res.error() };
}
return { expected_value, res->buffer };
}
Result<Image> CommandBuffer::get_resource_image(Name n) const {
assert(rg);
auto res = rg->get_resource_image(NameReference::direct(n), current_pass);
if (!res) {
return { expected_error, res.error() };
}
return { expected_value, res->attachment.image };
}
Result<ImageView> CommandBuffer::get_resource_image_view(Name n) const {
assert(rg);
auto res = rg->get_resource_image(NameReference::direct(n), current_pass);
if (!res) {
return { expected_error, res.error() };
}
return { expected_value, res->attachment.image_view };
}
Result<ImageAttachment> CommandBuffer::get_resource_image_attachment(Name n) const {
assert(rg);
auto res = rg->get_resource_image(NameReference::direct(n), current_pass);
if (!res) {
return { expected_error, res.error() };
}
return { expected_value, res->attachment };
}
Result<ImageAttachment> CommandBuffer::get_resource_image_attachment(const NameReference& n) const {
assert(rg);
auto res = rg->get_resource_image(n, current_pass);
if (!res) {
return { expected_error, res.error() };
}
return { expected_value, res->attachment };
}
CommandBuffer& CommandBuffer::set_descriptor_set_strategy(DescriptorSetStrategyFlags ds_strategy_flags) {
this->ds_strategy_flags = ds_strategy_flags;
return *this;
}
CommandBuffer& CommandBuffer::set_dynamic_state(DynamicStateFlags flags) {
VUK_EARLY_RET();
// determine which states change to dynamic now - those states need to be flushed into the command buffer
DynamicStateFlags not_enabled = DynamicStateFlags{ ~dynamic_state_flags.m_mask }; // has invalid bits, but doesn't matter
auto to_dynamic = not_enabled & flags;
if (to_dynamic & DynamicStateFlagBits::eViewport && viewports.size() > 0) {
ctx.vkCmdSetViewport(command_buffer, 0, (uint32_t)viewports.size(), viewports.data());
}
if (to_dynamic & DynamicStateFlagBits::eScissor && scissors.size() > 0) {
ctx.vkCmdSetScissor(command_buffer, 0, (uint32_t)scissors.size(), scissors.data());
}
if (to_dynamic & DynamicStateFlagBits::eLineWidth) {
ctx.vkCmdSetLineWidth(command_buffer, line_width);
}
if (to_dynamic & DynamicStateFlagBits::eDepthBias && rasterization_state) {
ctx.vkCmdSetDepthBias(
command_buffer, rasterization_state->depthBiasConstantFactor, rasterization_state->depthBiasClamp, rasterization_state->depthBiasSlopeFactor);
}
if (to_dynamic & DynamicStateFlagBits::eBlendConstants && blend_constants) {
ctx.vkCmdSetBlendConstants(command_buffer, blend_constants.value().data());
}
if (to_dynamic & DynamicStateFlagBits::eDepthBounds && depth_stencil_state) {
ctx.vkCmdSetDepthBounds(command_buffer, depth_stencil_state->minDepthBounds, depth_stencil_state->maxDepthBounds);
}
dynamic_state_flags = flags;
return *this;
}
CommandBuffer& CommandBuffer::set_viewport(unsigned index, Viewport vp) {
VUK_EARLY_RET();
if (viewports.size() < (index + 1)) {
assert(index + 1 <= VUK_MAX_VIEWPORTS);
viewports.resize(index + 1);
}
viewports[index] = vp;
if (dynamic_state_flags & DynamicStateFlagBits::eViewport) {
ctx.vkCmdSetViewport(command_buffer, index, 1, &viewports[index]);
}
return *this;
}
CommandBuffer& CommandBuffer::set_viewport(unsigned index, Rect2D area, float min_depth, float max_depth) {
VUK_EARLY_RET();
Viewport vp;
if (area.sizing == Sizing::eAbsolute) {
vp.x = (float)area.offset.x;
vp.y = (float)area.offset.y;
vp.width = (float)area.extent.width;
vp.height = (float)area.extent.height;
vp.minDepth = min_depth;
vp.maxDepth = max_depth;
} else {
assert(ongoing_render_pass);
auto fb_dimensions = ongoing_render_pass->extent;
vp.x = area._relative.x * fb_dimensions.width;
vp.height = area._relative.height * fb_dimensions.height;
vp.y = area._relative.y * fb_dimensions.height;
vp.width = area._relative.width * fb_dimensions.width;
vp.minDepth = min_depth;
vp.maxDepth = max_depth;
}
return set_viewport(index, vp);
}
CommandBuffer& CommandBuffer::set_scissor(unsigned index, Rect2D area) {
VUK_EARLY_RET();
VkRect2D vp;
if (area.sizing == Sizing::eAbsolute) {
vp = { area.offset, area.extent };
} else {
assert(ongoing_render_pass);
auto fb_dimensions = ongoing_render_pass->extent;
vp.offset.x = static_cast<int32_t>(area._relative.x * fb_dimensions.width);
vp.offset.y = static_cast<int32_t>(area._relative.y * fb_dimensions.height);
vp.extent.width = static_cast<int32_t>(area._relative.width * fb_dimensions.width);
vp.extent.height = static_cast<int32_t>(area._relative.height * fb_dimensions.height);
}
if (scissors.size() < (index + 1)) {
assert(index + 1 <= VUK_MAX_SCISSORS);
scissors.resize(index + 1);
}
scissors[index] = vp;
if (dynamic_state_flags & DynamicStateFlagBits::eScissor) {
ctx.vkCmdSetScissor(command_buffer, index, 1, &scissors[index]);
}
return *this;
}
CommandBuffer& CommandBuffer::set_rasterization(PipelineRasterizationStateCreateInfo state) {
VUK_EARLY_RET();
rasterization_state = state;
if (state.depthBiasEnable && (dynamic_state_flags & DynamicStateFlagBits::eDepthBias)) {
ctx.vkCmdSetDepthBias(command_buffer, state.depthBiasConstantFactor, state.depthBiasClamp, state.depthBiasSlopeFactor);
}
if (state.lineWidth != line_width && (dynamic_state_flags & DynamicStateFlagBits::eLineWidth)) {
ctx.vkCmdSetLineWidth(command_buffer, state.lineWidth);
}
return *this;
}
CommandBuffer& CommandBuffer::set_depth_stencil(PipelineDepthStencilStateCreateInfo state) {
VUK_EARLY_RET();
depth_stencil_state = state;
if (state.depthBoundsTestEnable && (dynamic_state_flags & DynamicStateFlagBits::eDepthBounds)) {
ctx.vkCmdSetDepthBounds(command_buffer, state.minDepthBounds, state.maxDepthBounds);
}
return *this;
}
CommandBuffer& CommandBuffer::set_conservative(PipelineRasterizationConservativeStateCreateInfo state) {
VUK_EARLY_RET();
conservative_state = state;
return *this;
}
PipelineColorBlendAttachmentState blend_preset_to_pcba(BlendPreset preset) {
PipelineColorBlendAttachmentState pcba;
switch (preset) {
case BlendPreset::eAlphaBlend:
pcba.blendEnable = true;
pcba.srcColorBlendFactor = BlendFactor::eSrcAlpha;
pcba.dstColorBlendFactor = BlendFactor::eOneMinusSrcAlpha;
pcba.colorBlendOp = BlendOp::eAdd;
pcba.srcAlphaBlendFactor = BlendFactor::eOne;
pcba.dstAlphaBlendFactor = BlendFactor::eOneMinusSrcAlpha;
pcba.alphaBlendOp = BlendOp::eAdd;
break;
case BlendPreset::eOff:
pcba.blendEnable = false;
break;
case BlendPreset::ePremultipliedAlphaBlend:
assert(0 && "NYI");
}
return pcba;
}
CommandBuffer& CommandBuffer::broadcast_color_blend(PipelineColorBlendAttachmentState state) {
VUK_EARLY_RET();
assert(ongoing_render_pass);
color_blend_attachments[0] = state;
set_color_blend_attachments.set(0, true);
broadcast_color_blend_attachment_0 = true;
return *this;
}
CommandBuffer& CommandBuffer::broadcast_color_blend(BlendPreset preset) {
VUK_EARLY_RET();
return broadcast_color_blend(blend_preset_to_pcba(preset));
}
CommandBuffer& CommandBuffer::set_color_blend(Name att, PipelineColorBlendAttachmentState state) {
VUK_EARLY_RET();
assert(ongoing_render_pass);
auto resolved_name = rg->resolve_name(att, current_pass);
auto it = std::find(ongoing_render_pass->color_attachment_names.begin(), ongoing_render_pass->color_attachment_names.end(), resolved_name);
assert(it != ongoing_render_pass->color_attachment_names.end() && "Color attachment name not found.");
auto idx = std::distance(ongoing_render_pass->color_attachment_names.begin(), it);
set_color_blend_attachments.set(idx, true);
color_blend_attachments[idx] = state;
broadcast_color_blend_attachment_0 = false;
return *this;
}
CommandBuffer& CommandBuffer::set_color_blend(Name att, BlendPreset preset) {
VUK_EARLY_RET();
return set_color_blend(att, blend_preset_to_pcba(preset));
}
CommandBuffer& CommandBuffer::set_blend_constants(std::array<float, 4> constants) {
VUK_EARLY_RET();
blend_constants = constants;
if (dynamic_state_flags & DynamicStateFlagBits::eBlendConstants) {
ctx.vkCmdSetBlendConstants(command_buffer, constants.data());
}
return *this;
}
CommandBuffer& CommandBuffer::bind_graphics_pipeline(PipelineBaseInfo* pi) {
VUK_EARLY_RET();
assert(ongoing_render_pass);
next_pipeline = pi;
return *this;
}
CommandBuffer& CommandBuffer::bind_graphics_pipeline(Name p) {
VUK_EARLY_RET();
return bind_graphics_pipeline(ctx.get_named_pipeline(p));
}
CommandBuffer& CommandBuffer::bind_compute_pipeline(PipelineBaseInfo* gpci) {
VUK_EARLY_RET();
assert(!ongoing_render_pass);
next_compute_pipeline = gpci;
return *this;
}
CommandBuffer& CommandBuffer::bind_compute_pipeline(Name p) {
VUK_EARLY_RET();
return bind_compute_pipeline(ctx.get_named_pipeline(p));
}
CommandBuffer& CommandBuffer::bind_ray_tracing_pipeline(PipelineBaseInfo* gpci) {
VUK_EARLY_RET();
assert(!ongoing_render_pass);
next_ray_tracing_pipeline = gpci;
return *this;
}
CommandBuffer& CommandBuffer::bind_ray_tracing_pipeline(Name p) {
VUK_EARLY_RET();
return bind_ray_tracing_pipeline(ctx.get_named_pipeline(p));
}
CommandBuffer& CommandBuffer::bind_vertex_buffer(unsigned binding, const Buffer& buf, unsigned first_attribute, Packed format) {
VUK_EARLY_RET();
assert(binding < VUK_MAX_ATTRIBUTES && "Vertex buffer binding must be smaller than VUK_MAX_ATTRIBUTES.");
uint32_t location = first_attribute;
uint32_t offset = 0;
for (auto& f : format.list) {
if (f.ignore) {
offset += f.size;
} else {
VertexInputAttributeDescription viad;
viad.binding = binding;
viad.format = f.format;
viad.location = location;
viad.offset = offset;
attribute_descriptions[viad.location] = viad;
VUK_SB_SET(set_attribute_descriptions, viad.location, true);
offset += f.size;
location++;
}
}
VkVertexInputBindingDescription vibd;
vibd.binding = binding;
vibd.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
vibd.stride = offset;
binding_descriptions[binding] = vibd;
VUK_SB_SET(set_binding_descriptions, binding, true);
if (buf.buffer) {
ctx.vkCmdBindVertexBuffers(command_buffer, binding, 1, &buf.buffer, &buf.offset);
}
return *this;
}
CommandBuffer& CommandBuffer::bind_vertex_buffer(unsigned binding, Name resource_name, unsigned first_location, Packed format_list) {
VUK_EARLY_RET();
auto res = rg->get_resource_buffer(NameReference::direct(resource_name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
return bind_vertex_buffer(binding, res->buffer, first_location, format_list);
}
CommandBuffer& CommandBuffer::bind_vertex_buffer(unsigned binding, const Buffer& buf, std::span<VertexInputAttributeDescription> viads, uint32_t stride) {
VUK_EARLY_RET();
assert(binding < VUK_MAX_ATTRIBUTES && "Vertex buffer binding must be smaller than VUK_MAX_ATTRIBUTES.");
for (auto& viad : viads) {
attribute_descriptions[viad.location] = viad;
VUK_SB_SET(set_attribute_descriptions, viad.location, true);
}
VkVertexInputBindingDescription vibd;
vibd.binding = binding;
vibd.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
vibd.stride = stride;
binding_descriptions[binding] = vibd;
VUK_SB_SET(set_binding_descriptions, binding, true);
if (buf.buffer) {
ctx.vkCmdBindVertexBuffers(command_buffer, binding, 1, &buf.buffer, &buf.offset);
}
return *this;
}
CommandBuffer& CommandBuffer::bind_vertex_buffer(unsigned binding, Name resource_name, std::span<VertexInputAttributeDescription> viads, uint32_t stride) {
VUK_EARLY_RET();
auto res = rg->get_resource_buffer(NameReference::direct(resource_name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
return bind_vertex_buffer(binding, res->buffer, viads, stride);
}
CommandBuffer& CommandBuffer::bind_index_buffer(const Buffer& buf, IndexType type) {
VUK_EARLY_RET();
ctx.vkCmdBindIndexBuffer(command_buffer, buf.buffer, buf.offset, (VkIndexType)type);
return *this;
}
CommandBuffer& CommandBuffer::bind_index_buffer(Name name, IndexType type) {
VUK_EARLY_RET();
auto res = rg->get_resource_buffer(NameReference::direct(name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
return bind_index_buffer(res->buffer, type);
}
CommandBuffer& CommandBuffer::set_primitive_topology(PrimitiveTopology topo) {
VUK_EARLY_RET();
topology = topo;
return *this;
}
CommandBuffer& CommandBuffer::bind_persistent(unsigned set, PersistentDescriptorSet& pda) {
VUK_EARLY_RET();
assert(set < VUK_MAX_SETS);
persistent_sets_to_bind.set(set, true);
persistent_sets[set] = { pda.backing_set, pda.set_layout };
return *this;
}
CommandBuffer& CommandBuffer::push_constants(ShaderStageFlags stages, size_t offset, void* data, size_t size) {
VUK_EARLY_RET();
assert(offset + size < VUK_MAX_PUSHCONSTANT_SIZE);
pcrs.push_back(VkPushConstantRange{ (VkShaderStageFlags)stages, (uint32_t)offset, (uint32_t)size });
void* dst = push_constant_buffer + offset;
::memcpy(dst, data, size);
return *this;
}
CommandBuffer& CommandBuffer::specialize_constants(uint32_t constant_id, void* data, size_t size) {
VUK_EARLY_RET();
auto v = spec_map_entries.emplace(constant_id, SpecEntry{ size == sizeof(double) });
memcpy(&v.first->second.data, data, size);
return *this;
}
CommandBuffer& CommandBuffer::bind_buffer(unsigned set, unsigned binding, const Buffer& buffer) {
VUK_EARLY_RET();
assert(set < VUK_MAX_SETS);
assert(binding < VUK_MAX_BINDINGS);
sets_to_bind.set(set, true);
set_bindings[set].bindings[binding].type = DescriptorType::eUniformBuffer; // just means buffer
set_bindings[set].bindings[binding].buffer = VkDescriptorBufferInfo{ buffer.buffer, buffer.offset, buffer.size };
set_bindings[set].used.set(binding);
return *this;
}
CommandBuffer& CommandBuffer::bind_buffer(unsigned set, unsigned binding, Name name) {
VUK_EARLY_RET();
auto res = rg->get_resource_buffer(NameReference::direct(name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
return bind_buffer(set, binding, res->buffer);
}
CommandBuffer& CommandBuffer::bind_image(unsigned set, unsigned binding, Name resource_name) {
VUK_EARLY_RET();
auto res = rg->get_resource_image(NameReference::direct(resource_name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
auto res_gl = rg->is_resource_image_in_general_layout(NameReference::direct(resource_name), current_pass);
if (!res_gl) {
current_error = std::move(res);
return *this;
}
auto layout = *res_gl ? ImageLayout::eGeneral : ImageLayout::eReadOnlyOptimalKHR;
return bind_image(set, binding, res->attachment, layout);
}
CommandBuffer& CommandBuffer::bind_image(unsigned set, unsigned binding, const ImageAttachment& ia, ImageLayout layout) {
VUK_EARLY_RET();
if (ia.image_view != ImageView{}) {
bind_image(set, binding, ia.image_view, layout);
} else {
assert(ia.image);
auto res = allocate_image_view(*allocator, ia);
if (!res) {
current_error = std::move(res);
return *this;
} else {
bind_image(set, binding, **res, layout);
}
}
return *this;
}
CommandBuffer& CommandBuffer::bind_image(unsigned set, unsigned binding, ImageView image_view, ImageLayout layout) {
VUK_EARLY_RET();
assert(set < VUK_MAX_SETS);
assert(binding < VUK_MAX_BINDINGS);
assert(image_view.payload != VK_NULL_HANDLE);
sets_to_bind.set(set, true);
auto& db = set_bindings[set].bindings[binding];
// if previous descriptor was not an image, we reset the DescriptorImageInfo
if (db.type != DescriptorType::eStorageImage && db.type != DescriptorType::eSampledImage && db.type != DescriptorType::eSampler &&
db.type != DescriptorType::eCombinedImageSampler) {
db.image = { {}, {}, {} };
}
db.image.set_image_view(image_view);
db.image.dii.imageLayout = (VkImageLayout)layout;
// if it was just a sampler, we upgrade to combined (has both image and sampler) - otherwise just image
db.type = db.type == DescriptorType::eSampler ? DescriptorType::eCombinedImageSampler : DescriptorType::eSampledImage;
set_bindings[set].used.set(binding);
return *this;
}
CommandBuffer& CommandBuffer::bind_sampler(unsigned set, unsigned binding, SamplerCreateInfo sci) {
VUK_EARLY_RET();
assert(set < VUK_MAX_SETS);
assert(binding < VUK_MAX_BINDINGS);
sets_to_bind.set(set, true);
auto& db = set_bindings[set].bindings[binding];
// if previous descriptor was not an image, we reset the DescriptorImageInfo
if (db.type != DescriptorType::eStorageImage && db.type != DescriptorType::eSampledImage && db.type != DescriptorType::eSampler &&
db.type != DescriptorType::eCombinedImageSampler) {
db.image = { {}, {}, {} };
}
db.image.set_sampler(ctx.acquire_sampler(sci, ctx.get_frame_count()));
// if it was just an image, we upgrade to combined (has both image and sampler) - otherwise just sampler
db.type = db.type == DescriptorType::eSampledImage ? DescriptorType::eCombinedImageSampler : DescriptorType::eSampler;
set_bindings[set].used.set(binding);
return *this;
}
void* CommandBuffer::_map_scratch_buffer(unsigned set, unsigned binding, size_t size) {
if (!current_error) {
return nullptr;
}
auto res = allocate_buffer(*allocator, { MemoryUsage::eCPUtoGPU, size, 1 });
if (!res) {
current_error = std::move(res);
return nullptr;
} else {
auto& buf = res->get();
bind_buffer(set, binding, buf);
return buf.mapped_ptr;
}
}
CommandBuffer& CommandBuffer::bind_acceleration_structure(unsigned set, unsigned binding, VkAccelerationStructureKHR tlas) {
VUK_EARLY_RET();
assert(set < VUK_MAX_SETS);
assert(binding < VUK_MAX_BINDINGS);
sets_to_bind.set(set, true);
auto& db = set_bindings[set].bindings[binding];
db.as.as = tlas;
db.as.wds.accelerationStructureCount = 1;
db.type = DescriptorType::eAccelerationStructureKHR;
set_bindings[set].used.set(binding);
return *this;
}
CommandBuffer& CommandBuffer::draw(size_t vertex_count, size_t instance_count, size_t first_vertex, size_t first_instance) {
VUK_EARLY_RET();
if (!_bind_graphics_pipeline_state()) {
return *this;
}
ctx.vkCmdDraw(command_buffer, (uint32_t)vertex_count, (uint32_t)instance_count, (uint32_t)first_vertex, (uint32_t)first_instance);
return *this;
}
CommandBuffer& CommandBuffer::draw_indexed(size_t index_count, size_t instance_count, size_t first_index, int32_t vertex_offset, size_t first_instance) {
VUK_EARLY_RET();
if (!_bind_graphics_pipeline_state()) {
return *this;
}
ctx.vkCmdDrawIndexed(command_buffer, (uint32_t)index_count, (uint32_t)instance_count, (uint32_t)first_index, vertex_offset, (uint32_t)first_instance);
return *this;
}
CommandBuffer& CommandBuffer::draw_indexed_indirect(size_t command_count, const Buffer& indirect_buffer) {
VUK_EARLY_RET();
if (!_bind_graphics_pipeline_state()) {
return *this;
}
ctx.vkCmdDrawIndexedIndirect(
command_buffer, indirect_buffer.buffer, (uint32_t)indirect_buffer.offset, (uint32_t)command_count, sizeof(DrawIndexedIndirectCommand));
return *this;
}
CommandBuffer& CommandBuffer::draw_indexed_indirect(size_t command_count, Name resource_name) {
VUK_EARLY_RET();
auto res = rg->get_resource_buffer(NameReference::direct(resource_name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
return draw_indexed_indirect(command_count, res->buffer);
}
CommandBuffer& CommandBuffer::draw_indexed_indirect(std::span<DrawIndexedIndirectCommand> cmds) {
VUK_EARLY_RET();
if (!_bind_graphics_pipeline_state()) {
return *this;
}
auto res = allocate_buffer(*allocator, { MemoryUsage::eCPUtoGPU, cmds.size_bytes(), 1 });
if (!res) {
current_error = std::move(res);
return *this;
}
auto& buf = *res;
memcpy(buf->mapped_ptr, cmds.data(), cmds.size_bytes());
ctx.vkCmdDrawIndexedIndirect(command_buffer, buf->buffer, (uint32_t)buf->offset, (uint32_t)cmds.size(), sizeof(DrawIndexedIndirectCommand));
return *this;
}
CommandBuffer& CommandBuffer::draw_indexed_indirect_count(size_t max_draw_count, const Buffer& indirect_buffer, const Buffer& count_buffer) {
VUK_EARLY_RET();
if (!_bind_graphics_pipeline_state()) {
return *this;
}
ctx.vkCmdDrawIndexedIndirectCount(command_buffer,
indirect_buffer.buffer,
indirect_buffer.offset,
count_buffer.buffer,
count_buffer.offset,
(uint32_t)max_draw_count,
sizeof(DrawIndexedIndirectCommand));
return *this;
}
CommandBuffer& CommandBuffer::draw_indexed_indirect_count(size_t max_command_count, Name indirect_resource_name, Name count_resource_name) {
VUK_EARLY_RET();
auto res = rg->get_resource_buffer(NameReference::direct(indirect_resource_name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
auto count_res = rg->get_resource_buffer(NameReference::direct(count_resource_name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
return draw_indexed_indirect_count(max_command_count, res->buffer, count_res->buffer);
}
CommandBuffer& CommandBuffer::dispatch(size_t size_x, size_t size_y, size_t size_z) {
VUK_EARLY_RET();
if (!_bind_compute_pipeline_state()) {
return *this;
}
ctx.vkCmdDispatch(command_buffer, (uint32_t)size_x, (uint32_t)size_y, (uint32_t)size_z);
return *this;
}
CommandBuffer& CommandBuffer::dispatch_invocations(size_t invocation_count_x, size_t invocation_count_y, size_t invocation_count_z) {
VUK_EARLY_RET();
if (!_bind_compute_pipeline_state()) {
return *this;
}
auto local_size = current_compute_pipeline->local_size;
// integer div ceil
uint32_t x = (uint32_t)(invocation_count_x + local_size[0] - 1) / local_size[0];
uint32_t y = (uint32_t)(invocation_count_y + local_size[1] - 1) / local_size[1];
uint32_t z = (uint32_t)(invocation_count_z + local_size[2] - 1) / local_size[2];
ctx.vkCmdDispatch(command_buffer, x, y, z);
return *this;
}
CommandBuffer& CommandBuffer::dispatch_invocations_per_pixel(Name name,
float invocations_per_pixel_scale_x,
float invocations_per_pixel_scale_y,
float invocations_per_pixel_scale_z) {
auto extent = get_resource_image_attachment(name).value().extent.extent;
return dispatch_invocations((uint32_t)std::ceil(invocations_per_pixel_scale_x * extent.width),
(uint32_t)std::ceil(invocations_per_pixel_scale_y * extent.height),
(uint32_t)std::ceil(invocations_per_pixel_scale_z * extent.depth));
}
CommandBuffer& CommandBuffer::dispatch_invocations_per_pixel(ImageAttachment& ia,
float invocations_per_pixel_scale_x,
float invocations_per_pixel_scale_y,
float invocations_per_pixel_scale_z) {
auto extent = ia.extent.extent;
return dispatch_invocations((uint32_t)std::ceil(invocations_per_pixel_scale_x * extent.width),
(uint32_t)std::ceil(invocations_per_pixel_scale_y * extent.height),
(uint32_t)std::ceil(invocations_per_pixel_scale_z * extent.depth));
}
CommandBuffer& CommandBuffer::dispatch_invocations_per_element(Name name, size_t element_size, float invocations_per_element_scale) {
auto count = (uint32_t)std::ceil(invocations_per_element_scale * idivceil(get_resource_buffer(name).value().size, element_size));
return dispatch_invocations(count, 1, 1);
}
CommandBuffer& CommandBuffer::dispatch_invocations_per_element(Buffer& buffer, size_t element_size, float invocations_per_element_scale) {
auto count = (uint32_t)std::ceil(invocations_per_element_scale * idivceil(buffer.size, element_size));
return dispatch_invocations(count, 1, 1);
}
CommandBuffer& CommandBuffer::dispatch_indirect(const Buffer& indirect_buffer) {
VUK_EARLY_RET();
if (!_bind_compute_pipeline_state()) {
return *this;
}
ctx.vkCmdDispatchIndirect(command_buffer, indirect_buffer.buffer, indirect_buffer.offset);
return *this;
}
CommandBuffer& CommandBuffer::dispatch_indirect(Name indirect_resource_name) {
VUK_EARLY_RET();
auto res = rg->get_resource_buffer(NameReference::direct(indirect_resource_name), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
return dispatch_indirect(res->buffer);
}
CommandBuffer& CommandBuffer::trace_rays(size_t size_x, size_t size_y, size_t size_z) {
VUK_EARLY_RET();
if (!_bind_ray_tracing_pipeline_state()) {
return *this;
}
auto& pipe = *current_ray_tracing_pipeline;
ctx.vkCmdTraceRaysKHR(
command_buffer, &pipe.rgen_region, &pipe.miss_region, &pipe.hit_region, &pipe.call_region, (uint32_t)size_x, (uint32_t)size_y, (uint32_t)size_z);
return *this;
}
CommandBuffer& CommandBuffer::clear_image(Name src, Clear c) {
VUK_EARLY_RET();
assert(rg);
auto res = rg->get_resource_image(NameReference::direct(src), current_pass);
if (!res) {
current_error = std::move(res);
return *this;
}
auto res_gl = rg->is_resource_image_in_general_layout(NameReference::direct(src), current_pass);
if (!res_gl) {
current_error = std::move(res_gl);
return *this;
}
auto layout = *res_gl ? ImageLayout::eGeneral : ImageLayout::eTransferDstOptimal;
VkImageSubresourceRange isr = {};
auto& attachment = res->attachment;
auto aspect = format_to_aspect(attachment.format);
isr.aspectMask = (VkImageAspectFlags)aspect;
isr.baseArrayLayer = attachment.base_layer;
isr.layerCount = attachment.layer_count;
isr.baseMipLevel = attachment.base_level;
isr.levelCount = attachment.level_count;
if (aspect == ImageAspectFlagBits::eColor) {
ctx.vkCmdClearColorImage(command_buffer, attachment.image.image, (VkImageLayout)layout, &c.c.color, 1, &isr);
} else if (aspect & (ImageAspectFlagBits::eDepth | ImageAspectFlagBits::eStencil)) {
ctx.vkCmdClearDepthStencilImage(command_buffer, attachment.image.image, (VkImageLayout)layout, &c.c.depthStencil, 1, &isr);
}
return *this;
}
CommandBuffer& CommandBuffer::resolve_image(Name src, Name dst) {
VUK_EARLY_RET();
assert(rg);
VkImageResolve ir;
auto src_res = rg->get_resource_image(NameReference::direct(src), current_pass);
if (!src_res) {
current_error = std::move(src_res);
return *this;
}
auto src_image = src_res->attachment.image;
auto dst_res = rg->get_resource_image(NameReference::direct(dst), current_pass);
if (!dst_res) {
current_error = std::move(dst_res);
return *this;
}
auto dst_image = dst_res->attachment.image;
ImageSubresourceLayers isl;
ImageAspectFlagBits aspect;
if (dst_res->attachment.format == Format::eD32Sfloat) {
aspect = ImageAspectFlagBits::eDepth;
} else {
aspect = ImageAspectFlagBits::eColor;
}
isl.aspectMask = aspect;
isl.baseArrayLayer = 0;
isl.layerCount = 1;
isl.mipLevel = 0;
ir.srcOffset = Offset3D{};
ir.srcSubresource = isl;
ir.dstOffset = Offset3D{};
ir.dstSubresource = isl;
ir.extent = static_cast<Extent3D>(src_res->attachment.extent.extent);
auto res_gl_src = rg->is_resource_image_in_general_layout(NameReference::direct(src), current_pass);
if (!res_gl_src) {
current_error = std::move(res_gl_src);
return *this;
}
auto res_gl_dst = rg->is_resource_image_in_general_layout(NameReference::direct(dst), current_pass);
if (!res_gl_dst) {
current_error = std::move(res_gl_dst);
return *this;
}
auto src_layout = *res_gl_src ? ImageLayout::eGeneral : ImageLayout::eTransferSrcOptimal;
auto dst_layout = *res_gl_dst ? ImageLayout::eGeneral : ImageLayout::eTransferDstOptimal;
ctx.vkCmdResolveImage(command_buffer, src_image.image, (VkImageLayout)src_layout, dst_image.image, (VkImageLayout)dst_layout, 1, &ir);
return *this;
}
CommandBuffer& CommandBuffer::blit_image(Name src, Name dst, ImageBlit region, Filter filter) {
VUK_EARLY_RET();
assert(rg);
auto src_res = rg->get_resource_image(NameReference::direct(src), current_pass);
if (!src_res) {
current_error = std::move(src_res);
return *this;
}
auto src_image = src_res->attachment.image;
auto dst_res = rg->get_resource_image(NameReference::direct(dst), current_pass);
if (!dst_res) {
current_error = std::move(dst_res);
return *this;
}
auto dst_image = dst_res->attachment.image;
auto res_gl_src = rg->is_resource_image_in_general_layout(NameReference::direct(src), current_pass);
if (!res_gl_src) {
current_error = std::move(res_gl_src);
return *this;
}
auto res_gl_dst = rg->is_resource_image_in_general_layout(NameReference::direct(dst), current_pass);
if (!res_gl_dst) {
current_error = std::move(res_gl_dst);
return *this;
}
auto src_layout = *res_gl_src ? ImageLayout::eGeneral : ImageLayout::eTransferSrcOptimal;
auto dst_layout = *res_gl_dst ? ImageLayout::eGeneral : ImageLayout::eTransferDstOptimal;
ctx.vkCmdBlitImage(
command_buffer, src_image.image, (VkImageLayout)src_layout, dst_image.image, (VkImageLayout)dst_layout, 1, (VkImageBlit*)®ion, (VkFilter)filter);
return *this;
}
CommandBuffer& CommandBuffer::copy_buffer_to_image(Name src, Name dst, BufferImageCopy bic) {
VUK_EARLY_RET();
assert(rg);
auto src_res = rg->get_resource_buffer(NameReference::direct(src), current_pass);
if (!src_res) {
current_error = std::move(src_res);
return *this;
}
auto src_bbuf = src_res->buffer;
bic.bufferOffset += src_bbuf.offset;
auto dst_res = rg->get_resource_image(NameReference::direct(dst), current_pass);
if (!dst_res) {
current_error = std::move(dst_res);
return *this;
}
auto dst_image = dst_res->attachment.image;
auto res_gl = rg->is_resource_image_in_general_layout(NameReference::direct(dst), current_pass);
if (!res_gl) {
current_error = std::move(res_gl);
return *this;
}
auto dst_layout = *res_gl ? ImageLayout::eGeneral : ImageLayout::eTransferDstOptimal;
ctx.vkCmdCopyBufferToImage(command_buffer, src_bbuf.buffer, dst_image.image, (VkImageLayout)dst_layout, 1, (VkBufferImageCopy*)&bic);
return *this;
}
CommandBuffer& CommandBuffer::copy_image_to_buffer(Name src, Name dst, BufferImageCopy bic) {
VUK_EARLY_RET();
assert(rg);
auto src_res = rg->get_resource_image(NameReference::direct(src), current_pass);
if (!src_res) {
current_error = std::move(src_res);
return *this;
}
auto src_image = src_res->attachment.image;
auto dst_res = rg->get_resource_buffer(NameReference::direct(dst), current_pass);
if (!dst_res) {
current_error = std::move(dst_res);
return *this;
}
auto dst_bbuf = dst_res->buffer;
bic.bufferOffset += dst_bbuf.offset;
auto res_gl = rg->is_resource_image_in_general_layout(NameReference::direct(src), current_pass);
if (!res_gl) {
current_error = std::move(res_gl);
return *this;
}
auto src_layout = *res_gl ? ImageLayout::eGeneral : ImageLayout::eTransferSrcOptimal;
ctx.vkCmdCopyImageToBuffer(command_buffer, src_image.image, (VkImageLayout)src_layout, dst_bbuf.buffer, 1, (VkBufferImageCopy*)&bic);
return *this;
}
CommandBuffer& CommandBuffer::copy_buffer(Name src, Name dst, size_t size) {
VUK_EARLY_RET();
assert(rg);
auto src_res = rg->get_resource_buffer(NameReference::direct(src), current_pass);
if (!src_res) {
current_error = std::move(src_res);
return *this;
}
auto src_bbuf = src_res->buffer;
auto dst_res = rg->get_resource_buffer(NameReference::direct(dst), current_pass);
if (!dst_res) {
current_error = std::move(dst_res);
return *this;
}
auto dst_bbuf = dst_res->buffer;
return copy_buffer(src_bbuf, dst_bbuf, size);
}
CommandBuffer& CommandBuffer::copy_buffer(const Buffer& src, const Buffer& dst, size_t size) {
VUK_EARLY_RET();
assert(src.size == dst.size);
if (src.buffer == dst.buffer) {
bool overlap_a = src.offset > dst.offset && src.offset < (dst.offset + dst.size);
bool overlap_b = dst.offset > src.offset && dst.offset < (src.offset + src.size);
assert(!overlap_a && !overlap_b);
}
VkBufferCopy bc{};
bc.srcOffset += src.offset;
bc.dstOffset += dst.offset;
bc.size = size == VK_WHOLE_SIZE ? src.size : size;
ctx.vkCmdCopyBuffer(command_buffer, src.buffer, dst.buffer, 1, &bc);
return *this;
}
CommandBuffer& CommandBuffer::fill_buffer(Name dst, size_t size, uint32_t data) {
VUK_EARLY_RET();
assert(rg);
auto dst_res = rg->get_resource_buffer(NameReference::direct(dst), current_pass);
if (!dst_res) {
current_error = std::move(dst_res);
return *this;
}
auto dst_bbuf = dst_res->buffer;
return fill_buffer(dst_bbuf, size, data);
}
CommandBuffer& CommandBuffer::fill_buffer(const Buffer& dst, size_t size, uint32_t data) {
ctx.vkCmdFillBuffer(command_buffer, dst.buffer, dst.offset, size, data);
return *this;
}
CommandBuffer& CommandBuffer::update_buffer(Name dst, size_t size, void* data) {
VUK_EARLY_RET();
assert(rg);
auto dst_res = rg->get_resource_buffer(NameReference::direct(dst), current_pass);
if (!dst_res) {
current_error = std::move(dst_res);
return *this;
}
auto dst_bbuf = dst_res->buffer;
return update_buffer(dst_bbuf, size, data);
}
CommandBuffer& CommandBuffer::update_buffer(const Buffer& dst, size_t size, void* data) {
ctx.vkCmdUpdateBuffer(command_buffer, dst.buffer, dst.offset, size, data);
return *this;
}
CommandBuffer& CommandBuffer::memory_barrier(Access src_access, Access dst_access) {
VkMemoryBarrier mb{ .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER };
auto src_use = to_use(src_access, DomainFlagBits::eAny);
auto dst_use = to_use(dst_access, DomainFlagBits::eAny);
mb.srcAccessMask = is_read_access(src_use) ? 0 : (VkAccessFlags)src_use.access;
mb.dstAccessMask = (VkAccessFlags)dst_use.access;
ctx.vkCmdPipelineBarrier(command_buffer, (VkPipelineStageFlags)src_use.stages, (VkPipelineStageFlags)dst_use.stages, {}, 1, &mb, 0, nullptr, 0, nullptr);
return *this;
}
CommandBuffer& CommandBuffer::image_barrier(Name src, vuk::Access src_acc, vuk::Access dst_acc, uint32_t mip_level, uint32_t level_count) {
VUK_EARLY_RET();
assert(rg);
auto src_res = rg->get_resource_image(NameReference::direct(src), current_pass);
if (!src_res) {
current_error = std::move(src_res);
return *this;
}
auto src_image = src_res->attachment.image;
// TODO: fill these out from attachment
VkImageSubresourceRange isr = {};
isr.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
isr.baseArrayLayer = 0;
isr.layerCount = VK_REMAINING_ARRAY_LAYERS;
isr.baseMipLevel = mip_level;
isr.levelCount = level_count;
VkImageMemoryBarrier imb{ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
imb.image = src_image.image;
auto src_use = to_use(src_acc, DomainFlagBits::eAny);
auto dst_use = to_use(dst_acc, DomainFlagBits::eAny);
imb.srcAccessMask = (VkAccessFlags)src_use.access;
imb.dstAccessMask = (VkAccessFlags)dst_use.access;
auto res_gl = rg->is_resource_image_in_general_layout(NameReference::direct(src), current_pass);
if (!res_gl) {
current_error = std::move(res_gl);
return *this;
}
if (*res_gl) {
imb.oldLayout = imb.newLayout = VK_IMAGE_LAYOUT_GENERAL;
} else {
imb.oldLayout = (VkImageLayout)src_use.layout;
imb.newLayout = (VkImageLayout)dst_use.layout;
}
imb.subresourceRange = isr;
ctx.vkCmdPipelineBarrier(command_buffer, (VkPipelineStageFlags)src_use.stages, (VkPipelineStageFlags)dst_use.stages, {}, 0, nullptr, 0, nullptr, 1, &imb);
return *this;
}
CommandBuffer& CommandBuffer::write_timestamp(Query q, PipelineStageFlagBits stage) {
VUK_EARLY_RET();
vuk::TimestampQuery tsq;
vuk::TimestampQueryCreateInfo ci{ .query = q };
auto res = allocator->allocate_timestamp_queries(std::span{ &tsq, 1 }, std::span{ &ci, 1 });
if (!res) {
current_error = std::move(res);
return *this;
}
ctx.vkCmdWriteTimestamp(command_buffer, (VkPipelineStageFlagBits)stage, tsq.pool, tsq.id);
return *this;
}
CommandBuffer& CommandBuffer::build_acceleration_structures(uint32_t info_count,
const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) {
VUK_EARLY_RET();
ctx.vkCmdBuildAccelerationStructuresKHR(command_buffer, info_count, pInfos, ppBuildRangeInfos);
return *this;
}
Result<void> CommandBuffer::result() {
return std::move(current_error);
}
VkCommandBuffer CommandBuffer::bind_compute_state() {
auto result = _bind_compute_pipeline_state();
assert(result);
return command_buffer;
}
VkCommandBuffer CommandBuffer::bind_graphics_state() {
auto result = _bind_graphics_pipeline_state();
assert(result);
return command_buffer;
}
VkCommandBuffer CommandBuffer::bind_ray_tracing_state() {
auto result = _bind_ray_tracing_pipeline_state();
assert(result);
return command_buffer;
}
bool CommandBuffer::_bind_state(PipeType pipe_type) {
VkPipelineLayout current_layout;
switch (pipe_type) {
case PipeType::eGraphics:
current_layout = current_graphics_pipeline->pipeline_layout;
break;
case PipeType::eCompute:
current_layout = current_compute_pipeline->pipeline_layout;
break;
case PipeType::eRayTracing:
current_layout = current_ray_tracing_pipeline->pipeline_layout;
break;
}
VkPipelineBindPoint bind_point;
switch (pipe_type) {
case PipeType::eGraphics:
bind_point = VK_PIPELINE_BIND_POINT_GRAPHICS;
break;
case PipeType::eCompute:
bind_point = VK_PIPELINE_BIND_POINT_COMPUTE;
break;
case PipeType::eRayTracing:
bind_point = VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR;
break;
}
for (auto& pcr : pcrs) {
void* data = push_constant_buffer + pcr.offset;
ctx.vkCmdPushConstants(command_buffer, current_layout, pcr.stageFlags, pcr.offset, pcr.size, data);
}
pcrs.clear();
auto sets_mask = sets_to_bind.to_ulong();
auto persistent_sets_mask = persistent_sets_to_bind.to_ulong();
uint64_t highest_undisturbed_binding_required = 0;
uint64_t lowest_disturbed_binding = VUK_MAX_SETS;
for (size_t i = 0; i < VUK_MAX_SETS; i++) {
bool set_to_bind = sets_mask & (1ULL << i);
bool persistent_set_to_bind = persistent_sets_mask & (1ULL << i);
VkDescriptorSetLayout pipeline_set_layout;
DescriptorSetLayoutAllocInfo* ds_layout_alloc_info;
switch (pipe_type) {
case PipeType::eGraphics:
ds_layout_alloc_info = ¤t_graphics_pipeline->layout_info[i];
break;
case PipeType::eCompute:
ds_layout_alloc_info = ¤t_compute_pipeline->layout_info[i];
break;
case PipeType::eRayTracing:
ds_layout_alloc_info = ¤t_ray_tracing_pipeline->layout_info[i];
break;
}
pipeline_set_layout = ds_layout_alloc_info->layout;
// binding validation
if (pipeline_set_layout != VK_NULL_HANDLE) { // set in the layout
bool is_used;
VUK_SB_TEST(sets_used, i, is_used);
if (!is_used && !set_to_bind && !persistent_set_to_bind) { // never set in the cbuf & not requested to bind now
assert(false && "Pipeline layout contains set, but never set in CommandBuffer or disturbed by a previous set composition or binding.");
return false;
} else if (!set_to_bind && !persistent_set_to_bind) { // but not requested to bind now
// validate that current set is compatible (== same set layout)
assert(set_layouts_used[i] == pipeline_set_layout && "Previously bound set is incompatible with currently bound pipeline.");
// this set is compatible, but we require it to be undisturbed
highest_undisturbed_binding_required = std::max(highest_undisturbed_binding_required, i);
// detect if during this binding we disturb a set that we depend on
assert(highest_undisturbed_binding_required < lowest_disturbed_binding &&
"Set composition disturbs previously bound set that is not recomposed or bound for this drawcall.");
continue;
}
} else { // not set in the layout
if (!set_to_bind && !persistent_set_to_bind) { // not requested to bind now, noop
continue;
} else { // requested to bind now
assert(false && "Set layout doesn't contain set, but set in CommandBuffer.");
return false;
}
}
// if the newly bound DS has a different set layout than the previously bound set, then it disturbs all the sets at higher indices
bool is_disturbing = set_layouts_used[i] != pipeline_set_layout;
if (is_disturbing) {
lowest_disturbed_binding = std::min(lowest_disturbed_binding, i + 1);
}
switch (pipe_type) {
case PipeType::eGraphics:
set_bindings[i].layout_info = ¤t_graphics_pipeline->layout_info[i];
break;
case PipeType::eCompute:
set_bindings[i].layout_info = ¤t_compute_pipeline->layout_info[i];
break;
case PipeType::eRayTracing:
set_bindings[i].layout_info = ¤t_ray_tracing_pipeline->layout_info[i];
break;
}
if (!persistent_set_to_bind) {
std::vector<VkDescriptorSetLayoutBinding>* ppipeline_set_bindings;
DescriptorSetLayoutCreateInfo* dslci;
switch (pipe_type) {
case PipeType::eGraphics:
dslci = ¤t_graphics_pipeline->base->dslcis[i];
break;
case PipeType::eCompute:
dslci = ¤t_compute_pipeline->base->dslcis[i];
break;
case PipeType::eRayTracing:
dslci = ¤t_ray_tracing_pipeline->base->dslcis[i];
break;
}
ppipeline_set_bindings = &dslci->bindings;
auto& pipeline_set_bindings = *ppipeline_set_bindings;
auto sb = set_bindings[i].finalize(dslci->used_bindings);
for (uint64_t j = 0; j < pipeline_set_bindings.size(); j++) {
auto& pipe_binding = pipeline_set_bindings[j];
auto& cbuf_binding = sb.bindings[pipeline_set_bindings[j].binding];
auto pipe_dtype = (DescriptorType)pipe_binding.descriptorType;
auto cbuf_dtype = cbuf_binding.type;
// untyped buffer descriptor inference
if (cbuf_dtype == DescriptorType::eUniformBuffer && pipe_dtype == DescriptorType::eStorageBuffer) {
cbuf_binding.type = DescriptorType::eStorageBuffer;
continue;
}
// storage image from any image
if ((cbuf_dtype == DescriptorType::eSampledImage || cbuf_dtype == DescriptorType::eCombinedImageSampler) &&
pipe_dtype == DescriptorType::eStorageImage) {
cbuf_binding.type = DescriptorType::eStorageImage;
continue;
}
// just sampler -> fine to have image and sampler
if (cbuf_dtype == DescriptorType::eCombinedImageSampler && pipe_dtype == DescriptorType::eSampler) {
cbuf_binding.type = DescriptorType::eSampler;
continue;
}
// just image -> fine to have image and sampler
if (cbuf_dtype == DescriptorType::eCombinedImageSampler && pipe_dtype == DescriptorType::eSampledImage) {
cbuf_binding.type = DescriptorType::eSampledImage;
continue;
}
// diagnose missing sampler or image
if (cbuf_dtype == DescriptorType::eSampler && pipe_dtype == DescriptorType::eCombinedImageSampler) {
assert(false && "Descriptor is combined image-sampler, but only sampler was bound.");
return false;
}
if (cbuf_dtype == DescriptorType::eSampledImage && pipe_dtype == DescriptorType::eCombinedImageSampler) {
assert(false && "Descriptor is combined image-sampler, but only image was bound.");
return false;
}
if (pipe_dtype != cbuf_dtype) {
bool optional;
VUK_SB_TEST(dslci->optional, j, optional);
if (optional) { // this was an optional binding with a mismatched or missing bound resource -> forgo writing
VUK_SB_SET(sb.used, j, false);
} else {
if (cbuf_dtype == vuk::DescriptorType(127)) {
assert(false && "Descriptor layout contains binding that was not bound.");
} else {
assert(false && "Attempting to bind the wrong descriptor type.");
}
return false;
}
}
}
auto strategy = ds_strategy_flags.m_mask == 0 ? DescriptorSetStrategyFlagBits::eCommon : ds_strategy_flags;
Unique<DescriptorSet> ds;
if (strategy & DescriptorSetStrategyFlagBits::ePerLayout) {
if (auto ret = allocator->allocate_descriptor_sets_with_value(std::span{ &*ds, 1 }, std::span{ &sb, 1 }); !ret) {
current_error = std::move(ret);
return false;
}
} else if (strategy & DescriptorSetStrategyFlagBits::eCommon) {
if (auto ret = allocator->allocate_descriptor_sets(std::span{ &*ds, 1 }, std::span{ ds_layout_alloc_info, 1 }); !ret) {
current_error = std::move(ret);
return false;
}
auto& cinfo = sb;
auto mask = cinfo.used.to_ulong();
uint32_t leading_ones = num_leading_ones((uint32_t)mask);
VkWriteDescriptorSet writes[VUK_MAX_BINDINGS];
int j = 0;
for (uint32_t i = 0; i < leading_ones; i++, j++) {
bool used;
VUK_SB_TEST(cinfo.used, i, used);
if (!used) {
j--;
continue;
}
auto& write = writes[j];
write = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
auto& binding = cinfo.bindings[i];
write.descriptorType = DescriptorBinding::vk_descriptor_type(binding.type);
write.dstArrayElement = 0;
write.descriptorCount = 1;
write.dstBinding = i;
write.dstSet = ds->descriptor_set;
switch (binding.type) {
case DescriptorType::eUniformBuffer:
case DescriptorType::eStorageBuffer:
write.pBufferInfo = &binding.buffer;
break;
case DescriptorType::eSampledImage:
case DescriptorType::eSampler:
case DescriptorType::eCombinedImageSampler:
case DescriptorType::eStorageImage:
write.pImageInfo = &binding.image.dii;
break;
case DescriptorType::eAccelerationStructureKHR:
binding.as.wds = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR };
binding.as.wds.accelerationStructureCount = 1;
binding.as.wds.pAccelerationStructures = &binding.as.as;
write.pNext = &binding.as.wds;
break;
default:
assert(0);
}
}
ctx.vkUpdateDescriptorSets(allocator->get_context().device, j, writes, 0, nullptr);
} else {
assert(0 && "Unimplemented DS strategy");
}
ctx.vkCmdBindDescriptorSets(command_buffer, bind_point, current_layout, (uint32_t)i, 1, &ds->descriptor_set, 0, nullptr);
set_layouts_used[i] = ds->layout_info.layout;
} else {
ctx.vkCmdBindDescriptorSets(command_buffer, bind_point, current_layout, (uint32_t)i, 1, &persistent_sets[i].first, 0, nullptr);
set_layouts_used[i] = persistent_sets[i].second;
}
}
auto sets_bound = sets_to_bind | persistent_sets_to_bind; // these sets we bound freshly, valid
for (uint64_t i = lowest_disturbed_binding; i < VUK_MAX_SETS; i++) { // clear the slots where the binding was disturbed
VUK_SB_SET(sets_used, i, false);
}
sets_used = sets_used | sets_bound;
sets_to_bind.reset();
persistent_sets_to_bind.reset();
return true;
}
bool CommandBuffer::_bind_compute_pipeline_state() {
if (next_compute_pipeline) {
ComputePipelineInstanceCreateInfo pi;
pi.base = next_compute_pipeline;
bool empty = true;
unsigned offset = 0;
for (auto& sc : pi.base->reflection_info.spec_constants) {
auto it = spec_map_entries.find(sc.binding);
if (it != spec_map_entries.end()) {
auto& map_e = it->second;
unsigned size = map_e.is_double ? (unsigned)sizeof(double) : 4;
assert(pi.specialization_map_entries.size() < VUK_MAX_SPECIALIZATIONCONSTANT_RANGES);
pi.specialization_map_entries.push_back(VkSpecializationMapEntry{ sc.binding, offset, size });
assert(offset + size < VUK_MAX_SPECIALIZATIONCONSTANT_SIZE);
memcpy(pi.specialization_constant_data.data() + offset, map_e.data, size);
offset += size;
empty = false;
}
}
if (!empty) {
VkSpecializationInfo& si = pi.specialization_info;
si.pMapEntries = pi.specialization_map_entries.data();
si.mapEntryCount = (uint32_t)pi.specialization_map_entries.size();
si.pData = pi.specialization_constant_data.data();
si.dataSize = pi.specialization_constant_data.size();
pi.base->psscis[0].pSpecializationInfo = &pi.specialization_info;
}
current_compute_pipeline = ComputePipelineInfo{};
allocator->allocate_compute_pipelines(std::span{ ¤t_compute_pipeline.value(), 1 }, std::span{ &pi, 1 });
// drop pipeline immediately
allocator->deallocate(std::span{ ¤t_compute_pipeline.value(), 1 });
ctx.vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, current_compute_pipeline->pipeline);
next_compute_pipeline = nullptr;
}
return _bind_state(PipeType::eCompute);
}
template<class T>
void write(std::byte*& data_ptr, const T& data) {
memcpy(data_ptr, &data, sizeof(T));
data_ptr += sizeof(T);
};
bool CommandBuffer::_bind_graphics_pipeline_state() {
if (next_pipeline) {
GraphicsPipelineInstanceCreateInfo pi;
pi.base = next_pipeline;
pi.render_pass = ongoing_render_pass->render_pass;
pi.dynamic_state_flags = dynamic_state_flags.m_mask;
auto& records = pi.records;
if (ongoing_render_pass->subpass > 0) {
records.nonzero_subpass = true;
pi.extended_size += sizeof(uint8_t);
}
pi.topology = (VkPrimitiveTopology)topology;
pi.primitive_restart_enable = false;
// VERTEX INPUT
Bitset<VUK_MAX_ATTRIBUTES> used_bindings = {};
if (pi.base->reflection_info.attributes.size() > 0) {
records.vertex_input = true;
for (unsigned i = 0; i < pi.base->reflection_info.attributes.size(); i++) {
auto& reflected_att = pi.base->reflection_info.attributes[i];
assert(set_attribute_descriptions.test(reflected_att.location) && "Pipeline expects attribute, but was never set in command buffer.");
VUK_SB_SET(used_bindings, attribute_descriptions[reflected_att.location].binding, true);
}
pi.extended_size += (uint16_t)pi.base->reflection_info.attributes.size() * sizeof(GraphicsPipelineInstanceCreateInfo::VertexInputAttributeDescription);
pi.extended_size += sizeof(uint8_t);
uint64_t count;
VUK_SB_COUNT(used_bindings, count);
pi.extended_size += (uint16_t)count * sizeof(GraphicsPipelineInstanceCreateInfo::VertexInputBindingDescription);
}
// BLEND STATE
// attachmentCount says how many attachments
pi.attachmentCount = (uint8_t)ongoing_render_pass->color_attachments.size();
bool rasterization = ongoing_render_pass->depth_stencil_attachment || pi.attachmentCount > 0;
if (pi.attachmentCount > 0) {
uint64_t count;
VUK_SB_COUNT(set_color_blend_attachments, count);
assert(count > 0 && "If a pass has a color attachment, you must set at least one color blend state.");
records.broadcast_color_blend_attachment_0 = broadcast_color_blend_attachment_0;
if (broadcast_color_blend_attachment_0) {
bool set;
VUK_SB_TEST(set_color_blend_attachments, 0, set);
assert(set && "Broadcast turned on, but no blend state set.");
if (color_blend_attachments[0] != PipelineColorBlendAttachmentState{}) {
records.color_blend_attachments = true;
pi.extended_size += sizeof(GraphicsPipelineInstanceCreateInfo::PipelineColorBlendAttachmentState);
}
} else {
assert(count >= pi.attachmentCount &&
"If color blend state is not broadcast, you must set it for each color attachment.");
records.color_blend_attachments = true;
pi.extended_size += (uint16_t)(pi.attachmentCount * sizeof(GraphicsPipelineInstanceCreateInfo::PipelineColorBlendAttachmentState));
}
}
records.logic_op = false; // TODO: logic op unsupported
if (blend_constants && !(dynamic_state_flags & DynamicStateFlagBits::eBlendConstants)) {
records.blend_constants = true;
pi.extended_size += sizeof(float) * 4;
}
unsigned spec_const_size = 0;
Bitset<VUK_MAX_SPECIALIZATIONCONSTANT_RANGES> set_constants = {};
assert(pi.base->reflection_info.spec_constants.size() < VUK_MAX_SPECIALIZATIONCONSTANT_RANGES);
if (spec_map_entries.size() > 0 && pi.base->reflection_info.spec_constants.size() > 0) {
for (unsigned i = 0; i < pi.base->reflection_info.spec_constants.size(); i++) {
auto& sc = pi.base->reflection_info.spec_constants[i];
auto size = sc.type == Program::Type::edouble ? sizeof(double) : 4;
auto it = spec_map_entries.find(sc.binding);
if (it != spec_map_entries.end()) {
spec_const_size += (uint32_t)size;
VUK_SB_SET(set_constants, i, true);
}
}
records.specialization_constants = true;
assert(spec_const_size < VUK_MAX_SPECIALIZATIONCONSTANT_SIZE);
pi.extended_size += (uint16_t)sizeof(set_constants);
pi.extended_size += (uint16_t)spec_const_size;
}
if (rasterization) {
assert(rasterization_state && "If a pass has a depth/stencil or color attachment, you must set the rasterization state.");
pi.cullMode = (VkCullModeFlags)rasterization_state->cullMode;
PipelineRasterizationStateCreateInfo def{ .cullMode = rasterization_state->cullMode };
if (dynamic_state_flags & DynamicStateFlagBits::eDepthBias) {
def.depthBiasConstantFactor = rasterization_state->depthBiasConstantFactor;
def.depthBiasClamp = rasterization_state->depthBiasClamp;
def.depthBiasSlopeFactor = rasterization_state->depthBiasSlopeFactor;
} else {
// TODO: static depth bias unsupported
assert(rasterization_state->depthBiasConstantFactor == def.depthBiasConstantFactor);
assert(rasterization_state->depthBiasClamp == def.depthBiasClamp);
assert(rasterization_state->depthBiasSlopeFactor == def.depthBiasSlopeFactor);
}
records.depth_bias_enable = rasterization_state->depthBiasEnable; // the enable itself is not dynamic state in core
if (*rasterization_state != def) {
records.non_trivial_raster_state = true;
pi.extended_size += sizeof(GraphicsPipelineInstanceCreateInfo::RasterizationState);
}
}
if (conservative_state) {
records.conservative_rasterization_enabled = true;
pi.extended_size += sizeof(GraphicsPipelineInstanceCreateInfo::ConservativeState);
}
if (ongoing_render_pass->depth_stencil_attachment) {
assert(depth_stencil_state && "If a pass has a depth/stencil attachment, you must set the depth/stencil state.");
records.depth_stencil = true;
pi.extended_size += sizeof(GraphicsPipelineInstanceCreateInfo::Depth);
assert(depth_stencil_state->stencilTestEnable == false); // TODO: stencil unsupported
assert(depth_stencil_state->depthBoundsTestEnable == false); // TODO: depth bounds unsupported
}
if (ongoing_render_pass->samples != SampleCountFlagBits::e1) {
records.more_than_one_sample = true;
pi.extended_size += sizeof(GraphicsPipelineInstanceCreateInfo::Multisample);
}
if (rasterization) {
if (viewports.size() > 0) {
records.viewports = true;
pi.extended_size += sizeof(uint8_t);
if (!(dynamic_state_flags & DynamicStateFlagBits::eViewport)) {
pi.extended_size += (uint16_t)viewports.size() * sizeof(VkViewport);
}
} else if (!(dynamic_state_flags & DynamicStateFlagBits::eViewport)) {
assert("If a pass has a depth/stencil or color attachment, you must set at least one viewport.");
}
}
if (rasterization) {
if (scissors.size() > 0) {
records.scissors = true;
pi.extended_size += sizeof(uint8_t);
if (!(dynamic_state_flags & DynamicStateFlagBits::eScissor)) {
pi.extended_size += (uint16_t)scissors.size() * sizeof(VkRect2D);
}
} else if (!(dynamic_state_flags & DynamicStateFlagBits::eScissor)) {
assert("If a pass has a depth/stencil or color attachment, you must set at least one scissor.");
}
}
// small buffer optimization:
// if the extended data fits, then we put it inline in the key
std::byte* data_ptr;
std::byte* data_start_ptr;
if (pi.is_inline()) {
data_start_ptr = data_ptr = pi.inline_data;
} else { // otherwise we allocate
pi.extended_data = new std::byte[pi.extended_size];
data_start_ptr = data_ptr = pi.extended_data;
}
// start writing packed stream
if (ongoing_render_pass->subpass > 0) {
write<uint8_t>(data_ptr, ongoing_render_pass->subpass);
}
if (records.vertex_input) {
for (unsigned i = 0; i < pi.base->reflection_info.attributes.size(); i++) {
auto& reflected_att = pi.base->reflection_info.attributes[i];
auto& att = attribute_descriptions[reflected_att.location];
GraphicsPipelineInstanceCreateInfo::VertexInputAttributeDescription viad{
.format = att.format, .offset = att.offset, .location = (uint8_t)att.location, .binding = (uint8_t)att.binding
};
write(data_ptr, viad);
}
uint64_t count;
VUK_SB_COUNT(used_bindings, count);
write<uint8_t>(data_ptr, (uint8_t)count);
for (unsigned i = 0; i < VUK_MAX_ATTRIBUTES; i++) {
bool used;
VUK_SB_TEST(used_bindings, i, used);
if (used) {
auto& bin = binding_descriptions[i];
GraphicsPipelineInstanceCreateInfo::VertexInputBindingDescription vibd{ .stride = bin.stride,
.inputRate = (uint32_t)bin.inputRate,
.binding = (uint8_t)bin.binding };
write(data_ptr, vibd);
}
}
}
if (records.color_blend_attachments) {
uint32_t num_pcba_to_write = records.broadcast_color_blend_attachment_0 ? 1 : (uint32_t)color_blend_attachments.size();
for (uint32_t i = 0; i < num_pcba_to_write; i++) {
auto& cba = color_blend_attachments[i];
GraphicsPipelineInstanceCreateInfo::PipelineColorBlendAttachmentState pcba{ .blendEnable = cba.blendEnable,
.srcColorBlendFactor = cba.srcColorBlendFactor,
.dstColorBlendFactor = cba.dstColorBlendFactor,
.colorBlendOp = cba.colorBlendOp,
.srcAlphaBlendFactor = cba.srcAlphaBlendFactor,
.dstAlphaBlendFactor = cba.dstAlphaBlendFactor,
.alphaBlendOp = cba.alphaBlendOp,
.colorWriteMask = (uint32_t)cba.colorWriteMask };
write(data_ptr, pcba);
}
}
if (blend_constants && !(dynamic_state_flags & DynamicStateFlagBits::eBlendConstants)) {
memcpy(data_ptr, &*blend_constants, sizeof(float) * 4);
data_ptr += sizeof(float) * 4;
}
if (records.specialization_constants) {
write(data_ptr, set_constants);
for (unsigned i = 0; i < VUK_MAX_SPECIALIZATIONCONSTANT_RANGES; i++) {
bool set;
VUK_SB_TEST(set_constants, i, set);
if (set) {
auto& sc = pi.base->reflection_info.spec_constants[i];
auto size = sc.type == Program::Type::edouble ? sizeof(double) : 4;
auto& map_e = spec_map_entries.find(sc.binding)->second;
memcpy(data_ptr, map_e.data, size);
data_ptr += size;
}
}
}
if (records.non_trivial_raster_state) {
GraphicsPipelineInstanceCreateInfo::RasterizationState rs{ .depthClampEnable = (bool)rasterization_state->depthClampEnable,
.rasterizerDiscardEnable = (bool)rasterization_state->rasterizerDiscardEnable,
.polygonMode = (uint8_t)rasterization_state->polygonMode,
.frontFace = (uint8_t)rasterization_state->frontFace };
write(data_ptr, rs);
// TODO: support depth bias
}
if (records.conservative_rasterization_enabled) {
GraphicsPipelineInstanceCreateInfo::ConservativeState cs{ .conservativeMode = (uint8_t)conservative_state->mode,
.overestimationAmount = conservative_state->overestimationAmount };
write(data_ptr, cs);
}
if (ongoing_render_pass->depth_stencil_attachment) {
GraphicsPipelineInstanceCreateInfo::Depth ds = { .depthTestEnable = (bool)depth_stencil_state->depthTestEnable,
.depthWriteEnable = (bool)depth_stencil_state->depthWriteEnable,
.depthCompareOp = (uint8_t)depth_stencil_state->depthCompareOp };
write(data_ptr, ds);
// TODO: support stencil
// TODO: support depth bounds
}
if (ongoing_render_pass->samples != SampleCountFlagBits::e1) {
GraphicsPipelineInstanceCreateInfo::Multisample ms{ .rasterization_samples = (uint32_t)ongoing_render_pass->samples };
write(data_ptr, ms);
}
if (viewports.size() > 0) {
write<uint8_t>(data_ptr, (uint8_t)viewports.size());
if (!(dynamic_state_flags & DynamicStateFlagBits::eViewport)) {
for (const auto& vp : viewports) {
write(data_ptr, vp);
}
}
}
if (scissors.size() > 0) {
write<uint8_t>(data_ptr, (uint8_t)scissors.size());
if (!(dynamic_state_flags & DynamicStateFlagBits::eScissor)) {
for (const auto& sc : scissors) {
write(data_ptr, sc);
}
}
}
assert(data_ptr - data_start_ptr == pi.extended_size); // sanity check: we wrote all the data we wanted to
// acquire_pipeline makes copy of extended_data if it needs to
current_graphics_pipeline = GraphicsPipelineInfo{};
allocator->allocate_graphics_pipelines(std::span{ ¤t_graphics_pipeline.value(), 1 }, std::span{ &pi, 1 });
if (!pi.is_inline()) {
delete pi.extended_data;
}
// drop pipeline immediately
allocator->deallocate(std::span{ ¤t_graphics_pipeline.value(), 1 });
ctx.vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, current_graphics_pipeline->pipeline);
next_pipeline = nullptr;
}
return _bind_state(PipeType::eGraphics);
}
bool CommandBuffer::_bind_ray_tracing_pipeline_state() {
if (next_ray_tracing_pipeline) {
RayTracingPipelineInstanceCreateInfo pi;
pi.base = next_ray_tracing_pipeline;
bool empty = true;
unsigned offset = 0;
for (auto& sc : pi.base->reflection_info.spec_constants) {
auto it = spec_map_entries.find(sc.binding);
if (it != spec_map_entries.end()) {
auto& map_e = it->second;
unsigned size = map_e.is_double ? (unsigned)sizeof(double) : 4;
assert(pi.specialization_map_entries.size() < VUK_MAX_SPECIALIZATIONCONSTANT_RANGES);
pi.specialization_map_entries.push_back(VkSpecializationMapEntry{ sc.binding, offset, size });
assert(offset + size < VUK_MAX_SPECIALIZATIONCONSTANT_SIZE);
memcpy(pi.specialization_constant_data.data() + offset, map_e.data, size);
offset += size;
empty = false;
}
}
if (!empty) {
VkSpecializationInfo& si = pi.specialization_info;
si.pMapEntries = pi.specialization_map_entries.data();
si.mapEntryCount = (uint32_t)pi.specialization_map_entries.size();
si.pData = pi.specialization_constant_data.data();
si.dataSize = pi.specialization_constant_data.size();
pi.base->psscis[0].pSpecializationInfo = &pi.specialization_info;
}
current_ray_tracing_pipeline = RayTracingPipelineInfo{};
allocator->allocate_ray_tracing_pipelines(std::span{ ¤t_ray_tracing_pipeline.value(), 1 }, std::span{ &pi, 1 });
// drop pipeline immediately
allocator->deallocate(std::span{ ¤t_ray_tracing_pipeline.value(), 1 });
ctx.vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, current_ray_tracing_pipeline->pipeline);
next_ray_tracing_pipeline = nullptr;
}
return _bind_state(PipeType::eRayTracing);
}
} // namespace vuk
<file_sep>Allocators
==========
Management of GPU resources is an important part of any renderer. vuk provides an API that lets you plug in your allocation schemes, complementing built-in general purpose schemes that get you started and give good performance out of the box.
Overview
--------
.. doxygenclass:: vuk::Allocator
.. doxygenstruct:: vuk::DeviceResource
To facilitate ownership, a RAII wrapper type is provided, that wraps an Allocator and a payload:
.. doxygenclass:: vuk::Unique
Built-in resources
------------------
.. doxygenstruct:: vuk::DeviceNestedResource
.. doxygenstruct:: vuk::DeviceVkResource
.. doxygenstruct:: vuk::DeviceFrameResource
.. doxygenstruct:: vuk::DeviceSuperFrameResource
Helpers
-------
Allocator provides functions that can perform bulk allocation (to reduce overhead for repeated calls) and return resources directly. However, usually it is more convenient to allocate a single resource and immediately put it into a RAII wrapper to prevent forgetting to deallocate it.
.. doxygenfile:: include/vuk/AllocatorHelpers.hpp
Reference
---------
.. doxygenclass:: vuk::Allocator
:members:
<file_sep>#include "example_runner.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
/* 05_deferred
* In this example we will take our cube to the next level by rendering it deferred.
* To achieve this, we will first render the cube to three offscreen textures -
* one containing the world position, the second the world normals and the third containing colour.
* We will also have depth buffering for this draw.
* After this, we will compute the shading by using a fullscreen pass, where we sample from these textures.
* To achieve this, we will need to let the rendergraph know of our image dependencies.
* Note that it is generally not a good idea to store position (since it can be reconstructed from depth).
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
float angle = 0.f;
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
vuk::Example x{
.name = "05_deferred",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/deferred.vert").generic_string()), (root / "examples/deferred.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/deferred.frag").generic_string()), (root / "examples/deferred.frag").generic_string());
runner.context->create_named_pipeline("cube_deferred", pci);
}
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/fullscreen.vert").generic_string()), (root / "examples/fullscreen.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/deferred_resolve.frag").generic_string()),
(root / "examples/deferred_resolve.frag").generic_string());
runner.context->create_named_pipeline("deferred_resolve", pci);
}
// We set up the cube data, same as in example 02_cube
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
// For the example, we just ask these that these uploads complete before moving on to rendering
// In an engine, you would integrate these uploads into some explicit system
runner.enqueue_setup(std::move(vert_fut));
runner.enqueue_setup(std::move(ind_fut));
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
auto cam_pos = glm::vec3(0, 1.5, 3.5);
vp.view = glm::lookAt(cam_pos, glm::vec3(0), glm::vec3(0, 1, 0));
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 1.f, 10.f);
vp.proj[1][1] *= -1;
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
vuk::RenderGraph rg("05");
rg.attach_in("05_deferred", std::move(target));
// Here we will render the cube into 3 offscreen textures
rg.add_pass({ // Passes can be optionally named, this useful for visualization and debugging
.name = "05_deferred_MRT",
// Declare our framebuffer
.resources = { "05_position"_image >> vuk::eColorWrite,
"05_normal"_image >> vuk::eColorWrite,
"05_color"_image >> vuk::eColorWrite,
"05_depth"_image >> vuk::eDepthStencilRW },
.execute = [uboVP](vuk::CommandBuffer& command_buffer) {
// Rendering is the same as in the case for forward
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization(vuk::PipelineRasterizationStateCreateInfo{}) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
.depthWriteEnable = true,
.depthCompareOp = vuk::CompareOp::eLessOrEqual,
})
.set_color_blend("05_position", {}) // Set the default color blend state individually for demonstration
.set_color_blend("05_normal",
{}) // If you want to use different blending state per attachment, you must enable the independentBlend feature
.set_color_blend("05_color", {})
.bind_vertex_buffer(0,
*verts,
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat,
vuk::Format::eR32G32B32Sfloat,
vuk::Ignore{ offsetof(util::Vertex, uv_coordinates) - offsetof(util::Vertex, tangent) },
vuk::Format::eR32G32Sfloat })
.bind_index_buffer(*inds, vuk::IndexType::eUint32)
.bind_graphics_pipeline("cube_deferred")
.bind_buffer(0, 0, uboVP);
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = static_cast<glm::mat4>(glm::angleAxis(glm::radians(angle), glm::vec3(0.f, 1.f, 0.f)));
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
} });
angle += 360.f * ImGui::GetIO().DeltaTime;
// The shading pass for the deferred rendering
rg.add_pass({ .name = "05_deferred_resolve",
// Declare that we are going to render to the final color image
// Declare that we are going to sample (in the fragment shader) from the previous attachments
.resources = { "05_deferred"_image >> vuk::eColorWrite >> "05_deferred_final",
"05_position+"_image >> vuk::eFragmentSampled,
"05_normal+"_image >> vuk::eFragmentSampled,
"05_color+"_image >> vuk::eFragmentSampled },
.execute = [cam_pos](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
.bind_graphics_pipeline("deferred_resolve");
// Set camera position so we can do lighting
*command_buffer.map_scratch_buffer<glm::vec3>(0, 3) = cam_pos;
// We will sample using nearest neighbour
vuk::SamplerCreateInfo sci;
sci.minFilter = sci.magFilter = vuk::Filter::eNearest;
// Bind the previous attachments as sampled images
command_buffer.bind_image(0, 0, "05_position+")
.bind_sampler(0, 0, sci)
.bind_image(0, 1, "05_normal+")
.bind_sampler(0, 1, sci)
.bind_image(0, 2, "05_color+")
.bind_sampler(0, 2, sci)
.draw(3, 1, 0, 0);
} });
// The intermediate offscreen textures need to be bound
rg.attach_and_clear_image(
"05_position", { .format = vuk::Format::eR16G16B16A16Sfloat, .sample_count = vuk::Samples::e1 }, vuk::ClearColor{ 1.f, 0.f, 0.f, 0.f });
rg.attach_and_clear_image("05_normal", { .format = vuk::Format::eR16G16B16A16Sfloat }, vuk::ClearColor{ 0.f, 1.f, 0.f, 0.f });
rg.attach_and_clear_image("05_color", { .format = vuk::Format::eR8G8B8A8Srgb }, vuk::ClearColor{ 0.f, 0.f, 1.f, 0.f });
rg.attach_and_clear_image("05_depth", { .format = vuk::Format::eD32Sfloat }, vuk::ClearDepthStencil{ 1.0f, 0 });
// The framebuffer for the deferred rendering consists of "05_position", "05_normal", "05_color" and "05_depth" images
// Since these belong to the same framebuffer, vuk can infer the missing parameters that we don't explicitly provide
// For example all images in a framebuffer must be the same extent, hence it is enough to know the extent of one image
// In this case we have not specified any extent - and the second pass does not give any information
// So we provide an additional rule - the extent of "05_position" must match our target extent
// With this rule, all image parameters can be inferred
rg.inference_rule("05_position", vuk::same_extent_as("05_deferred"));
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "05_deferred_final" };
},
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
verts.reset();
inds.reset();
}
};
REGISTER_EXAMPLE(x);
} // namespace<file_sep>#pragma once
// http://howardhinnant.github.io/stack_alloc.html
// https://codereview.stackexchange.com/a/31575
// but modified to use a heap arena
#include <cassert>
#include <cstddef>
#include <new>
class arena {
static const std::size_t alignment = 16;
std::size_t size_;
char* buf_;
char* ptr_;
std::size_t align_up(std::size_t n) noexcept {
return (n + (alignment - 1)) & ~(alignment - 1);
}
bool pointer_in_buffer(char* p) noexcept {
return buf_ <= p && p <= buf_ + size_;
}
public:
arena(std::size_t N) noexcept {
buf_ = (char*)operator new[](N, (std::align_val_t{ alignment }));
ptr_ = buf_;
size_ = N;
}
~arena() {
::operator delete[](buf_, std::align_val_t{ alignment });
ptr_ = nullptr;
}
arena(const arena& o) {
size_ = o.size_;
buf_ = (char*)operator new[](size_, (std::align_val_t{ alignment }));
ptr_ = buf_;
}
arena& operator=(const arena& o) {
::operator delete[](buf_, std::align_val_t{ alignment });
size_ = o.size_;
buf_ = (char*)operator new[](size_, (std::align_val_t{ alignment }));
ptr_ = buf_;
return *this;
};
char* allocate(std::size_t n);
void deallocate(char* p, std::size_t n) noexcept;
std::size_t size() {
return size_;
}
std::size_t used() const {
return static_cast<std::size_t>(ptr_ - buf_);
}
void reset() {
ptr_ = buf_;
}
};
inline char* arena::allocate(std::size_t n) {
assert(pointer_in_buffer(ptr_) && "short_alloc has outlived arena");
n = align_up(n);
if (buf_ + size_ - ptr_ >= (int64_t)n) {
char* r = ptr_;
ptr_ += n;
return r;
}
return static_cast<char*>(::operator new(n));
}
inline void arena::deallocate(char* p, std::size_t n) noexcept {
assert(pointer_in_buffer(ptr_) && "short_alloc has outlived arena");
if (pointer_in_buffer(p)) {
n = align_up(n);
if (p + n == ptr_)
ptr_ = p;
} else
::operator delete(p);
}
template<class T, std::size_t N>
class short_alloc {
arena& a_;
public:
typedef T value_type;
public:
template<class _Up>
struct rebind {
typedef short_alloc<_Up, N> other;
};
short_alloc(arena& a) : a_(a) {}
template<class U>
short_alloc(const short_alloc<U, N>& a) noexcept : a_(a.a_) {}
short_alloc(const short_alloc&) = default;
short_alloc& operator=(const short_alloc&) = delete;
T* allocate(std::size_t n) {
return reinterpret_cast<T*>(a_.allocate(n * sizeof(T)));
}
void deallocate(T* p, std::size_t n) noexcept {
a_.deallocate(reinterpret_cast<char*>(p), n * sizeof(T));
}
template<class T1, std::size_t N1, class U, std::size_t M>
friend bool operator==(const short_alloc<T1, N1>& x, const short_alloc<U, M>& y) noexcept;
template<class U, std::size_t M>
friend class short_alloc;
};
template<class T, std::size_t N, class U, std::size_t M>
inline bool operator==(const short_alloc<T, N>& x, const short_alloc<U, M>& y) noexcept {
return N == M && &x.a_ == &y.a_;
}
template<class T, std::size_t N, class U, std::size_t M>
inline bool operator!=(const short_alloc<T, N>& x, const short_alloc<U, M>& y) noexcept {
return !(x == y);
}
<file_sep>#pragma once
// based on https://github.com/kociap/anton_core/blob/master/public/anton/expected.hpp
#include "vuk/Config.hpp"
#include "vuk/Exception.hpp"
#include "vuk/vuk_fwd.hpp"
#include <cassert>
#include <memory>
#include <type_traits>
#include <utility>
#define FWD(x) (static_cast<decltype(x)&&>(x))
#define MOV(x) (static_cast<std::remove_reference_t<decltype(x)>&&>(x))
namespace vuk {
namespace detail {
template<class U>
void destroy_at(U* p) {
if constexpr (std::is_array_v<U>) {
for (auto& elem : *p) {
(&elem)->~U();
}
} else {
p->~U();
}
}
} // namespace detail
struct Exception;
struct ResultErrorTag {
explicit ResultErrorTag() = default;
};
constexpr ResultErrorTag expected_error;
struct ResultValueTag {
explicit ResultValueTag() = default;
};
constexpr ResultValueTag expected_value;
template<typename T, typename E>
struct Result {
public:
using value_type = T;
using error_type = E;
template<typename... Args>
Result(ResultValueTag, Args&&... args) : _value{ FWD(args)... }, _holds_value(true) {}
template<class U>
Result(ResultErrorTag, U&& err_t) : _holds_value(false) {
using V = std::remove_reference_t<U>;
static_assert(std::is_base_of_v<E, V>, "Concrete error must derive from E");
#if VUK_FAIL_FAST
fprintf(stderr, "%s", err_t.what());
assert(0);
#endif
_error = new V(MOV(err_t));
}
Result(Result const& other) = delete;
template<class U, class F>
Result(Result<U, F>&& other) : _null_state(), _holds_value(other._holds_value) {
static_assert(std::is_convertible_v<F*, E*>, "error must be convertible");
if constexpr (!std::is_same_v<U, T>) {
assert(!other._holds_value);
} else {
if (other._holds_value) {
std::construct_at(&_value, MOV(other._value));
}
}
if (!other._holds_value) {
_error = MOV(other._error);
other._error = nullptr;
}
_extracted = other._extracted;
}
Result& operator=(Result const& other) = delete;
template<class U, class F>
Result& operator=(Result<U, F>&& other) {
static_assert(std::is_convertible_v<F*, E*>, "error must be convertible");
if constexpr (!std::is_same_v<U, T>) {
assert(!other.holds_value);
}
if (_holds_value) {
if (other._holds_value) {
_value = MOV(other._value);
} else {
detail::destroy_at(&_value);
std::construct_at(&_error, MOV(other._error));
other._error = nullptr;
_holds_value = false;
}
} else {
delete _error;
if (other._holds_value) {
std::construct_at(&_value, MOV(other._value));
_holds_value = true;
} else {
_error = MOV(other._error);
other._error = nullptr;
}
}
_extracted = other._extracted;
return *this;
}
~Result() noexcept(false) {
if (_holds_value) {
_value.~T();
} else {
if (!_extracted && _error) {
#if VUK_USE_EXCEPTIONS
_error->throw_this();
#else
std::abort();
#endif
}
delete _error;
}
}
[[nodiscard]] operator bool() const {
return _holds_value;
}
[[nodiscard]] bool holds_value() const {
return _holds_value;
}
[[nodiscard]] T* operator->() {
if (!_holds_value) {
_error->throw_this();
}
return &_value;
}
[[nodiscard]] T const* operator->() const {
if (!_holds_value) {
_error->throw_this();
}
return &_value;
}
[[nodiscard]] T& operator*() & {
if (!_holds_value) {
_error->throw_this();
}
return _value;
}
[[nodiscard]] T const& operator*() const& {
if (!_holds_value) {
_error->throw_this();
}
return _value;
}
[[nodiscard]] T&& operator*() && {
if (!_holds_value) {
_error->throw_this();
}
return MOV(_value);
}
[[nodiscard]] T const&& operator*() const&& {
if (!_holds_value) {
_error->throw_this();
}
return _value;
}
[[nodiscard]] T& value() & {
if (!_holds_value) {
_error->throw_this();
}
return _value;
}
[[nodiscard]] T const& value() const& {
if (!_holds_value) {
_error->throw_this();
}
return _value;
}
[[nodiscard]] T&& value() && {
if (!_holds_value) {
_error->throw_this();
}
return MOV(_value);
}
[[nodiscard]] E& error() & {
assert(!_holds_value && "cannot call error() on Result that does not hold an error");
_extracted = true;
return *_error;
}
[[nodiscard]] E const& error() const& {
assert(!_holds_value && "cannot call error() on Result that does not hold an error");
_extracted = true;
return *_error;
}
friend void swap(Result& lhs, Result& rhs) {
using std::swap;
if (lhs._holds_value) {
if (rhs._holds_value) {
swap(lhs._value, rhs._value);
} else {
std::construct_at(&rhs._value, MOV(lhs._value));
detail::destroy_at(&lhs._value);
std::construct_at(&lhs._error, MOV(rhs._error));
swap(lhs._holds_value, rhs._holds_value);
}
} else {
if (rhs._holds_value) {
std::construct_at(&rhs._error, MOV(lhs._error));
std::construct_at(&lhs._value, MOV(rhs._value));
detail::destroy_at(&rhs._value);
swap(lhs._holds_value, rhs._holds_value);
} else {
swap(lhs._error, rhs._error);
}
}
swap(lhs._extracted, rhs._extracted);
}
private:
union {
T _value;
E* _error;
bool _null_state;
};
bool _holds_value;
mutable bool _extracted = false;
template<class U, class B>
friend struct Result;
};
template<typename E>
struct Result<void, E> {
public:
using value_type = void;
using error_type = E;
Result(ResultValueTag) : _holds_value(true) {}
template<class U>
Result(ResultErrorTag, U&& err_t) : _holds_value(false) {
using V = std::remove_reference_t<U>;
static_assert(std::is_base_of_v<E, V>, "Concrete error must derive from E");
#if VUK_FAIL_FAST
fprintf(stderr, "%s", err_t.what());
assert(0);
#endif
_error = new V(MOV(err_t));
}
Result(Result const& other) = delete;
template<class U, class F>
Result(Result<U, F>&& other) : _null_state(), _holds_value(other._holds_value) {
static_assert(std::is_convertible_v<F*, E*>, "error must be convertible");
if (!other._holds_value) {
_error = other._error;
other._error = nullptr;
_extracted = other._extracted;
}
}
Result& operator=(Result const& other) = delete;
template<class U, class F>
Result& operator=(Result<U, F>&& other) {
static_assert(std::is_convertible_v<F*, E*>, "error must be convertible");
if constexpr (!std::is_same_v<U, value_type>) {
assert(!other._holds_value);
}
if (_holds_value) {
if (!other._holds_value) {
_error = MOV(other._error);
other._error = nullptr;
_holds_value = false;
}
} else {
delete _error;
if (other._holds_value) {
_holds_value = true;
} else {
_error = MOV(other._error);
other._error = nullptr;
}
}
_extracted = other._extracted;
return *this;
}
~Result() noexcept(false) {
if (!_holds_value) {
if (!_extracted && _error) {
#if VUK_USE_EXCEPTIONS
_error->throw_this();
#else
std::abort();
#endif
}
delete _error;
}
}
[[nodiscard]] operator bool() const {
return _holds_value;
}
[[nodiscard]] bool holds_value() const {
return _holds_value;
}
[[nodiscard]] E& error() & {
assert(!_holds_value && "cannot call error() on Result that does not hold an error");
_extracted = true;
return *_error;
}
[[nodiscard]] E const& error() const& {
assert(!_holds_value && "cannot call error() on Result that does not hold an error");
_extracted = true;
return *_error;
}
friend void swap(Result& lhs, Result& rhs) {
using std::swap;
if (lhs._holds_value) {
if (!rhs._holds_value) {
std::construct_at(&lhs._error, MOV(rhs._error));
delete rhs._error;
swap(lhs._holds_value, rhs._holds_value);
}
} else {
if (rhs._holds_value) {
std::construct_at(&rhs._error, MOV(lhs._error));
swap(lhs._holds_value, rhs._holds_value);
}
}
}
private:
union {
E* _error;
bool _null_state;
};
bool _holds_value;
mutable bool _extracted = false;
template<class U, class B>
friend struct Result;
};
} // namespace vuk
#undef FWD
#undef MOV<file_sep>#pragma once
#include "vuk/Buffer.hpp"
#include "vuk/Future.hpp"
#include "vuk/Hash.hpp"
#include "vuk/Image.hpp"
#include "vuk/ImageAttachment.hpp"
#include "vuk/MapProxy.hpp"
#include "vuk/Result.hpp"
#include "vuk/Swapchain.hpp"
#include "vuk/vuk_fwd.hpp"
#include <functional>
#include <optional>
#include <span>
#include <string_view>
#include <unordered_set>
#include <vector>
namespace vuk {
struct FutureBase;
struct Resource;
namespace detail {
struct BufferResourceInputOnly;
struct BufferResource {
Name name;
BufferResourceInputOnly operator>>(Access ba);
};
struct ImageResourceInputOnly;
struct ImageResource {
Name name;
ImageResourceInputOnly operator>>(Access ia);
};
struct ImageResourceInputOnly {
Name name;
Access ba;
Resource operator>>(Name output);
operator Resource();
};
struct BufferResourceInputOnly {
Name name;
Access ba;
Resource operator>>(Name output);
operator Resource();
};
} // namespace detail
struct Resource {
QualifiedName name;
Name original_name;
enum class Type { eBuffer, eImage } type;
Access ia;
QualifiedName out_name;
struct RenderGraph* foreign = nullptr;
int32_t reference = 0;
bool promoted_to_general = false;
Resource(Name n, Type t, Access ia) : name{ Name{}, n }, type(t), ia(ia) {}
Resource(Name n, Type t, Access ia, Name out_name) : name{ Name{}, n }, type(t), ia(ia), out_name{ Name{}, out_name } {}
Resource(RenderGraph* foreign, QualifiedName n, Type t, Access ia) : name{ n }, type(t), ia(ia), foreign(foreign) {}
bool operator==(const Resource& o) const noexcept {
return name == o.name;
}
};
QueueResourceUse to_use(Access acc, DomainFlags domain);
enum class PassType { eUserPass, eClear, eResolve, eDiverge, eConverge, eForcedAccess };
/// @brief Fundamental unit of execution and scheduling. Refers to resources
struct Pass {
Name name;
DomainFlags execute_on = DomainFlagBits::eDevice;
std::vector<Resource> resources;
std::function<void(CommandBuffer&)> execute;
std::byte* arguments; // internal use
PassType type = PassType::eUserPass;
};
// declare these specializations for GCC
template<>
ConstMapIterator<QualifiedName, const struct AttachmentInfo&>::~ConstMapIterator();
template<>
ConstMapIterator<QualifiedName, const struct BufferInfo&>::~ConstMapIterator();
struct RenderGraph : std::enable_shared_from_this<RenderGraph> {
RenderGraph();
RenderGraph(Name name);
~RenderGraph();
RenderGraph(const RenderGraph&) = delete;
RenderGraph& operator=(const RenderGraph&) = delete;
RenderGraph(RenderGraph&&) noexcept;
RenderGraph& operator=(RenderGraph&&) noexcept;
/// @brief Add a pass to the rendergraph
/// @param pass the Pass to add to the RenderGraph
void add_pass(Pass pass, source_location location = source_location::current());
/// @brief Add an alias for a resource
/// @param new_name Additional name to refer to the resource
/// @param old_name Old name used to refere to the resource
void add_alias(Name new_name, Name old_name);
/// @brief Diverge image. subrange is available as subrange_name afterwards.
void diverge_image(Name whole_name, Subrange::Image subrange, Name subrange_name);
/// @brief Reconverge image from named parts. Prevents diverged use moving before pre_diverge or after post_diverge.
void converge_image_explicit(std::span<Name> pre_diverge, Name post_diverge);
/// @brief Add a resolve operation from the image resource `ms_name` that consumes `resolved_name_src` and produces `resolved_name_dst`
/// This is only supported for color images.
/// @param resolved_name_src Image resource name consumed (single-sampled)
/// @param resolved_name_dst Image resource name created (single-sampled)
/// @param ms_name Image resource to resolve from (multisampled)
void resolve_resource_into(Name resolved_name_src, Name resolved_name_dst, Name ms_name);
/// @brief Clear image attachment
/// @param image_name_in Name of the image resource to clear
/// @param image_name_out Name of the cleared image resource
/// @param clear_value Value used for the clear
/// @param subrange Range of image cleared
void clear_image(Name image_name_in, Name image_name_out, Clear clear_value);
/// @brief Attach a swapchain to the given name
/// @param name Name of the resource to attach to
void attach_swapchain(Name name, SwapchainRef swp);
/// @brief Attach a buffer to the given name
/// @param name Name of the resource to attach to
/// @param buffer Buffer to attach
/// @param initial Access to the resource prior to this rendergraph
void attach_buffer(Name name, Buffer buffer, Access initial = eNone);
/// @brief Attach a buffer to be allocated from the specified allocator
/// @param name Name of the resource to attach to
/// @param buffer Buffer to attach
/// @param allocator Allocator the Buffer will be allocated from
/// @param initial Access to the resource prior to this rendergraph
void attach_buffer_from_allocator(Name name, Buffer buffer, Allocator allocator, Access initial = eNone);
/// @brief Attach an image to the given name
/// @param name Name of the resource to attach to
/// @param image_attachment ImageAttachment to attach
/// @param initial Access to the resource prior to this rendergraph
void attach_image(Name name, ImageAttachment image_attachment, Access initial = eNone);
/// @brief Attach an image to be allocated from the specified allocator
/// @param name Name of the resource to attach to
/// @param image_attachment ImageAttachment to attach
/// @param buffer Buffer to attach
/// @param initial Access to the resource prior to this rendergraph
void attach_image_from_allocator(Name name, ImageAttachment image_attachment, Allocator allocator, Access initial = eNone);
/// @brief Attach an image to the given name
/// @param name Name of the resource to attach to
/// @param image_attachment ImageAttachment to attach
/// @param clear_value Value used for the clear
/// @param initial Access to the resource prior to this rendergraph
void attach_and_clear_image(Name name, ImageAttachment image_attachment, Clear clear_value, Access initial = eNone);
/// @brief Attach a future to the given name
/// @param name Name of the resource to attach to
/// @param future Future to be attached into this rendergraph
void attach_in(Name name, Future future);
/// @brief Attach multiple futures - the names are matched to future bound names
/// @param futures Futures to be attached into this rendergraph
void attach_in(std::span<Future> futures);
void inference_rule(Name target, std::function<void(const struct InferenceContext& ctx, ImageAttachment& ia)>);
void inference_rule(Name target, std::function<void(const struct InferenceContext& ctx, Buffer& ia)>);
/// @brief Compute all the unconsumed resource names and return them as Futures
std::vector<Future> split();
/// @brief Mark resources to be released from the rendergraph with future access
/// @param name Name of the resource to be released
/// @param final Access after the rendergraph
void release(Name name, Access final);
/// @brief Mark resource to be released from the rendergraph for presentation
/// @param name Name of the resource to be released
void release_for_present(Name name);
/// @brief Name of the rendergraph
Name name;
private:
struct RGImpl* impl;
friend struct ExecutableRenderGraph;
friend struct Compiler;
friend struct RGCImpl;
// future support functions
friend class Future;
void attach_out(QualifiedName, Future& fimg, DomainFlags dst_domain);
void detach_out(QualifiedName, Future& fimg);
Name get_temporary_name();
};
struct InferenceContext {
const ImageAttachment& get_image_attachment(Name name) const;
const Buffer& get_buffer(Name name) const;
struct ExecutableRenderGraph* erg;
Name prefix;
};
using IARule = std::function<void(const struct InferenceContext& ctx, ImageAttachment& ia)>;
using BufferRule = std::function<void(const struct InferenceContext& ctx, Buffer& buffer)>;
// builtin inference rules for convenience
/// @brief Inference target has the same extent as the source
IARule same_extent_as(Name inference_source);
/// @brief Inference target has the same width & height as the source
IARule same_2D_extent_as(Name inference_source);
/// @brief Inference target has the same format as the source
IARule same_format_as(Name inference_source);
/// @brief Inference target has the same shape(extent, layers, levels) as the source
IARule same_shape_as(Name inference_source);
/// @brief Inference target is similar to(same shape, same format, same sample count) the source
IARule similar_to(Name inference_source);
/// @brief Inference target is the same size as the source
BufferRule same_size_as(Name inference_source);
struct Compiler {
Compiler();
~Compiler();
/// @brief Build the graph, assign framebuffers, render passes and subpasses
/// link automatically calls this, only needed if you want to use the reflection functions
/// @param compile_options CompileOptions controlling compilation behaviour
Result<void> compile(std::span<std::shared_ptr<RenderGraph>> rgs, const RenderGraphCompileOptions& compile_options);
/// @brief Use this RenderGraph and create an ExecutableRenderGraph
/// @param compile_options CompileOptions controlling compilation behaviour
Result<struct ExecutableRenderGraph> link(std::span<std::shared_ptr<RenderGraph>> rgs, const RenderGraphCompileOptions& compile_options);
// reflection functions
/// @brief retrieve usages of resources in the RenderGraph
std::span<struct ChainLink*> get_use_chains() const;
/// @brief retrieve bound image attachments in the RenderGraph
MapProxy<QualifiedName, const struct AttachmentInfo&> get_bound_attachments();
/// @brief retrieve bound buffers in the RenderGraph
MapProxy<QualifiedName, const struct BufferInfo&> get_bound_buffers();
/// @brief compute ImageUsageFlags for given use chain
ImageUsageFlags compute_usage(const struct ChainLink* chain);
/// @brief Get the image attachment heading this use chain
const struct AttachmentInfo& get_chain_attachment(const struct ChainLink* chain);
/// @brief Get the last name that references this chain (may not exist)
std::optional<QualifiedName> get_last_use_name(const struct ChainLink* chain);
/// @brief Dump the pass dependency graph in graphviz format
std::string dump_graph();
private:
struct RGCImpl* impl;
// internal passes
Result<void> inline_rgs(std::span<std::shared_ptr<RenderGraph>> rgs);
void queue_inference();
void pass_partitioning();
void resource_linking();
void render_pass_assignment();
friend struct ExecutableRenderGraph;
};
struct SubmitInfo {
std::vector<std::pair<DomainFlagBits, uint64_t>> relative_waits;
std::vector<std::pair<DomainFlagBits, uint64_t>> absolute_waits;
std::vector<VkCommandBuffer> command_buffers;
std::vector<FutureBase*> future_signals;
std::vector<SwapchainRef> used_swapchains;
};
struct SubmitBatch {
DomainFlagBits domain;
std::vector<SubmitInfo> submits;
};
struct SubmitBundle {
std::vector<SubmitBatch> batches;
};
struct ExecutableRenderGraph {
ExecutableRenderGraph(Compiler&);
~ExecutableRenderGraph();
ExecutableRenderGraph(const ExecutableRenderGraph&) = delete;
ExecutableRenderGraph& operator=(const ExecutableRenderGraph&) = delete;
ExecutableRenderGraph(ExecutableRenderGraph&&) noexcept;
ExecutableRenderGraph& operator=(ExecutableRenderGraph&&) noexcept;
Result<SubmitBundle> execute(Allocator&, std::vector<std::pair<Swapchain*, size_t>> swp_with_index);
Result<struct BufferInfo, RenderGraphException> get_resource_buffer(const NameReference&, struct PassInfo*);
Result<struct AttachmentInfo, RenderGraphException> get_resource_image(const NameReference&, struct PassInfo*);
Result<bool, RenderGraphException> is_resource_image_in_general_layout(const NameReference&, struct PassInfo* pass_info);
QualifiedName resolve_name(Name, struct PassInfo*) const noexcept;
private:
struct RGCImpl* impl;
void fill_render_pass_info(struct RenderPassInfo& rpass, const size_t& i, class CommandBuffer& cobuf);
Result<SubmitInfo> record_single_submit(Allocator&, std::span<PassInfo*> passes, DomainFlagBits domain);
friend struct InferenceContext;
};
} // namespace vuk
inline vuk::detail::ImageResource operator"" _image(const char* name, size_t) {
return { name };
}
inline vuk::detail::BufferResource operator"" _buffer(const char* name, size_t) {
return { name };
}
namespace std {
template<>
struct hash<vuk::Subrange::Image> {
size_t operator()(vuk::Subrange::Image const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.base_layer, x.base_level, x.layer_count, x.level_count);
return h;
}
};
}; // namespace std
<file_sep>#include "utils.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/CommandBuffer.hpp"
#include "vuk/Context.hpp"
#include "vuk/Partials.hpp"
#include "vuk/RenderGraph.hpp"
#include "vuk/SampledImage.hpp"
#include "imgui_vert.hpp"
#include "imgui_frag.hpp"
util::ImGuiData util::ImGui_ImplVuk_Init(vuk::Allocator& allocator) {
vuk::Context& ctx = allocator.get_context();
auto& io = ImGui::GetIO();
io.BackendRendererName = "imgui_impl_vuk";
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
ImGuiData data;
auto [tex, stub] = create_texture(allocator, vuk::Format::eR8G8B8A8Srgb, vuk::Extent3D{ (unsigned)width, (unsigned)height, 1u }, pixels, false);
data.font_texture = std::move(tex);
vuk::Compiler comp;
stub.wait(allocator, comp);
ctx.set_name(data.font_texture, "ImGui/font");
vuk::SamplerCreateInfo sci;
sci.minFilter = sci.magFilter = vuk::Filter::eLinear;
sci.mipmapMode = vuk::SamplerMipmapMode::eLinear;
sci.addressModeU = sci.addressModeV = sci.addressModeW = vuk::SamplerAddressMode::eRepeat;
data.font_sci = sci;
data.font_si = std::make_unique<vuk::SampledImage>(vuk::SampledImage::Global{ *data.font_texture.view, sci, vuk::ImageLayout::eReadOnlyOptimalKHR });
io.Fonts->TexID = (ImTextureID)data.font_si.get();
{
vuk::PipelineBaseCreateInfo pci;
// glslangValidator.exe -V imgui.vert --vn imgui_vert -o examples/imgui_vert.hpp
pci.add_static_spirv(imgui_vert, sizeof(imgui_vert) / 4, "imgui.vert");
// glslangValidator.exe -V imgui.frag --vn imgui_frag -o examples/imgui_frag.hpp
pci.add_static_spirv(imgui_frag, sizeof(imgui_frag) / 4, "imgui.frag");
ctx.create_named_pipeline("imgui", pci);
}
return data;
}
vuk::Future util::ImGui_ImplVuk_Render(vuk::Allocator& allocator,
vuk::Future target,
util::ImGuiData& data,
ImDrawData* draw_data,
const plf::colony<vuk::SampledImage>& sampled_images) {
auto reset_render_state = [](const util::ImGuiData& data, vuk::CommandBuffer& command_buffer, ImDrawData* draw_data, vuk::Buffer vertex, vuk::Buffer index) {
command_buffer.bind_image(0, 0, *data.font_texture.view).bind_sampler(0, 0, data.font_sci);
if (index.size > 0) {
command_buffer.bind_index_buffer(index, sizeof(ImDrawIdx) == 2 ? vuk::IndexType::eUint16 : vuk::IndexType::eUint32);
}
command_buffer.bind_vertex_buffer(0, vertex, 0, vuk::Packed{ vuk::Format::eR32G32Sfloat, vuk::Format::eR32G32Sfloat, vuk::Format::eR8G8B8A8Unorm });
command_buffer.bind_graphics_pipeline("imgui");
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer());
struct PC {
float scale[2];
float translate[2];
} pc;
pc.scale[0] = 2.0f / draw_data->DisplaySize.x;
pc.scale[1] = 2.0f / draw_data->DisplaySize.y;
pc.translate[0] = -1.0f - draw_data->DisplayPos.x * pc.scale[0];
pc.translate[1] = -1.0f - draw_data->DisplayPos.y * pc.scale[1];
command_buffer.push_constants(vuk::ShaderStageFlagBits::eVertex, 0, pc);
};
size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
auto imvert = *allocate_buffer(allocator, { vuk::MemoryUsage::eCPUtoGPU, vertex_size, 1 });
auto imind = *allocate_buffer(allocator, { vuk::MemoryUsage::eCPUtoGPU, index_size, 1 });
size_t vtx_dst = 0, idx_dst = 0;
vuk::Compiler comp;
for (int n = 0; n < draw_data->CmdListsCount; n++) {
const ImDrawList* cmd_list = draw_data->CmdLists[n];
auto imverto = imvert->add_offset(vtx_dst * sizeof(ImDrawVert));
auto imindo = imind->add_offset(idx_dst * sizeof(ImDrawIdx));
// TODO:
vuk::host_data_to_buffer(allocator, vuk::DomainFlagBits{}, imverto, std::span(cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size)).wait(allocator, comp);
vuk::host_data_to_buffer(allocator, vuk::DomainFlagBits{}, imindo, std::span(cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size)).wait(allocator, comp);
vtx_dst += cmd_list->VtxBuffer.Size;
idx_dst += cmd_list->IdxBuffer.Size;
}
std::shared_ptr<vuk::RenderGraph> rg = std::make_shared<vuk::RenderGraph>("imgui");
rg->attach_in("target", std::move(target));
// add rendergraph dependencies to be transitioned
// make all rendergraph sampled images available
std::vector<vuk::Resource> resources;
resources.emplace_back(vuk::Resource{ "target", vuk::Resource::Type::eImage, vuk::eColorRW, "target+" });
for (auto& si : sampled_images) {
if (!si.is_global) {
resources.emplace_back(
vuk::Resource{ si.rg_attachment.reference.rg, si.rg_attachment.reference.name, vuk::Resource::Type::eImage, vuk::Access::eFragmentSampled });
}
}
vuk::Pass pass{ .name = "imgui",
.resources = std::move(resources),
.execute = [&data, &allocator, verts = imvert.get(), inds = imind.get(), draw_data, reset_render_state](vuk::CommandBuffer& command_buffer) {
command_buffer.set_dynamic_state(vuk::DynamicStateFlagBits::eViewport | vuk::DynamicStateFlagBits::eScissor);
command_buffer.set_rasterization(vuk::PipelineRasterizationStateCreateInfo{});
command_buffer.set_color_blend("target", vuk::BlendPreset::eAlphaBlend);
reset_render_state(data, command_buffer, draw_data, verts, inds);
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
// (Because we merged all buffers into a single one, we maintain our own offset into them)
int global_vtx_offset = 0;
int global_idx_offset = 0;
for (int n = 0; n < draw_data->CmdListsCount; n++) {
const ImDrawList* cmd_list = draw_data->CmdLists[n];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) {
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != nullptr) {
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
reset_render_state(data, command_buffer, draw_data, verts, inds);
else
pcmd->UserCallback(cmd_list, pcmd);
} else {
// Project scissor/clipping rectangles into framebuffer space
ImVec4 clip_rect;
clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
auto fb_width = command_buffer.get_ongoing_render_pass().extent.width;
auto fb_height = command_buffer.get_ongoing_render_pass().extent.height;
if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) {
// Negative offsets are illegal for vkCmdSetScissor
if (clip_rect.x < 0.0f)
clip_rect.x = 0.0f;
if (clip_rect.y < 0.0f)
clip_rect.y = 0.0f;
// Apply scissor/clipping rectangle
vuk::Rect2D scissor;
scissor.offset.x = (int32_t)(clip_rect.x);
scissor.offset.y = (int32_t)(clip_rect.y);
scissor.extent.width = (uint32_t)(clip_rect.z - clip_rect.x);
scissor.extent.height = (uint32_t)(clip_rect.w - clip_rect.y);
command_buffer.set_scissor(0, scissor);
// Bind texture
if (pcmd->TextureId) {
auto& si = *reinterpret_cast<vuk::SampledImage*>(pcmd->TextureId);
if (si.is_global) {
command_buffer.bind_image(0, 0, si.global.iv).bind_sampler(0, 0, si.global.sci);
} else {
if (si.rg_attachment.ivci) {
auto ivci = *si.rg_attachment.ivci;
// it is possible that we end up binding multiple images here with the same name -
// the rendergraph sorts this out, but we need to refer to the correct one here
// so we use a NameReference to make sure that we include the source rendergraph for identification
// this is useful for generic name binding, but not really needed for usual passes
auto res_img = command_buffer.get_resource_image_attachment(si.rg_attachment.reference)->image;
ivci.image = res_img.image;
auto iv = vuk::allocate_image_view(allocator, ivci);
command_buffer.bind_image(0, 0, **iv).bind_sampler(0, 0, si.rg_attachment.sci);
} else {
command_buffer
.bind_image(0,
0,
*command_buffer.get_resource_image_attachment(si.rg_attachment.reference),
vuk::ImageLayout::eShaderReadOnlyOptimal)
.bind_sampler(0, 0, si.rg_attachment.sci);
}
}
}
// Draw
command_buffer.draw_indexed(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
}
}
}
global_idx_offset += cmd_list->IdxBuffer.Size;
global_vtx_offset += cmd_list->VtxBuffer.Size;
}
} };
rg->add_pass(std::move(pass));
return { std::move(rg), "target+" };
}
<file_sep>#include "example_runner.hpp"
#include <algorithm>
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
#include <numeric>
#include <optional>
#include <random>
#include <stb_image.h>
/* 10_baby_renderer
*
* In this example we make a small (baby) renderer (not for rendering babies!).
* Here we use very simple (read: potentially not performant or convenient) abstractions.
* The goal is that we can render diverse object with a single simple loop render loop.
*
* Generally resources can be bound individually to draws, here we show this for textures and a material buffer.
* Or they can be aggregated into arrays and indexed in the shader, which is done here for model matrices.
* This small example shows no state deduplication or sorting, which are very good optimizations for a real renderer.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
// The Y rotation angle of our cube
float angle = 0.f;
// Generate vertices and indices for the cube
auto box = util::generate_cube();
struct Mesh {
vuk::Unique<vuk::Buffer> vertex_buffer;
vuk::Unique<vuk::Buffer> index_buffer;
uint32_t index_count;
};
struct Material {
vuk::PipelineBaseInfo* pipeline;
virtual void bind_parameters(vuk::CommandBuffer&){};
virtual void bind_textures(vuk::CommandBuffer&){};
};
struct NormalMaterial : Material {
vuk::ImageView texture;
void bind_textures(vuk::CommandBuffer& cbuf) override {
cbuf.bind_image(0, 2, texture).bind_sampler(0, 2, {});
}
};
struct TintMaterial : Material {
vuk::ImageView texture;
glm::vec4 tint_color = glm::vec4(0);
void bind_textures(vuk::CommandBuffer& cbuf) override {
cbuf.bind_image(0, 2, texture).bind_sampler(0, 2, {});
}
void bind_parameters(vuk::CommandBuffer& cbuf) override {
*cbuf.map_scratch_buffer<glm::vec4>(0, 3) = tint_color;
}
};
std::optional<Mesh> cube_mesh, quad_mesh;
struct Renderable {
Mesh* mesh;
Material* material;
glm::vec3 position;
glm::vec3 velocity = glm::vec3(0);
};
std::optional<vuk::Texture> texture_of_doge, variant1, variant2;
std::vector<NormalMaterial> nmats;
std::vector<TintMaterial> tmats;
std::vector<Renderable> renderables;
std::random_device rd;
std::mt19937 g(rd());
vuk::Example xample{
.name = "10_baby_renderer",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
vuk::Context& ctx = allocator.get_context();
// Use STBI to load the image
int x, y, chans;
auto doge_image = stbi_load((root / "examples/doge.png").generic_string().c_str(), &x, &y, &chans, 4);
// Similarly to buffers, we allocate the image and enqueue the upload
auto [tex, tex_fut] = create_texture(allocator, vuk::Format::eR8G8B8A8Srgb, vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u }, doge_image, false);
texture_of_doge = std::move(tex);
stbi_image_free(doge_image);
// Let's create two variants of the doge image (like in example 09)
// Creating a compute pipeline that inverts an image
{
vuk::PipelineBaseCreateInfo pbci;
pbci.add_glsl(util::read_entire_file((root / "examples/invert.comp").generic_string()), (root / "examples/invert.comp").generic_string());
runner.context->create_named_pipeline("invert", pbci);
}
vuk::ImageCreateInfo ici;
ici.format = vuk::Format::eR8G8B8A8Srgb;
ici.extent = vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u };
ici.samples = vuk::Samples::e1;
ici.imageType = vuk::ImageType::e2D;
ici.initialLayout = vuk::ImageLayout::eUndefined;
ici.tiling = vuk::ImageTiling::eOptimal;
ici.usage = vuk::ImageUsageFlagBits::eTransferDst | vuk::ImageUsageFlagBits::eSampled;
ici.mipLevels = ici.arrayLayers = 1;
variant1 = ctx.allocate_texture(allocator, ici);
ici.format = vuk::Format::eR8G8B8A8Unorm;
ici.usage = vuk::ImageUsageFlagBits::eStorage | vuk::ImageUsageFlagBits::eSampled;
variant2 = ctx.allocate_texture(allocator, ici);
// Make a RenderGraph to process the loaded image
vuk::RenderGraph rg("PP");
rg.add_pass({ .name = "preprocess",
.resources = { "10_doge"_image >> (vuk::eTransferRead | vuk::eComputeSampled),
"10_v1"_image >> vuk::eTransferWrite,
"10_v2"_image >> vuk::eComputeWrite },
.execute = [x, y](vuk::CommandBuffer& command_buffer) {
// For the first image, flip the image on the Y axis using a blit
vuk::ImageBlit blit;
blit.srcSubresource.aspectMask = vuk::ImageAspectFlagBits::eColor;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.srcSubresource.mipLevel = 0;
blit.srcOffsets[0] = vuk::Offset3D{ 0, 0, 0 };
blit.srcOffsets[1] = vuk::Offset3D{ x, y, 1 };
blit.dstSubresource = blit.srcSubresource;
blit.dstOffsets[0] = vuk::Offset3D{ x, y, 0 };
blit.dstOffsets[1] = vuk::Offset3D{ 0, 0, 1 };
command_buffer.blit_image("10_doge", "10_v1", blit, vuk::Filter::eLinear);
// For the second image, invert the colours in compute
command_buffer.bind_image(0, 0, "10_doge")
.bind_sampler(0, 0, {})
.bind_image(0, 1, "10_v2")
.bind_compute_pipeline("invert")
.dispatch_invocations(x, y);
} });
// Bind the resources for the variant generation
// We specify the initial and final access
// The texture we have created is already in ShaderReadOptimal, but we need it in General during the pass, and we need it back to ShaderReadOptimal
// afterwards
rg.attach_in("10_doge", std::move(tex_fut));
rg.attach_image("10_v1", vuk::ImageAttachment::from_texture(*variant1), vuk::eNone);
rg.release("10_v1+", vuk::eFragmentSampled);
rg.attach_image("10_v2", vuk::ImageAttachment::from_texture(*variant2), vuk::eNone);
rg.release("10_v2+", vuk::eFragmentSampled);
// enqueue running the preprocessing rendergraph and force 10_doge to be sampleable later
auto fut = vuk::transition(vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "10_doge" }, vuk::eFragmentSampled);
runner.enqueue_setup(std::move(fut));
// Set up the resources for our renderer
// Create meshes
cube_mesh.emplace();
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnTransfer, std::span(box.first));
cube_mesh->vertex_buffer = std::move(vert_buf);
auto [idx_buf, idx_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnTransfer, std::span(box.second));
cube_mesh->index_buffer = std::move(idx_buf);
cube_mesh->index_count = (uint32_t)box.second.size();
quad_mesh.emplace();
auto [vert_buf2, vert_fut2] =
create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnTransfer, std::span(&box.first[0], 6));
quad_mesh->vertex_buffer = std::move(vert_buf2);
auto [idx_buf2, idx_fut2] =
create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnTransfer, std::span(&box.second[0], 6));
quad_mesh->index_buffer = std::move(idx_buf2);
quad_mesh->index_count = 6;
runner.enqueue_setup(std::move(vert_fut));
runner.enqueue_setup(std::move(idx_fut));
runner.enqueue_setup(std::move(vert_fut2));
runner.enqueue_setup(std::move(idx_fut2));
// Create the pipelines
// A "normal" pipeline
vuk::PipelineBaseInfo* pipe1;
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/baby_renderer.vert").generic_string()), (root / "examples/baby_renderer.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle_depthshaded_tex.frag").generic_string()), (root / "examples/triangle_depthshaded_tex.frag").generic_string());
pipe1 = runner.context->get_pipeline(pci);
}
// A "tinted" pipeline
vuk::PipelineBaseInfo* pipe2;
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/baby_renderer.vert").generic_string()), (root / "examples/baby_renderer.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle_tinted_tex.frag").generic_string()), (root / "examples/triangle_tinted_tex.frag").generic_string());
pipe2 = runner.context->get_pipeline(pci);
}
// Create materials
nmats.resize(3);
nmats[0].texture = texture_of_doge->view.get();
nmats[1].texture = variant1->view.get();
nmats[2].texture = variant2->view.get();
for (auto& mat : nmats) {
mat.pipeline = pipe1;
}
tmats.resize(3);
std::uniform_real_distribution<float> dist_tint(0, 1);
tmats[0].texture = texture_of_doge->view.get();
tmats[1].texture = variant1->view.get();
tmats[2].texture = variant2->view.get();
for (auto& mat : tmats) {
mat.pipeline = pipe2;
mat.tint_color = glm::vec4(dist_tint(g), dist_tint(g), dist_tint(g), 1.f);
}
// Create objects
std::uniform_int_distribution<size_t> dist_mat(0, 1);
std::uniform_int_distribution<size_t> dist_tex(0, 2);
std::uniform_real_distribution<float> dist_pos(-10, 10);
// 64 quads
for (int i = 0; i < 64; i++) {
auto mat_id = dist_mat(g);
auto tex_id = dist_tex(g);
Material* m = mat_id == 0 ? (Material*)&nmats[tex_id] : (Material*)&tmats[tex_id];
glm::vec3 pos = glm::vec3(dist_pos(g), dist_pos(g), dist_pos(g));
renderables.emplace_back(Renderable{ .mesh = &*quad_mesh, .material = m, .position = pos });
}
// 16 cubes
for (int i = 0; i < 16; i++) {
auto mat_id = dist_mat(g);
auto tex_id = dist_tex(g);
Material* m = mat_id == 0 ? (Material*)&nmats[tex_id] : (Material*)&tmats[tex_id];
glm::vec3 pos = glm::vec3(dist_pos(g), dist_pos(g), dist_pos(g));
renderables.emplace_back(Renderable{ .mesh = &*cube_mesh, .material = m, .position = pos });
}
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
// We set up VP data, same as in example 02_cube
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
vp.view = glm::lookAt(glm::vec3(0, 10.0, 11), glm::vec3(0), glm::vec3(0, 1, 0));
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 1.f, 100.f);
vp.proj[1][1] *= -1;
// Upload view & projection
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
// Do a terrible simulation step
// All objects are attracted to the origin
for (auto& r : renderables) {
auto force_mag = 0.1f / glm::length(r.position);
r.velocity += force_mag * (-r.position) * ImGui::GetIO().DeltaTime;
r.position += r.velocity * ImGui::GetIO().DeltaTime;
}
// Upload model matrices to an array
auto modelmats = **allocate_buffer(frame_allocator, { vuk::MemoryUsage::eCPUtoGPU, sizeof(glm::mat4) * renderables.size(), 1 });
for (auto i = 0; i < renderables.size(); i++) {
glm::mat4 model_matrix = glm::translate(glm::mat4(1.f), renderables[i].position);
memcpy(reinterpret_cast<glm::mat4*>(modelmats.mapped_ptr) + i, &model_matrix, sizeof(glm::mat4));
}
vuk::RenderGraph rg("10");
rg.attach_in("10_baby_renderer", std::move(target));
// Set up the pass to draw the renderables
rg.add_pass({ .name = "forward",
.resources = { "10_baby_renderer"_image >> vuk::eColorWrite >> "10_baby_renderer_final", "10_depth"_image >> vuk::eDepthStencilRW },
.execute = [uboVP, modelmats](vuk::CommandBuffer& command_buffer) {
command_buffer.set_dynamic_state(vuk::DynamicStateFlagBits::eViewport | vuk::DynamicStateFlagBits::eScissor)
.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
.depthWriteEnable = true,
.depthCompareOp = vuk::CompareOp::eLessOrEqual,
})
.broadcast_color_blend({}); // Set the default color blend state
// These binds don't change between meshes, so it is sufficient to bind them once
command_buffer.bind_buffer(0, 0, uboVP).bind_buffer(0, 1, modelmats);
for (auto i = 0; i < renderables.size(); i++) {
auto& r = renderables[i];
// Set up the draw state based on the mesh and material
command_buffer
.bind_vertex_buffer(0,
r.mesh->vertex_buffer.get(),
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat,
vuk::Ignore{ offsetof(util::Vertex, uv_coordinates) - sizeof(util::Vertex::position) },
vuk::Format::eR32G32Sfloat })
.bind_index_buffer(r.mesh->index_buffer.get(), vuk::IndexType::eUint32)
.bind_graphics_pipeline(r.material->pipeline);
r.material->bind_parameters(command_buffer);
r.material->bind_textures(command_buffer);
// Draw the mesh, assign them different base instance to pick the correct transformation
command_buffer.draw_indexed(r.mesh->index_count, 1, 0, 0, i);
}
} });
angle += 10.f * ImGui::GetIO().DeltaTime;
rg.attach_and_clear_image("10_depth", { .format = vuk::Format::eD32Sfloat }, vuk::ClearDepthStencil{ 1.0f, 0 });
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "10_baby_renderer_final" };
},
// Perform cleanup for the example
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
// We release the resources manually
cube_mesh.reset();
quad_mesh.reset();
texture_of_doge.reset();
variant1.reset();
variant2.reset();
}
};
REGISTER_EXAMPLE(xample);
} // namespace<file_sep>#include "TestContext.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/Partials.hpp"
#include <doctest/doctest.h>
using namespace vuk;
struct AllocatorChecker : DeviceNestedResource {
int32_t counter = 0;
AllocatorChecker(DeviceResource& upstream) : DeviceNestedResource(upstream) {}
Result<void, AllocateException> allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) override {
counter += cis.size();
return upstream->allocate_buffers(dst, cis, loc);
}
void deallocate_buffers(std::span<const Buffer> src) override {
counter -= src.size();
upstream->deallocate_buffers(src);
}
Result<void, AllocateException> allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) override {
counter += cis.size();
return upstream->allocate_images(dst, cis, loc);
}
void deallocate_images(std::span<const Image> src) override {
counter -= src.size();
upstream->deallocate_images(src);
}
};
TEST_CASE("superframe allocator, uncached resource") {
REQUIRE(test_context.prepare());
AllocatorChecker ac(*test_context.sfa_resource);
DeviceSuperFrameResource sfr(ac, 2);
Buffer buf;
BufferCreateInfo bci{ .mem_usage = vuk::MemoryUsage::eCPUonly, .size = 1024 };
sfr.allocate_buffers(std::span{ &buf, 1 }, std::span{ &bci, 1 }, {});
sfr.deallocate_buffers(std::span{ &buf, 1 });
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
REQUIRE(ac.counter == 0);
}
/* TEST_CASE("frame allocator, uncached resource") {
REQUIRE(test_context.prepare());
AllocatorChecker ac(*test_context.sfa_resource);
DeviceSuperFrameResource sfr(ac, 2);
Buffer buf;
BufferCreateInfo bci{ .mem_usage = vuk::MemoryUsage::eCPUonly, .size = 1024 };
auto& fa = sfr.get_next_frame();
fa.allocate_buffers(std::span{ &buf, 1 }, std::span{ &bci, 1 }, {});
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
REQUIRE(ac.counter == 0);
}*/
TEST_CASE("frame allocator, cached resource") {
REQUIRE(test_context.prepare());
AllocatorChecker ac(*test_context.sfa_resource);
DeviceSuperFrameResource sfr(ac, 2);
Image im;
ImageCreateInfo ici{ .format = vuk::Format::eR8G8B8A8Srgb, .extent = vuk::Extent3D{100, 100, 1}, .usage = vuk::ImageUsageFlagBits::eColorAttachment };
auto& fa = sfr.get_next_frame();
fa.allocate_images(std::span{ &im, 1 }, std::span{ &ici, 1 }, {});
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
sfr.force_collect();
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
REQUIRE(ac.counter == 0);
}
TEST_CASE("frame allocator, cached resource identity") {
REQUIRE(test_context.prepare());
AllocatorChecker ac(*test_context.sfa_resource);
DeviceSuperFrameResource sfr(ac, 2);
Image im1;
Image im2;
ImageCreateInfo ici{ .format = vuk::Format::eR8G8B8A8Srgb, .extent = vuk::Extent3D{ 100, 100, 1 }, .usage = vuk::ImageUsageFlagBits::eColorAttachment };
{
auto& fa = sfr.get_next_frame();
fa.allocate_images(std::span{ &im1, 1 }, std::span{ &ici, 1 }, {});
fa.allocate_images(std::span{ &im2, 1 }, std::span{ &ici, 1 }, {});
}
REQUIRE(im1 != im2);
Image im3;
Image im4;
{
auto& fa = sfr.get_next_frame();
fa.allocate_images(std::span{ &im3, 1 }, std::span{ &ici, 1 }, {});
fa.allocate_images(std::span{ &im4, 1 }, std::span{ &ici, 1 }, {});
}
REQUIRE((im1 == im3 || im1 == im4));
REQUIRE((im2 == im3 || im2 == im4));
}
/*
TEST_CASE("multiframe allocator, uncached resource") {
REQUIRE(test_context.prepare());
AllocatorChecker ac(*test_context.sfa_resource);
DeviceSuperFrameResource sfr(ac, 2);
Buffer buf;
BufferCreateInfo bci{ .mem_usage = vuk::MemoryUsage::eCPUonly, .size = 1024 };
auto& mfa = sfr.get_multiframe_allocator(3);
mfa.allocate_buffers(std::span{ &buf, 1 }, std::span{ &bci, 1 }, {});
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
sfr.get_next_frame();
sfr.get_next_frame();
REQUIRE(ac.counter == 0);
}*/
TEST_CASE("multiframe allocator, cached resource") {
REQUIRE(test_context.prepare());
AllocatorChecker ac(*test_context.sfa_resource);
DeviceSuperFrameResource sfr(ac, 2);
Image im;
ImageCreateInfo ici{ .format = vuk::Format::eR8G8B8A8Srgb, .extent = vuk::Extent3D{ 100, 100, 1 }, .usage = vuk::ImageUsageFlagBits::eColorAttachment };
auto& mfa = sfr.get_multiframe_allocator(3);
mfa.allocate_images(std::span{ &im, 1 }, std::span{ &ici, 1 }, {});
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
sfr.get_next_frame();
sfr.get_next_frame();
sfr.force_collect();
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
REQUIRE(ac.counter == 1);
sfr.get_next_frame();
REQUIRE(ac.counter == 0);
}
TEST_CASE("multiframe allocator, cached resource identity for different MFAs") {
REQUIRE(test_context.prepare());
AllocatorChecker ac(*test_context.sfa_resource);
DeviceSuperFrameResource sfr(ac, 2);
Image im1;
Image im2;
ImageCreateInfo ici{ .format = vuk::Format::eR8G8B8A8Srgb, .extent = vuk::Extent3D{ 100, 100, 1 }, .usage = vuk::ImageUsageFlagBits::eColorAttachment };
{
auto& mfa = sfr.get_multiframe_allocator(3);
mfa.allocate_images(std::span{ &im1, 1 }, std::span{ &ici, 1 }, {});
mfa.allocate_images(std::span{ &im2, 1 }, std::span{ &ici, 1 }, {});
}
REQUIRE(im1 != im2);
Image im3;
Image im4;
{
auto& mfa = sfr.get_multiframe_allocator(3);
mfa.allocate_images(std::span{ &im3, 1 }, std::span{ &ici, 1 }, {});
mfa.allocate_images(std::span{ &im4, 1 }, std::span{ &ici, 1 }, {});
}
REQUIRE(im3 != im4);
REQUIRE((im3 != im1 && im3 != im2));
REQUIRE((im4 != im1 && im4 != im2));
}<file_sep>#pragma once
#include "../src/CreateInfo.hpp"
#include "vuk/Config.hpp"
#include "vuk/vuk_fwd.hpp"
#include <array>
#include <string>
#include <unordered_map>
#include <vector>
namespace vuk {
struct Program {
enum class Type {
einvalid,
euint,
euint64_t,
eint,
eint64_t,
efloat,
edouble,
euvec2,
euvec3,
euvec4,
eivec2,
eivec3,
eivec4,
evec2,
evec3,
evec4,
edvec2,
edvec3,
edvec4,
emat3,
emat4,
edmat3,
edmat4,
eu64vec2,
eu64vec3,
eu64vec4,
ei64vec2,
ei64vec3,
ei64vec4,
estruct
};
struct Attribute {
std::string name;
size_t location;
Type type;
};
struct TextureAddress {
unsigned container;
float page;
};
struct Member {
std::string name;
std::string type_name; // if this is a struct
Type type;
size_t size;
size_t offset;
unsigned array_size;
std::vector<Member> members;
};
// always a struct
struct UniformBuffer {
std::string name;
unsigned binding;
size_t size;
unsigned array_size;
std::vector<Member> members;
VkShaderStageFlags stage;
};
struct StorageBuffer {
std::string name;
unsigned binding;
size_t min_size;
bool is_hlsl_counter_buffer = false;
std::vector<Member> members;
VkShaderStageFlags stage;
};
struct StorageImage {
std::string name;
unsigned array_size;
unsigned binding;
VkShaderStageFlags stage;
};
struct SampledImage {
std::string name;
unsigned array_size;
unsigned binding;
VkShaderStageFlags stage;
};
struct CombinedImageSampler {
std::string name;
unsigned array_size;
unsigned binding;
bool shadow; // if this is a samplerXXXShadow
VkShaderStageFlags stage;
};
struct Sampler {
std::string name;
unsigned array_size;
unsigned binding;
bool shadow; // if this is a samplerShadow
VkShaderStageFlags stage;
};
struct TexelBuffer {
std::string name;
unsigned binding;
VkShaderStageFlags stage;
};
struct SubpassInput {
std::string name;
unsigned binding;
VkShaderStageFlags stage;
};
struct AccelerationStructure {
std::string name;
unsigned array_size;
unsigned binding;
VkShaderStageFlags stage;
};
struct SpecConstant {
unsigned binding; // constant_id
Type type;
VkShaderStageFlags stage;
};
VkShaderStageFlagBits introspect(const uint32_t* ir, size_t word_count);
std::array<unsigned, 3> local_size;
std::vector<Attribute> attributes;
std::vector<VkPushConstantRange> push_constant_ranges;
std::vector<SpecConstant> spec_constants;
struct Descriptors {
std::vector<UniformBuffer> uniform_buffers;
std::vector<StorageBuffer> storage_buffers;
std::vector<StorageImage> storage_images;
std::vector<TexelBuffer> texel_buffers;
std::vector<CombinedImageSampler> combined_image_samplers;
std::vector<SampledImage> sampled_images;
std::vector<Sampler> samplers;
std::vector<SubpassInput> subpass_inputs;
std::vector<AccelerationStructure> acceleration_structures;
unsigned highest_descriptor_binding = 0;
};
std::unordered_map<size_t, Descriptors> sets;
VkShaderStageFlags stages = {};
void append(const Program& o);
};
struct ShaderModule {
VkShaderModule shader_module;
vuk::Program reflection_info;
VkShaderStageFlagBits stage;
};
struct ShaderModuleCreateInfo;
template<>
struct create_info<vuk::ShaderModule> {
using type = vuk::ShaderModuleCreateInfo;
};
} // namespace vuk
namespace std {
template<>
struct hash<vuk::ShaderModuleCreateInfo> {
size_t operator()(vuk::ShaderModuleCreateInfo const& x) const noexcept;
};
}; // namespace std
<file_sep>#include "vuk/RenderGraph.hpp"
#include "RenderGraphImpl.hpp"
#include "RenderGraphUtil.hpp"
#include "vuk/CommandBuffer.hpp"
#include "vuk/Context.hpp"
#include "vuk/Exception.hpp"
#include "vuk/Future.hpp"
#include <charconv>
#include <set>
#include <sstream>
#include <unordered_set>
#include <bit>
// intrinsics
namespace {
void diverge(vuk::CommandBuffer&) {}
void converge(vuk::CommandBuffer&) {}
} // namespace
namespace vuk {
RenderGraph::RenderGraph() : impl(new RGImpl) {
name = Name(std::to_string(reinterpret_cast<uintptr_t>(impl)));
}
RenderGraph::RenderGraph(Name name) : name(name), impl(new RGImpl) {}
RenderGraph::RenderGraph(RenderGraph&& o) noexcept : name(o.name), impl(std::exchange(o.impl, nullptr)) {}
RenderGraph& RenderGraph::operator=(RenderGraph&& o) noexcept {
impl = std::exchange(o.impl, nullptr);
name = o.name;
return *this;
}
RenderGraph::~RenderGraph() {
delete impl;
}
void RenderGraph::add_pass(Pass p, source_location source) {
PassWrapper pw;
pw.name = p.name;
pw.arguments = p.arguments;
pw.execute = std::move(p.execute);
pw.execute_on = p.execute_on;
pw.resources.offset0 = impl->resources.size();
impl->resources.insert(impl->resources.end(), p.resources.begin(), p.resources.end());
pw.resources.offset1 = impl->resources.size();
pw.type = p.type;
pw.source = std::move(source);
impl->passes.emplace_back(std::move(pw));
}
void RGCImpl::append(Name subgraph_name, const RenderGraph& other) {
Name joiner = subgraph_name.is_invalid() ? Name("") : subgraph_name;
for (auto [new_name, old_name] : other.impl->aliases) {
computed_aliases.emplace(QualifiedName{ joiner, new_name }, QualifiedName{ Name{}, old_name });
}
for (auto& p : other.impl->passes) {
PassInfo& pi = computed_passes.emplace_back(p);
pi.qualified_name = { joiner, p.name };
pi.resources.offset0 = resources.size();
for (auto r : p.resources.to_span(other.impl->resources)) {
r.original_name = r.name.name;
if (r.foreign) {
auto prefix = Name{ std::find_if(sg_prefixes.begin(), sg_prefixes.end(), [=](auto& kv) { return kv.first == r.foreign; })->second };
auto full_src_prefix = !r.name.prefix.is_invalid() ? prefix.append(r.name.prefix.to_sv()) : prefix;
auto res_name = resolve_alias_rec({ full_src_prefix, r.name.name });
auto res_out_name = r.out_name.name.is_invalid() ? QualifiedName{} : resolve_alias_rec({ full_src_prefix, r.out_name.name });
auto full_dst_prefix = !r.name.prefix.is_invalid() ? joiner.append(r.name.prefix.to_sv()) : joiner;
computed_aliases.emplace(QualifiedName{ full_dst_prefix, r.name.name }, res_name);
r.name = res_name;
if (!r.out_name.is_invalid()) {
computed_aliases.emplace(QualifiedName{ full_dst_prefix, r.out_name.name }, res_out_name);
r.out_name = res_out_name;
}
} else {
if (!r.name.name.is_invalid()) {
r.name = resolve_alias_rec({ joiner, r.name.name });
}
r.out_name = r.out_name.name.is_invalid() ? QualifiedName{} : resolve_alias_rec({ joiner, r.out_name.name });
}
resources.emplace_back(std::move(r));
}
pi.resources.offset1 = resources.size();
}
for (auto [name, att] : other.impl->bound_attachments) {
att.name = { joiner, name.name };
bound_attachments.emplace_back(std::move(att));
}
for (auto [name, buf] : other.impl->bound_buffers) {
buf.name = { joiner, name.name };
bound_buffers.emplace_back(std::move(buf));
}
for (auto [name, iainf] : other.impl->ia_inference_rules) {
auto& rule = ia_inference_rules[resolve_alias_rec(QualifiedName{ joiner, name.name })];
rule.prefix = joiner;
rule.rules.emplace_back(iainf);
}
for (auto [name, bufinf] : other.impl->buf_inference_rules) {
auto& rule = buf_inference_rules[resolve_alias_rec(QualifiedName{ joiner, name.name })];
rule.prefix = joiner;
rule.rules.emplace_back(bufinf);
}
for (auto& [name, v] : other.impl->releases) {
auto res_name = resolve_alias_rec({ joiner, name.name });
releases.emplace_back(res_name, v);
}
for (auto [name, v] : other.impl->diverged_subchain_headers) {
v.first.prefix = joiner;
diverged_subchain_headers.emplace(QualifiedName{ joiner, name.name }, v);
}
}
void RenderGraph::add_alias(Name new_name, Name old_name) {
if (new_name != old_name) {
impl->aliases.emplace_back(new_name, old_name);
}
}
void RenderGraph::diverge_image(Name whole_name, Subrange::Image subrange, Name subrange_name) {
impl->diverged_subchain_headers.emplace_back(QualifiedName{ Name{}, subrange_name }, std::pair{ QualifiedName{ Name{}, whole_name }, subrange });
add_pass({ .name = whole_name.append("_DIVERGE"),
.resources = { Resource{ whole_name, Resource::Type::eImage, Access::eConsume, subrange_name } },
.execute = diverge,
.type = PassType::eDiverge });
}
void RenderGraph::converge_image_explicit(std::span<Name> pre_diverge, Name post_diverge) {
Pass post{ .name = post_diverge.append("_CONVERGE"), .execute = converge, .type = PassType::eConverge };
post.resources.emplace_back(Resource{ Name{}, Resource::Type::eImage, Access::eConverge, post_diverge });
for (auto& name : pre_diverge) {
post.resources.emplace_back(Resource{ name, Resource::Type::eImage, Access::eConsume });
}
add_pass(std::move(post));
}
void RGCImpl::merge_diverge_passes(std::vector<PassInfo, short_alloc<PassInfo, 64>>& passes) {
std::unordered_map<QualifiedName, PassInfo*> merge_passes;
for (auto& pass : passes) {
if (pass.pass->type == PassType::eDiverge) {
auto& pi = merge_passes[pass.qualified_name];
if (!pi) {
pi = &pass;
auto res = pass.resources.to_span(resources)[0];
res.name = {};
pass.resources.append(resources, res);
pass.resources.to_span(resources)[0].out_name = {};
} else {
auto o = pass.resources.to_span(resources);
assert(o.size() == 1);
o[0].name = {};
pi->resources.append(resources, o[0]);
pass.resources = {};
}
}
}
std::erase_if(passes, [](auto& pass) { return pass.pass->type == PassType::eDiverge && pass.resources.size() == 0; });
}
Result<void> build_links(std::span<PassInfo> passes, ResourceLinkMap& res_to_links, std::vector<Resource>& resources, std::vector<ChainAccess>& pass_reads) {
// build edges into link map
// reserving here to avoid rehashing map
res_to_links.clear();
res_to_links.reserve(passes.size() * 10);
for (auto pass_idx = 0; pass_idx < passes.size(); pass_idx++) {
auto& pif = passes[pass_idx];
for (Resource& res : pif.resources.to_span(resources)) {
bool is_undef = false;
bool is_def = !res.out_name.is_invalid();
int32_t res_idx = static_cast<int32_t>(&res - &*pif.resources.to_span(resources).begin());
if (!res.name.is_invalid()) {
auto& r_io = res_to_links[res.name];
r_io.type = res.type;
if (!is_write_access(res.ia) && pif.pass->type != PassType::eForcedAccess && res.ia != Access::eConsume) {
r_io.reads.append(pass_reads, { pass_idx, res_idx });
}
if (is_write_access(res.ia) || res.ia == Access::eConsume || pif.pass->type == PassType::eForcedAccess) {
r_io.undef = { pass_idx, res_idx };
is_undef = true;
if (is_def) {
r_io.next = &res_to_links[res.out_name];
}
}
}
if (is_def) {
auto& w_io = res_to_links[res.out_name];
w_io.def = { pass_idx, res_idx };
w_io.type = res.type;
if (is_undef) {
w_io.prev = &res_to_links[res.name];
}
}
}
}
return { expected_value };
}
Result<void> RGCImpl::terminate_chains() {
// introduce chain links with inputs (acquired and attached buffers & images) and outputs (releases)
// these are denoted with negative indices
for (auto& bound : bound_attachments) {
res_to_links[bound.name].def = { .pass = static_cast<int32_t>(-1 * (&bound - &*bound_attachments.begin() + 1)) };
}
for (auto& bound : bound_buffers) {
res_to_links[bound.name].def = { .pass = static_cast<int32_t>(-1 * (&bound - &*bound_buffers.begin() + 1)) };
}
for (auto& bound : releases) {
res_to_links[bound.first].undef = { .pass = static_cast<int32_t>(-1 * (&bound - &*releases.begin() + 1)) };
}
return { expected_value };
}
Result<void> collect_chains(ResourceLinkMap& res_to_links, std::vector<ChainLink*>& chains) {
chains.clear();
// collect chains by looking at links without a prev
for (auto& [name, link] : res_to_links) {
if (!link.prev) {
chains.push_back(&link);
}
}
return { expected_value };
}
Result<void> RGCImpl::diagnose_unheaded_chains() {
// diagnose unheaded chains at this point
for (auto& chp : chains) {
if (!chp->def) {
if (chp->reads.size() > 0) {
auto& pass = get_pass(chp->reads.to_span(pass_reads)[0]);
auto& res = get_resource(chp->reads.to_span(pass_reads)[0]);
return { expected_error, errors::make_unattached_resource_exception(pass, res) };
}
if (chp->undef && chp->undef->pass >= 0) {
auto& pass = get_pass(*chp->undef);
auto& res = get_resource(*chp->undef);
return { expected_error, errors::make_unattached_resource_exception(pass, res) };
}
}
}
return { expected_value };
}
Result<void> RGCImpl::schedule_intra_queue(std::span<PassInfo> passes, const RenderGraphCompileOptions& compile_options) {
// calculate indegrees for all passes & build adjacency
std::vector<size_t> indegrees(passes.size());
std::vector<uint8_t> adjacency_matrix(passes.size() * passes.size());
for (auto& [qfname, link] : res_to_links) {
if (link.undef && (link.undef->pass >= 0) &&
((link.def && link.def->pass >= 0) || link.reads.size() > 0)) { // we only care about an undef if the def or reads are in the graph
indegrees[link.undef->pass]++;
if (link.def) {
adjacency_matrix[link.def->pass * passes.size() + link.undef->pass]++; // def -> undef
}
}
for (auto& read : link.reads.to_span(pass_reads)) {
if ((link.def && link.def->pass >= 0)) {
indegrees[read.pass]++; // this only counts as a dep if there is a def before
adjacency_matrix[link.def->pass * passes.size() + read.pass]++; // def -> read
}
if ((link.undef && link.undef->pass >= 0)) {
indegrees[link.undef->pass]++;
adjacency_matrix[read.pass * passes.size() + link.undef->pass]++; // read -> undef
}
}
}
// enqueue all indegree == 0 passes
std::vector<size_t> process_queue;
for (auto i = 0; i < indegrees.size(); i++) {
if (indegrees[i] == 0)
process_queue.push_back(i);
}
// dequeue indegree = 0 pass, add it to the ordered list, then decrement adjacent pass indegrees and push indegree == 0 to queue
computed_pass_idx_to_ordered_idx.resize(passes.size());
ordered_idx_to_computed_pass_idx.resize(passes.size());
while (process_queue.size() > 0) {
auto pop_idx = process_queue.back();
computed_pass_idx_to_ordered_idx[pop_idx] = ordered_passes.size();
ordered_idx_to_computed_pass_idx[ordered_passes.size()] = pop_idx;
ordered_passes.emplace_back(&passes[pop_idx]);
process_queue.pop_back();
for (auto i = 0; i < passes.size(); i++) { // all the outgoing from this pass
if (i == pop_idx) {
continue;
}
auto adj_value = adjacency_matrix[pop_idx * passes.size() + i];
if (adj_value > 0) {
if (indegrees[i] -= adj_value; indegrees[i] == 0) {
process_queue.push_back(i);
}
}
}
}
assert(ordered_passes.size() == passes.size());
return { expected_value };
}
Result<void> RGCImpl::fix_subchains() {
// subchain fixup pass
// connect subchains
// diverging subchains are chains where def->pass >= 0 AND def->pass type is eDiverge
// reconverged subchains are chains where def->pass >= 0 AND def->pass type is eConverge
for (auto& head : chains) {
if (head->def->pass >= 0 && head->type == Resource::Type::eImage) { // no Buffer divergence
auto& pass = get_pass(*head->def);
if (pass.pass->type == PassType::eDiverge) { // diverging subchain
auto& whole_res = pass.resources.to_span(resources)[0].name;
auto parent_chain_end = &res_to_links[whole_res];
head->source = parent_chain_end;
parent_chain_end->child_chains.append(child_chains, head);
} else if (pass.pass->type == PassType::eConverge) { // reconverged subchain
// take first resource which guaranteed to be diverged
auto div_resources = pass.resources.to_span(resources).subspan(1);
for (auto& res : div_resources) {
res_to_links[res.name].destination = head;
}
}
}
}
// fixup diverge subchains by copying first use on the converge subchain to their end
for (auto& head : chains) {
if (head->source) { // a diverged subchain
// seek to the end
ChainLink* chain;
for (chain = head; chain->destination == nullptr; chain = chain->next)
;
auto last_chain_on_diverged = chain;
auto first_chain_on_converged = chain->destination;
if (first_chain_on_converged->reads.size() > 0) { // first use is reads
// take the reads
for (auto& r : first_chain_on_converged->reads.to_span(pass_reads)) {
last_chain_on_diverged->reads.append(pass_reads, r);
}
// remove the undef from the diverged chain
last_chain_on_diverged->undef = {};
} else if (first_chain_on_converged->undef) {
// take the undef from the converged chain and put it on the diverged chain undef
last_chain_on_diverged->undef = first_chain_on_converged->undef;
// we need to add a release to nothing to preserve the last undef
ChainLink helper;
helper.prev = last_chain_on_diverged;
helper.def = last_chain_on_diverged->undef;
helper.type = last_chain_on_diverged->type;
auto& rel = releases.emplace_back(QualifiedName{}, Release{});
helper.undef = { .pass = static_cast<int32_t>(-1 * (&rel - &*releases.begin() + 1)) };
auto& new_link = helper_links.emplace_back(helper);
last_chain_on_diverged->next = &new_link;
}
}
}
// take all diverged subchains and replace their def with a new attachment that has the proper acq and subrange
for (auto& head : chains) {
if (head->def->pass >= 0 && head->type == Resource::Type::eImage) { // no Buffer divergence
auto& pass = get_pass(*head->def);
if (pass.pass->type == PassType::eDiverge) { // diverging subchain
// whole resource is always first resource
auto& whole_res = pass.resources.to_span(resources)[0].name;
auto link = &res_to_links[whole_res];
while (link->prev) { // seek to the head of the original chain
link = link->prev;
}
auto att = get_bound_attachment(link->def->pass); // the original chain attachment, make copy
auto& our_res = get_resource(*head->def);
att.image_subrange = diverged_subchain_headers.at(our_res.out_name).second; // look up subrange referenced by this subchain
att.name = QualifiedName{ Name{}, att.name.name.append(our_res.out_name.name.to_sv()) };
att.parent_attachment = link->def->pass;
auto new_bound = bound_attachments.emplace_back(att);
// replace def with new attachment
head->def = { .pass = static_cast<int32_t>(-1 * bound_attachments.size()) };
}
}
}
// fixup converge subchains by removing the first use
for (auto& head : chains) {
if (head->def->pass >= 0 && head->type == Resource::Type::eImage) { // no Buffer divergence
auto& pass = get_pass(*head->def);
if (pass.pass->type == PassType::eConverge) { // converge subchain
if (head->reads.size() > 0) { // first use is reads
head->reads = {}; // remove the reads
} else if (head->undef) { // first use is undef
head = head->next; // drop link from chain
head->prev = nullptr;
}
// reconverged resource is always first resource
auto& whole_res = pass.resources.to_span(resources)[0];
// take first resource which guaranteed to be diverged
auto div_resources = pass.resources.to_span(resources).subspan(1);
auto& div_res = div_resources[1];
// TODO: we actually need to walk all converging resources here to find the scope of the convergence
// walk this resource to convergence
auto link = &res_to_links[div_res.name];
while (link->prev) { // seek to the head of the diverged chain
link = link->prev;
}
assert(link->source);
link = link->source;
head->source = link; // set the source for this subchain the original undiv chain
link->child_chains.append(child_chains, head);
while (link->prev) { // seek to the head of the original chain
link = link->prev;
}
auto whole_att = get_bound_attachment(link->def->pass); // the whole attachment
whole_att.name = QualifiedName{ Name{}, whole_att.name.name.append(whole_res.out_name.name.to_sv()) };
whole_att.acquire.unsynchronized = true;
whole_att.parent_attachment = link->def->pass;
auto new_bound = bound_attachments.emplace_back(whole_att);
// replace head->def with new attachments (the converged resource)
head->def = { .pass = static_cast<int32_t>(-1 * bound_attachments.size()) };
}
}
}
return { expected_value };
// TODO: validate incorrect convergence
/* else if (chain.back().high_level_access == Access::eConverge) {
assert(it->second.dst_use.layout != ImageLayout::eUndefined); // convergence into no use = disallowed
}*/
//
}
std::string Compiler::dump_graph() {
std::stringstream ss;
/* ss << "digraph vuk {\n";
for (auto i = 0; i < impl->computed_passes.size(); i++) {
for (auto j = 0; j < impl->computed_passes.size(); j++) {
if (i == j)
continue;
auto& p1 = impl->computed_passes[i];
auto& p2 = impl->computed_passes[j];
for (auto& o : p1.output_names.to_span(impl->output_names)) {
for (auto& i : p2.input_names.to_span(impl->input_names)) {
if (o == impl->resolve_alias(i)) {
ss << "\"" << p1.pass->name.c_str() << "\" -> \"" << p2.pass->name.c_str() << "\" [label=\"" << impl->resolve_alias(i).name.c_str() << "\"];\n";
// p2 is ordered after p1
}
}
}
for (auto& o : p1.input_names.to_span(impl->input_names)) {
for (auto& i : p2.write_input_names.to_span(impl->write_input_names)) {
if (impl->resolve_alias(o) == impl->resolve_alias(i)) {
ss << "\"" << p1.pass->name.c_str() << "\" -> \"" << p2.pass->name.c_str() << "\" [label=\"" << impl->resolve_alias(i).name.c_str() << "\"];\n";
// p2 is ordered after p1
}
}
}
}
}
ss << "}\n";*/
return ss.str();
}
void RGCImpl::compute_prefixes(const RenderGraph& rg, std::string& prefix) {
auto prefix_current_size = prefix.size();
prefix.append(rg.name.c_str());
if (auto& counter = ++sg_name_counter[rg.name]; counter > 1) {
prefix.append("#");
prefix.resize(prefix.size() + 10);
auto [ptr, ec] = std::to_chars(prefix.data() + prefix.size() - 10, prefix.data() + prefix.size(), counter - 1);
assert(ec == std::errc());
prefix.resize(ptr - prefix.data());
}
sg_prefixes.emplace(&rg, prefix);
prefix.append("::");
for (auto& [sg_ptr, sg_info] : rg.impl->subgraphs) {
if (sg_info.count > 0) {
assert(sg_ptr->impl);
compute_prefixes(*sg_ptr, prefix);
}
}
prefix.resize(prefix_current_size); // rewind prefix
}
void RGCImpl::inline_subgraphs(const RenderGraph& rg, robin_hood::unordered_flat_set<RenderGraph*>& consumed_rgs) {
auto our_prefix = sg_prefixes.at(&rg);
for (auto& [sg_ptr, sg_info] : rg.impl->subgraphs) {
auto sg_raw_ptr = sg_ptr.get();
if (sg_info.count > 0) {
auto prefix = sg_prefixes.at(sg_raw_ptr);
assert(sg_raw_ptr->impl);
for (auto& [name_in_parent, name_in_sg] : sg_info.exported_names) {
QualifiedName old_name;
if (!name_in_sg.prefix.is_invalid()) { // unfortunately, prefix + name_in_sg.prefix duplicates the name of the sg, so remove it
std::string fixed_prefix = prefix.substr(0, prefix.size() - sg_raw_ptr->name.to_sv().size());
fixed_prefix.append(name_in_sg.prefix.to_sv());
old_name = QualifiedName{ Name(fixed_prefix), name_in_sg.name };
} else {
old_name = QualifiedName{ Name(prefix), name_in_sg.name };
}
auto new_name = QualifiedName{ our_prefix.empty() ? Name{} : Name(our_prefix), name_in_parent };
computed_aliases[new_name] = old_name;
}
if (!consumed_rgs.contains(sg_raw_ptr)) {
inline_subgraphs(*sg_raw_ptr, consumed_rgs);
append(Name(prefix), *sg_raw_ptr);
consumed_rgs.emplace(sg_raw_ptr);
}
}
}
}
Compiler::Compiler() : impl(new RGCImpl) {}
Compiler::~Compiler() {
delete impl;
}
Result<void> Compiler::inline_rgs(std::span<std::shared_ptr<RenderGraph>> rgs) {
// inline all the subgraphs into us
robin_hood::unordered_flat_set<RenderGraph*> consumed_rgs = {};
std::string prefix = "";
for (auto& rg : rgs) {
impl->compute_prefixes(*rg, prefix);
consumed_rgs.clear();
impl->inline_subgraphs(*rg, consumed_rgs);
}
for (auto& rg : rgs) {
auto our_prefix = std::find_if(impl->sg_prefixes.begin(), impl->sg_prefixes.end(), [rgp = rg.get()](auto& kv) { return kv.first == rgp; })->second;
impl->append(Name{ our_prefix.c_str() }, *rg);
}
return { expected_value };
}
void RGCImpl::compute_assigned_names() {
// gather name alias info now - once we partition, we might encounter unresolved aliases
robin_hood::unordered_flat_map<QualifiedName, QualifiedName> name_map;
name_map.insert(computed_aliases.begin(), computed_aliases.end());
for (auto& passinfo : computed_passes) {
for (auto& res : passinfo.resources.to_span(resources)) {
// for read or write, we add source to use chain
if (!res.name.is_invalid() && !res.out_name.is_invalid()) {
auto [iter, succ] = name_map.emplace(res.out_name, res.name);
assert(iter->second == res.name);
}
}
}
assigned_names.clear();
// populate resource name -> use chain map
for (auto& [k, v] : name_map) {
auto it = name_map.find(v);
auto res = v;
while (it != name_map.end()) {
res = it->second;
it = name_map.find(res);
}
assert(!res.is_invalid());
assigned_names.emplace(k, res);
}
}
void Compiler::queue_inference() {
// queue inference pass
// prepopulate run domain with requested domain
for (auto& p : impl->computed_passes) {
p.domain = p.pass->execute_on;
}
for (auto& head : impl->chains) {
DomainFlags last_domain = DomainFlagBits::eDevice;
bool is_image = head->type == Resource::Type::eImage;
auto propagate_domain = [&last_domain](auto& domain) {
if (domain != last_domain && domain != DomainFlagBits::eDevice && domain != DomainFlagBits::eAny) {
last_domain = domain;
}
if ((last_domain != DomainFlagBits::eDevice && last_domain != DomainFlagBits::eAny) &&
(domain == DomainFlagBits::eDevice || domain == DomainFlagBits::eAny)) {
domain = last_domain;
}
};
// forward inference
ChainLink* chain;
for (chain = head; chain != nullptr; chain = chain->next) {
if (chain->def->pass >= 0) {
propagate_domain(impl->get_pass(*chain->def).domain);
} else {
DomainFlagBits att_dom;
if (is_image) {
att_dom = impl->get_bound_attachment(chain->def->pass).acquire.initial_domain;
} else {
att_dom = impl->get_bound_buffer(chain->def->pass).acquire.initial_domain;
}
if ((DomainFlags)att_dom != last_domain && att_dom != DomainFlagBits::eDevice && att_dom != DomainFlagBits::eAny) {
last_domain = att_dom;
}
}
for (auto& r : chain->reads.to_span(impl->pass_reads)) {
propagate_domain(impl->get_pass(r).domain);
}
if (chain->undef && chain->undef->pass >= 0) {
propagate_domain(impl->get_pass(*chain->undef).domain);
}
}
}
// backward inference
for (auto& head : impl->chains) {
DomainFlags last_domain = DomainFlagBits::eDevice;
// queue inference pass
auto propagate_domain = [&last_domain](auto& domain) {
if (domain != last_domain && domain != DomainFlagBits::eDevice && domain != DomainFlagBits::eAny) {
last_domain = domain;
}
if ((last_domain != DomainFlagBits::eDevice && last_domain != DomainFlagBits::eAny) &&
(domain == DomainFlagBits::eDevice || domain == DomainFlagBits::eAny)) {
domain = last_domain;
}
};
ChainLink* chain;
// wind chain to the end
for (chain = head; chain->next != nullptr; chain = chain->next)
;
for (; chain != nullptr; chain = chain->prev) {
if (chain->undef) {
if (chain->undef->pass < 0) {
last_domain = impl->get_release(chain->undef->pass).dst_use.domain;
} else {
propagate_domain(impl->get_pass(*chain->undef).domain);
}
}
for (auto& r : chain->reads.to_span(impl->pass_reads)) {
propagate_domain(impl->get_pass(r).domain);
}
if (chain->def->pass >= 0) {
propagate_domain(impl->get_pass(*chain->def).domain);
}
}
}
// queue inference failure fixup pass
for (auto& p : impl->ordered_passes) {
if (p->domain == DomainFlagBits::eDevice || p->domain == DomainFlagBits::eAny) { // couldn't infer, set pass as graphics
p->domain = DomainFlagBits::eGraphicsQueue;
}
}
}
// partition passes into different queues
void Compiler::pass_partitioning() {
impl->partitioned_passes.reserve(impl->ordered_passes.size());
impl->computed_pass_idx_to_partitioned_idx.resize(impl->ordered_passes.size());
for (size_t i = 0; i < impl->ordered_passes.size(); i++) {
auto& p = impl->ordered_passes[i];
if (p->domain & DomainFlagBits::eTransferQueue) {
impl->computed_pass_idx_to_partitioned_idx[impl->ordered_idx_to_computed_pass_idx[i]] = impl->partitioned_passes.size();
impl->last_ordered_pass_idx_in_domain_array[2] = impl->ordered_idx_to_computed_pass_idx[i];
impl->partitioned_passes.push_back(p);
}
}
impl->transfer_passes = { impl->partitioned_passes.begin(), impl->partitioned_passes.size() };
for (size_t i = 0; i < impl->ordered_passes.size(); i++) {
auto& p = impl->ordered_passes[i];
if (p->domain & DomainFlagBits::eComputeQueue) {
impl->computed_pass_idx_to_partitioned_idx[impl->ordered_idx_to_computed_pass_idx[i]] = impl->partitioned_passes.size();
impl->last_ordered_pass_idx_in_domain_array[1] = impl->ordered_idx_to_computed_pass_idx[i];
impl->partitioned_passes.push_back(p);
}
}
impl->compute_passes = { impl->partitioned_passes.begin() + impl->transfer_passes.size(), impl->partitioned_passes.size() - impl->transfer_passes.size() };
for (size_t i = 0; i < impl->ordered_passes.size(); i++) {
auto& p = impl->ordered_passes[i];
if (p->domain & DomainFlagBits::eGraphicsQueue) {
impl->computed_pass_idx_to_partitioned_idx[impl->ordered_idx_to_computed_pass_idx[i]] = impl->partitioned_passes.size();
impl->last_ordered_pass_idx_in_domain_array[0] = impl->ordered_idx_to_computed_pass_idx[i];
impl->partitioned_passes.push_back(p);
}
}
impl->graphics_passes = { impl->partitioned_passes.begin() + impl->transfer_passes.size() + impl->compute_passes.size(),
impl->partitioned_passes.size() - impl->transfer_passes.size() - impl->compute_passes.size() };
}
// resource linking pass
// populate swapchain and resource -> bound references
void Compiler::resource_linking() {
for (auto head : impl->chains) {
bool is_image = head->type == Resource::Type::eImage;
bool is_swapchain = false;
if (is_image) {
auto& att = impl->get_bound_attachment(head->def->pass);
att.use_chains.append(impl->attachment_use_chain_references, head);
is_swapchain = att.type == AttachmentInfo::Type::eSwapchain;
} else {
auto& att = impl->get_bound_buffer(head->def->pass);
att.use_chains.append(impl->attachment_use_chain_references, head);
}
if (head->source) { // propagate use onto previous chain def
ChainLink* link = head;
while (link->source) {
for (link = link->source; link->def->pass > 0; link = link->prev)
;
}
for (; link->def->pass >= 0; link = link->prev)
;
if (link->type == Resource::Type::eImage) {
auto& att = impl->get_bound_attachment(link->def->pass);
att.use_chains.append(impl->attachment_use_chain_references, head);
is_swapchain = att.type == AttachmentInfo::Type::eSwapchain;
} else {
auto& att = impl->get_bound_buffer(link->def->pass);
att.use_chains.append(impl->attachment_use_chain_references, head);
}
}
for (ChainLink* link = head; link != nullptr; link = link->next) {
if (link->def->pass >= 0) {
auto& pass = impl->get_pass(*link->def);
auto& def_res = impl->get_resource(*link->def);
if (is_swapchain) {
pass.referenced_swapchains.append(impl->swapchain_references, head->def->pass);
}
def_res.reference = head->def->pass;
}
for (auto& r : link->reads.to_span(impl->pass_reads)) {
auto& pass = impl->get_pass(r);
auto& def_res = impl->get_resource(r);
if (is_swapchain) {
pass.referenced_swapchains.append(impl->swapchain_references, head->def->pass);
}
def_res.reference = head->def->pass;
}
if (link->undef && link->undef->pass >= 0) {
auto& pass = impl->get_pass(*link->undef);
auto& def_res = impl->get_resource(*link->undef);
if (is_swapchain) {
pass.referenced_swapchains.append(impl->swapchain_references, head->def->pass);
}
def_res.reference = head->def->pass;
}
}
}
}
void Compiler::render_pass_assignment() {
// graphics: assemble renderpasses based on framebuffers
// we need to collect passes into framebuffers, which will determine the renderpasses
// renderpasses are uniquely identified by their index from now on
// tell passes in which renderpass/subpass they will execute
impl->rpis.reserve(impl->graphics_passes.size());
for (auto& passinfo : impl->graphics_passes) {
int32_t rpi_index = -1;
RenderPassInfo* rpi = nullptr;
for (auto& res : passinfo->resources.to_span(impl->resources)) {
if (is_framebuffer_attachment(res)) {
if (rpi == nullptr) {
rpi_index = (int32_t)impl->rpis.size();
rpi = &impl->rpis.emplace_back();
}
auto& bound_att = impl->get_bound_attachment(res.reference);
AttachmentRPInfo rp_info{ &bound_att };
rp_info.description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
rp_info.description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
rpi->attachments.append(impl->rp_infos, rp_info);
}
}
passinfo->render_pass_index = (int32_t)rpi_index;
passinfo->subpass = 0;
}
}
Result<void> Compiler::compile(std::span<std::shared_ptr<RenderGraph>> rgs, const RenderGraphCompileOptions& compile_options) {
auto arena = impl->arena_.release();
delete impl;
arena->reset();
impl = new RGCImpl(arena);
VUK_DO_OR_RETURN(inline_rgs(rgs));
impl->compute_assigned_names();
impl->merge_diverge_passes(impl->computed_passes);
// run global pass ordering - once we split per-queue we don't see enough
// inputs to order within a queue
VUK_DO_OR_RETURN(build_links(impl->computed_passes, impl->res_to_links, impl->resources, impl->pass_reads));
VUK_DO_OR_RETURN(impl->terminate_chains());
VUK_DO_OR_RETURN(collect_chains(impl->res_to_links, impl->chains));
VUK_DO_OR_RETURN(impl->diagnose_unheaded_chains());
VUK_DO_OR_RETURN(impl->schedule_intra_queue(impl->computed_passes, compile_options));
VUK_DO_OR_RETURN(impl->fix_subchains());
// auto dumped_graph = dump_graph();
queue_inference();
pass_partitioning();
resource_linking();
render_pass_assignment();
return { expected_value };
}
void RenderGraph::resolve_resource_into(Name resolved_name_src, Name resolved_name_dst, Name ms_name) {
add_pass({ .resources = { Resource{ ms_name, Resource::Type::eImage, eTransferRead, {} },
Resource{ resolved_name_src, Resource::Type::eImage, eTransferWrite, resolved_name_dst } },
.execute = [ms_name, resolved_name_src](CommandBuffer& cbuf) { cbuf.resolve_image(ms_name, resolved_name_src); },
.type = PassType::eResolve });
inference_rule(resolved_name_src, same_shape_as(ms_name));
inference_rule(ms_name, same_shape_as(resolved_name_src));
}
void RenderGraph::clear_image(Name image_name, Name image_name_out, Clear clear_value) {
auto arg_ptr = impl->arena_->allocate(sizeof(Clear));
std::memcpy(arg_ptr, &clear_value, sizeof(Clear));
Resource res{ image_name, Resource::Type::eImage, eClear, image_name_out };
add_pass({ .name = image_name.append("_CLEAR"),
.resources = { std::move(res) },
.execute = [image_name, clear_value](CommandBuffer& cbuf) { cbuf.clear_image(image_name, clear_value); },
.arguments = reinterpret_cast<std::byte*>(arg_ptr),
.type = PassType::eClear });
}
void RenderGraph::attach_swapchain(Name name, SwapchainRef swp) {
AttachmentInfo attachment_info;
attachment_info.name = { Name{}, name };
attachment_info.attachment.extent = Dimension3D::absolute(swp->extent);
// directly presented
attachment_info.attachment.format = swp->format;
attachment_info.attachment.sample_count = Samples::e1;
attachment_info.attachment.base_layer = 0;
attachment_info.attachment.base_level = 0;
attachment_info.attachment.layer_count = 1;
attachment_info.attachment.level_count = 1;
attachment_info.type = AttachmentInfo::Type::eSwapchain;
attachment_info.swapchain = swp;
QueueResourceUse& initial = attachment_info.acquire.src_use;
// for WSI, we want to wait for colourattachmentoutput
// we don't care about any writes, we will clear
initial.access = AccessFlags{};
initial.stages = PipelineStageFlagBits::eColorAttachmentOutput;
// discard
initial.layout = ImageLayout::eUndefined;
impl->bound_attachments.emplace(attachment_info.name, attachment_info);
}
void RenderGraph::attach_buffer(Name name, Buffer buf, Access initial) {
BufferInfo buf_info{ .name = { Name{}, name }, .buffer = buf, .acquire = { .src_use = to_use(initial, DomainFlagBits::eAny) } };
impl->bound_buffers.emplace(buf_info.name, buf_info);
}
void RenderGraph::attach_buffer_from_allocator(Name name, Buffer buf, Allocator allocator, Access initial) {
BufferInfo buf_info{ .name = { Name{}, name }, .buffer = buf, .acquire = { .src_use = to_use(initial, DomainFlagBits::eAny) }, .allocator = allocator };
impl->bound_buffers.emplace(buf_info.name, buf_info);
}
void RenderGraph::attach_image(Name name, ImageAttachment att, Access initial_acc) {
AttachmentInfo attachment_info;
attachment_info.name = { Name{}, name };
attachment_info.attachment = att;
if (att.has_concrete_image() && att.has_concrete_image_view()) {
attachment_info.type = AttachmentInfo::Type::eExternal;
} else {
attachment_info.type = AttachmentInfo::Type::eInternal;
}
attachment_info.attachment.format = att.format;
QueueResourceUse& initial = attachment_info.acquire.src_use;
initial = to_use(initial_acc, DomainFlagBits::eAny);
impl->bound_attachments.emplace(attachment_info.name, attachment_info);
}
void RenderGraph::attach_image_from_allocator(Name name, ImageAttachment att, Allocator allocator, Access initial_acc) {
AttachmentInfo attachment_info;
attachment_info.allocator = allocator;
attachment_info.name = { Name{}, name };
attachment_info.attachment = att;
if (att.has_concrete_image() && att.has_concrete_image_view()) {
attachment_info.type = AttachmentInfo::Type::eExternal;
} else {
attachment_info.type = AttachmentInfo::Type::eInternal;
}
attachment_info.attachment.format = att.format;
QueueResourceUse& initial = attachment_info.acquire.src_use;
initial = to_use(initial_acc, DomainFlagBits::eAny);
impl->bound_attachments.emplace(attachment_info.name, attachment_info);
}
void RenderGraph::attach_and_clear_image(Name name, ImageAttachment att, Clear clear_value, Access initial_acc) {
Name tmp_name = name.append(get_temporary_name().to_sv());
attach_image(tmp_name, att, initial_acc);
clear_image(tmp_name, name, clear_value);
}
void RenderGraph::attach_in(Name name, Future fimg) {
if (fimg.get_status() == FutureBase::Status::eSubmitted || fimg.get_status() == FutureBase::Status::eHostAvailable) {
if (fimg.is_image()) {
auto att = fimg.get_result<ImageAttachment>();
AttachmentInfo attachment_info;
attachment_info.name = { Name{}, name };
attachment_info.attachment = att;
attachment_info.type = AttachmentInfo::Type::eExternal;
attachment_info.acquire = { fimg.control->last_use, fimg.control->initial_domain, fimg.control->initial_visibility };
impl->bound_attachments.emplace(attachment_info.name, attachment_info);
} else {
BufferInfo buf_info{ .name = { Name{}, name }, .buffer = fimg.get_result<Buffer>() };
buf_info.acquire = { fimg.control->last_use, fimg.control->initial_domain, fimg.control->initial_visibility };
impl->bound_buffers.emplace(buf_info.name, buf_info);
}
impl->imported_names.emplace_back(QualifiedName{ {}, name });
} else if (fimg.get_status() == FutureBase::Status::eInitial) {
// an unsubmitted RG is being attached, we remove the release from that RG, and we allow the name to be found in us
assert(fimg.rg->impl);
std::erase_if(fimg.rg->impl->releases, [name = fimg.get_bound_name()](auto& item) { return item.first == name; });
auto sg_info_it = std::find_if(impl->subgraphs.begin(), impl->subgraphs.end(), [&](auto& it) { return it.first == fimg.rg; });
if (sg_info_it == impl->subgraphs.end()) {
impl->subgraphs.emplace_back(std::pair{ fimg.rg, RGImpl::SGInfo{} });
sg_info_it = impl->subgraphs.end() - 1;
}
auto& sg_info = sg_info_it->second;
sg_info.count++;
auto old_exported_names = sg_info.exported_names;
auto current_exported_name_size = sg_info.exported_names.size_bytes();
sg_info.exported_names = std::span{ reinterpret_cast<decltype(sg_info.exported_names)::value_type*>(
impl->arena_->allocate(current_exported_name_size + sizeof(sg_info.exported_names[0]))),
sg_info.exported_names.size() + 1 };
std::copy(old_exported_names.begin(), old_exported_names.end(), sg_info.exported_names.begin());
sg_info.exported_names.back() = std::pair{ name, fimg.get_bound_name() };
impl->imported_names.emplace_back(QualifiedName{ {}, name });
fimg.rg.reset();
} else {
assert(0);
}
}
void RenderGraph::attach_in(std::span<Future> futures) {
for (auto& f : futures) {
auto name = f.get_bound_name();
attach_in(name.name, std::move(f));
}
}
void RenderGraph::inference_rule(Name target, std::function<void(const struct InferenceContext&, ImageAttachment&)> rule) {
impl->ia_inference_rules.emplace_back(IAInference{ QualifiedName{ Name{}, target }, std::move(rule) });
}
void RenderGraph::inference_rule(Name target, std::function<void(const struct InferenceContext&, Buffer&)> rule) {
impl->buf_inference_rules.emplace_back(BufferInference{ QualifiedName{ Name{}, target }, std::move(rule) });
}
robin_hood::unordered_flat_set<QualifiedName> RGImpl::get_available_resources() {
std::vector<PassInfo> pass_infos;
pass_infos.reserve(passes.size());
for (auto& pass : passes) {
pass_infos.emplace_back(pass).resources = pass.resources;
}
std::vector<Resource> resolved_resources;
for (auto res : resources) {
res.name.name = res.name.name.is_invalid() ? Name{} : resolve_alias(res.name.name);
res.out_name.name = res.out_name.name.is_invalid() ? Name{} : resolve_alias(res.out_name.name);
resolved_resources.emplace_back(res);
}
ResourceLinkMap res_to_links;
std::vector<ChainAccess> pass_reads;
std::vector<ChainLink*> chains;
build_links(pass_infos, res_to_links, resolved_resources, pass_reads);
for (auto& bound : bound_attachments) {
res_to_links[bound.first].def = { .pass = static_cast<int32_t>(-1 * (&bound - &*bound_attachments.begin() + 1)) };
}
for (auto& bound : bound_buffers) {
res_to_links[bound.first].def = { .pass = static_cast<int32_t>(-1 * (&bound - &*bound_buffers.begin() + 1)) };
}
for (auto& bound : releases) {
res_to_links[bound.first].undef = { .pass = static_cast<int32_t>(-1 * (&bound - &*releases.begin() + 1)) };
}
collect_chains(res_to_links, chains);
robin_hood::unordered_flat_set<QualifiedName> outputs;
outputs.insert(imported_names.begin(), imported_names.end());
for (auto& head : chains) {
ChainLink* link;
for (link = head; link->next != nullptr; link = link->next)
;
if (link->reads.size()) {
auto r = link->reads.to_span(pass_reads)[0];
outputs.emplace(get_resource(pass_infos, r).name);
}
if (link->undef) {
if (link->undef->pass >= 0) {
outputs.emplace(get_resource(pass_infos, *link->undef).out_name);
} else {
if (link->def->pass >= 0) {
outputs.emplace(get_resource(pass_infos, *link->def).out_name);
} else {
// tailed by release and def unusable
}
}
}
if (link->def) {
if (link->def->pass >= 0) {
outputs.emplace(get_resource(pass_infos, *link->def).out_name);
} else {
QualifiedName name = link->type == Resource::Type::eImage
? (&*bound_attachments.begin() + (-1 * (link->def->pass) - 1))->first
: (&*bound_buffers.begin() + (-1 * (link->def->pass) - 1))->first; // the only def we have is the binding
outputs.emplace(name);
}
}
}
return outputs;
}
std::vector<Future> RenderGraph::split() {
robin_hood::unordered_flat_set<QualifiedName> outputs = impl->get_available_resources();
std::vector<Future> futures;
for (auto& elem : outputs) {
futures.emplace_back(this->shared_from_this(), elem);
}
return futures;
}
void RenderGraph::attach_out(QualifiedName name, Future& fimg, DomainFlags dst_domain) {
impl->releases.emplace_back(name, Release{ Access::eNone, to_use(Access::eNone, dst_domain), fimg.control.get() });
}
void RenderGraph::detach_out(QualifiedName name, Future& fimg) {
for (auto it = impl->releases.begin(); it != impl->releases.end(); ++it) {
if (it->first == name && it->second.signal == fimg.control.get()) {
impl->releases.erase(it);
return;
}
}
}
void RenderGraph::release(Name name, Access final) {
impl->releases.emplace_back(QualifiedName{ Name{}, name }, Release{ final, to_use(final, DomainFlagBits::eAny) });
}
void RenderGraph::release_for_present(Name name) {
/*
Normally, we would need an external dependency at the end as well since
we are changing layout in finalLayout, but since we are signalling a
semaphore, we can rely on Vulkan's default behavior, which injects an
external dependency here with dstStageMask =
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, dstAccessMask = 0.
*/
QueueResourceUse final{
.stages = PipelineStageFlagBits::eAllCommands, .access = AccessFlagBits{}, .layout = ImageLayout::ePresentSrcKHR, .domain = DomainFlagBits::eAny
};
impl->releases.emplace_back(QualifiedName{ Name{}, name }, Release{ .original = ePresent, .dst_use = final });
}
Name RenderGraph::get_temporary_name() {
return impl->temporary_name.append(std::to_string(impl->temporary_name_counter++));
}
IARule same_extent_as(Name n) {
return [=](const InferenceContext& ctx, ImageAttachment& ia) {
ia.extent = ctx.get_image_attachment(n).extent;
};
}
IARule same_2D_extent_as(Name n) {
return [=](const InferenceContext& ctx, ImageAttachment& ia) {
auto& o = ctx.get_image_attachment(n);
ia.extent.sizing = o.extent.sizing;
ia.extent.extent.width = o.extent.extent.width;
ia.extent.extent.height = o.extent.extent.height;
};
}
IARule same_format_as(Name n) {
return [=](const InferenceContext& ctx, ImageAttachment& ia) {
ia.format = ctx.get_image_attachment(n).format;
};
}
IARule same_shape_as(Name n) {
return [=](const InferenceContext& ctx, ImageAttachment& ia) {
auto& src = ctx.get_image_attachment(n);
if (src.base_layer != VK_REMAINING_ARRAY_LAYERS)
ia.base_layer = src.base_layer;
if (src.layer_count != VK_REMAINING_ARRAY_LAYERS)
ia.layer_count = src.layer_count;
if (src.base_level != VK_REMAINING_MIP_LEVELS)
ia.base_level = src.base_level;
if (src.level_count != VK_REMAINING_MIP_LEVELS)
ia.level_count = src.level_count;
if (src.extent.extent.width != 0 && src.extent.extent.height != 0)
ia.extent = src.extent;
if (src.view_type != ImageViewType::eInfer)
ia.view_type = src.view_type;
};
}
IARule similar_to(Name n) {
return [=](const InferenceContext& ctx, ImageAttachment& ia) {
auto& src = ctx.get_image_attachment(n);
if (src.base_layer != VK_REMAINING_ARRAY_LAYERS)
ia.base_layer = src.base_layer;
if (src.layer_count != VK_REMAINING_ARRAY_LAYERS)
ia.layer_count = src.layer_count;
if (src.base_level != VK_REMAINING_MIP_LEVELS)
ia.base_level = src.base_level;
if (src.level_count != VK_REMAINING_MIP_LEVELS)
ia.level_count = src.level_count;
if (src.extent.extent.width != 0 && src.extent.extent.height != 0)
ia.extent = src.extent;
if (src.format != Format::eUndefined)
ia.format = src.format;
if (src.sample_count != Samples::eInfer)
ia.sample_count = src.sample_count;
};
}
BufferRule same_size_as(Name inference_source) {
return [=](const InferenceContext& ctx, Buffer& buf) {
auto& src = ctx.get_buffer(inference_source);
buf.size = src.size;
};
}
bool crosses_queue(QueueResourceUse last_use, QueueResourceUse current_use) {
return (last_use.domain != DomainFlagBits::eNone && last_use.domain != DomainFlagBits::eAny && current_use.domain != DomainFlagBits::eNone &&
current_use.domain != DomainFlagBits::eAny && (last_use.domain & DomainFlagBits::eQueueMask) != (current_use.domain & DomainFlagBits::eQueueMask));
}
void RGCImpl::emit_image_barrier(RelSpan<VkImageMemoryBarrier2KHR>& barriers,
int32_t bound_attachment,
QueueResourceUse last_use,
QueueResourceUse current_use,
Subrange::Image& subrange,
ImageAspectFlags aspect,
bool is_release) {
scope_to_domain((VkPipelineStageFlagBits2KHR&)last_use.stages, is_release ? last_use.domain : current_use.domain & DomainFlagBits::eQueueMask);
scope_to_domain((VkPipelineStageFlagBits2KHR&)current_use.stages, is_release ? last_use.domain : current_use.domain & DomainFlagBits::eQueueMask);
// compute image barrier for this access -> access
VkImageMemoryBarrier2KHR barrier{ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2_KHR };
barrier.srcAccessMask = is_read_access(last_use) ? 0 : (VkAccessFlags)last_use.access;
barrier.dstAccessMask = (VkAccessFlags)current_use.access;
barrier.oldLayout = (VkImageLayout)last_use.layout;
barrier.newLayout = (VkImageLayout)current_use.layout;
barrier.subresourceRange.aspectMask = (VkImageAspectFlags)aspect;
barrier.subresourceRange.baseArrayLayer = subrange.base_layer;
barrier.subresourceRange.baseMipLevel = subrange.base_level;
barrier.subresourceRange.layerCount = subrange.layer_count;
barrier.subresourceRange.levelCount = subrange.level_count;
assert(last_use.domain.m_mask != 0);
assert(current_use.domain.m_mask != 0);
if (last_use.domain == DomainFlagBits::eAny) {
last_use.domain = current_use.domain;
}
if (current_use.domain == DomainFlagBits::eAny) {
current_use.domain = last_use.domain;
}
barrier.srcQueueFamilyIndex = static_cast<uint32_t>((last_use.domain & DomainFlagBits::eQueueMask).m_mask);
barrier.dstQueueFamilyIndex = static_cast<uint32_t>((current_use.domain & DomainFlagBits::eQueueMask).m_mask);
if (last_use.stages == PipelineStageFlags{}) {
barrier.srcAccessMask = {};
}
if (current_use.stages == PipelineStageFlags{}) {
barrier.dstAccessMask = {};
}
std::memcpy(&barrier.pNext, &bound_attachment, sizeof(int32_t));
barrier.srcStageMask = (VkPipelineStageFlags2)last_use.stages.m_mask;
barrier.dstStageMask = (VkPipelineStageFlags2)current_use.stages.m_mask;
barriers.append(image_barriers, barrier);
}
void RGCImpl::emit_memory_barrier(RelSpan<VkMemoryBarrier2KHR>& barriers, QueueResourceUse last_use, QueueResourceUse current_use) {
// for now we only emit pre- memory barriers, so the executing domain is always 'current_use.domain'
scope_to_domain((VkPipelineStageFlagBits2KHR&)last_use.stages, current_use.domain & DomainFlagBits::eQueueMask);
scope_to_domain((VkPipelineStageFlagBits2KHR&)current_use.stages, current_use.domain & DomainFlagBits::eQueueMask);
VkMemoryBarrier2KHR barrier{ .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2_KHR };
barrier.srcAccessMask = is_read_access(last_use) ? 0 : (VkAccessFlags)last_use.access;
barrier.dstAccessMask = (VkAccessFlags)current_use.access;
barrier.srcStageMask = (VkPipelineStageFlagBits2)last_use.stages.m_mask;
barrier.dstStageMask = (VkPipelineStageFlagBits2)current_use.stages.m_mask;
if (barrier.srcStageMask == 0) {
barrier.srcStageMask = (VkPipelineStageFlagBits2)PipelineStageFlagBits::eNone;
barrier.srcAccessMask = {};
}
barriers.append(mem_barriers, barrier);
}
Result<void> RGCImpl::generate_barriers_and_waits() {
// we need to handle chains in order of dependency
std::vector<ChainLink*> work_queue;
for (auto head : chains) {
bool is_image = head->type == Resource::Type::eImage;
if (is_image) {
if (!head->source) {
work_queue.push_back(head);
}
} else {
work_queue.push_back(head);
}
}
// handle head (queue wait, initial use) -> emit barriers -> handle tail (signal, final use)
unsigned seen_chains = 0;
while (work_queue.size() > 0) {
ChainLink* head = work_queue.back();
work_queue.pop_back();
seen_chains++;
// handle head
ImageAspectFlags aspect;
Subrange::Image image_subrange;
bool is_image = head->type == Resource::Type::eImage;
if (is_image) {
auto& att = get_bound_attachment(head->def->pass);
aspect = format_to_aspect(att.attachment.format);
image_subrange = att.image_subrange;
}
bool is_subchain = head->source != nullptr;
// initial waits are handled by the common chain code
// last use on the chain
QueueResourceUse last_use;
ChainLink* link;
for (link = head; link != nullptr; link = link->next) {
// populate last use from def or attach
if (link->def->pass >= 0) {
auto& def_pass = get_pass(*link->def);
auto& def_res = get_resource(*link->def);
last_use = to_use(def_res.ia, def_pass.domain);
} else {
last_use = is_image ? get_bound_attachment(head->def->pass).acquire.src_use : get_bound_buffer(head->def->pass).acquire.src_use;
}
// handle chain
// we need to emit: def -> reads, RAW or nothing
// reads -> undef, WAR
// if there were no reads, then def -> undef, which is either WAR or WAW
// we need to sometimes emit a barrier onto the last thing that happened, find that pass here
// it is either last read pass, or if there were no reads, the def pass, or if the def pass doesn't exist, then we search parent chains
int32_t last_executing_pass_idx = link->def->pass >= 0 ? (int32_t)computed_pass_idx_to_ordered_idx[link->def->pass] : -1;
if (link->reads.size() > 0) { // we need to emit: def -> reads, RAW or nothing (before first read)
// to avoid R->R deps, we emit a single dep for all the reads
// for this we compute a merged layout (TRANSFER_SRC_OPTIMAL / READ_ONLY_OPTIMAL / GENERAL)
QueueResourceUse use;
auto reads = link->reads.to_span(pass_reads);
size_t read_idx = 0;
size_t start_of_reads = 0;
// this is where we stick the source dep, it is either def or undef in the parent chain
int32_t last_use_source = link->def->pass >= 0 ? link->def->pass : -1;
while (read_idx < reads.size()) {
int32_t first_pass_idx = INT32_MAX;
bool need_read_only = false;
bool need_transfer = false;
bool need_general = false;
use.domain = DomainFlagBits::eNone;
use.layout = ImageLayout::eReadOnlyOptimalKHR;
for (; read_idx < reads.size(); read_idx++) {
auto& r = reads[read_idx];
auto& pass = get_pass(r);
auto& res = get_resource(r);
auto use2 = to_use(res.ia, pass.domain);
if (use.domain == DomainFlagBits::eNone) {
use.domain = use2.domain;
} else if (use.domain != use2.domain) {
// there are multiple domains in this read group
// this is okay - but in this case we can't synchronize against all of them together
// so we synchronize against them individually by setting last use and ending the read gather
break;
}
// this read can be merged, so merge it
int32_t order_idx = (int32_t)computed_pass_idx_to_ordered_idx[r.pass];
if (order_idx < first_pass_idx) {
first_pass_idx = (int32_t)order_idx;
}
if (order_idx > last_executing_pass_idx) {
last_executing_pass_idx = (int32_t)order_idx;
}
if (is_transfer_access(res.ia)) {
need_transfer = true;
}
if (is_storage_access(res.ia)) {
need_general = true;
}
if (is_readonly_access(res.ia)) {
need_read_only = true;
}
use.access |= use2.access;
use.stages |= use2.stages;
}
// compute barrier and waits for the merged reads
if (need_transfer && !need_read_only) {
use.layout = ImageLayout::eTransferSrcOptimal;
}
if (need_general || (need_transfer && need_read_only)) {
use.layout = ImageLayout::eGeneral;
for (auto& r : reads.subspan(start_of_reads, read_idx - start_of_reads)) {
auto& res = get_resource(r);
res.promoted_to_general = true;
}
}
if (last_use_source < 0 && is_subchain) {
assert(link->source->undef && link->source->undef->pass >= 0);
last_use_source = link->source->undef->pass;
}
// TODO: do not emit this if dep is a read and the layouts match
auto& dst = get_pass(first_pass_idx);
if (is_image) {
if (crosses_queue(last_use, use)) {
emit_image_barrier(get_pass((int32_t)computed_pass_idx_to_ordered_idx[last_use_source]).post_image_barriers,
head->def->pass,
last_use,
use,
image_subrange,
aspect,
true);
}
emit_image_barrier(dst.pre_image_barriers, head->def->pass, last_use, use, image_subrange, aspect);
} else {
emit_memory_barrier(dst.pre_memory_barriers, last_use, use);
}
if (crosses_queue(last_use, use)) {
// in this case def was on a different queue the subsequent reads
// we stick the wait on the first read pass in order
get_pass(first_pass_idx)
.relative_waits.append(
waits, { (DomainFlagBits)(last_use.domain & DomainFlagBits::eQueueMask).m_mask, computed_pass_idx_to_ordered_idx[last_use_source] });
get_pass((int32_t)computed_pass_idx_to_ordered_idx[last_use_source]).is_waited_on++;
}
last_use = use;
last_use_source = reads[read_idx - 1].pass;
start_of_reads = read_idx;
}
}
// if there are no intervening reads, emit def -> undef, otherwise emit reads -> undef
// def -> undef, which is either WAR or WAW (before undef)
// reads -> undef, WAR (before undef)
if (link->undef && link->undef->pass >= 0) {
auto& pass = get_pass(*link->undef);
auto& res = get_resource(*link->undef);
QueueResourceUse use = to_use(res.ia, pass.domain);
if (use.layout == ImageLayout::eGeneral) {
res.promoted_to_general = true;
}
// handle renderpass details
// all renderpass write-attachments are entered via an undef (because of it being a write)
if (pass.render_pass_index >= 0) {
auto& rpi = rpis[pass.render_pass_index];
auto& bound_att = get_bound_attachment(head->def->pass);
for (auto& att : rpi.attachments.to_span(rp_infos)) {
if (att.attachment_info == &bound_att) {
// if the last use was discard, then downgrade load op
if (last_use.layout == ImageLayout::eUndefined) {
att.description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
} else if (use.access & AccessFlagBits::eColorAttachmentWrite) { // add CA read, because of LOAD_OP_LOAD
use.access |= AccessFlagBits::eColorAttachmentRead;
} else if (use.access & AccessFlagBits::eDepthStencilAttachmentWrite) { // add DSA read, because of LOAD_OP_LOAD
use.access |= AccessFlagBits::eDepthStencilAttachmentRead;
}
}
}
}
// if the def pass doesn't exist, and there were no reads
if (last_executing_pass_idx == -1) {
if (is_subchain) { // if subchain, search parent chain for pass
assert(link->source->undef && link->source->undef->pass >= 0);
last_executing_pass_idx = (int32_t)computed_pass_idx_to_ordered_idx[link->source->undef->pass];
}
}
if (res.ia != eConsume) {
if (is_image) {
if (crosses_queue(last_use, use)) { // release barrier
if (last_executing_pass_idx !=
-1) { // if last_executing_pass_idx is -1, then there is release in this rg, so we don't emit the release (single-sided acq)
emit_image_barrier(get_pass(last_executing_pass_idx).post_image_barriers, head->def->pass, last_use, use, image_subrange, aspect, true);
}
}
emit_image_barrier(get_pass(*link->undef).pre_image_barriers, head->def->pass, last_use, use, image_subrange, aspect);
} else {
emit_memory_barrier(get_pass(*link->undef).pre_memory_barriers, last_use, use);
}
if (crosses_queue(last_use, use)) {
// we wait on either def or the last read if there was one
if (last_executing_pass_idx != -1) {
get_pass(*link->undef)
.relative_waits.append(waits, { (DomainFlagBits)(last_use.domain & DomainFlagBits::eQueueMask).m_mask, last_executing_pass_idx });
get_pass(last_executing_pass_idx).is_waited_on++;
} else {
auto& acquire = is_image ? get_bound_attachment(link->def->pass).acquire : get_bound_buffer(link->def->pass).acquire;
get_pass(*link->undef).absolute_waits.append(absolute_waits, { acquire.initial_domain, acquire.initial_visibility });
}
}
last_use = use;
}
}
// process tails outside
if (link->next == nullptr) {
break;
}
}
// tail can be either a release or nothing
if (link->undef && link->undef->pass < 0) { // a release
// what if last pass is a read:
// we loop through the read passes and select the one executing last based on the ordering
// that pass can perform the signal and the barrier post-pass
auto& release = get_release(link->undef->pass);
int32_t last_pass_idx = 0;
if (link->reads.size() > 0) {
for (auto& r : link->reads.to_span(pass_reads)) {
auto order_idx = computed_pass_idx_to_ordered_idx[r.pass];
if (order_idx > last_pass_idx) {
last_pass_idx = (int32_t)order_idx;
}
}
} else { // no intervening read, we put it directly on def
if (link->def->pass >= 0) {
last_pass_idx = (int32_t)computed_pass_idx_to_ordered_idx[link->def->pass];
} else { // no passes using this resource, just acquired and released -> put the dep on last pass
// in case neither acquire nor release specify a pass we just put it on the last pass
last_pass_idx = (int32_t)ordered_passes.size() - 1;
// if release specifies a domain, use that
if (release.dst_use.domain != DomainFlagBits::eAny && release.dst_use.domain != DomainFlagBits::eDevice) {
last_pass_idx = last_ordered_pass_idx_in_domain((DomainFlagBits)(release.dst_use.domain & DomainFlagBits::eQueueMask).m_mask);
}
}
}
// if the release has a bound future to signal, record that here
auto& pass = get_pass(last_pass_idx);
if (auto* fut = release.signal) {
fut->last_use = last_use;
if (is_image) {
get_bound_attachment(head->def->pass).attached_future = fut;
} else {
get_bound_buffer(head->def->pass).attached_future = fut;
}
pass.future_signals.append(future_signals, fut);
}
QueueResourceUse use = release.dst_use;
if (use.layout != ImageLayout::eUndefined) {
if (is_image) {
// single sided release barrier
emit_image_barrier(get_pass(last_pass_idx).post_image_barriers, head->def->pass, last_use, use, image_subrange, aspect, true);
} else {
emit_memory_barrier(get_pass(last_pass_idx).post_memory_barriers, last_use, use);
}
}
} else if (!link->undef) {
// no release on this end, so if def belongs to an RP and there were no reads, we can downgrade the store
if (link->def && link->def->pass >= 0 && link->reads.size() == 0) {
auto& pass = get_pass(link->def->pass);
if (pass.render_pass_index >= 0) {
auto& rpi = rpis[pass.render_pass_index];
auto& bound_att = get_bound_attachment(head->def->pass);
for (auto& att : rpi.attachments.to_span(rp_infos)) {
if (att.attachment_info == &bound_att) {
att.description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
}
}
}
// TODO: we can also downgrade if the reads are in the same RP, but this is less likely
}
// we have processed this chain, lets see if we can unblock more chains
for (auto new_head : link->child_chains.to_span(child_chains)) {
auto& new_att = get_bound_attachment(new_head->def->pass);
new_att.acquire.src_use = last_use;
work_queue.push_back(new_head);
}
}
assert(seen_chains == chains.size());
return { expected_value };
}
Result<void> RGCImpl::merge_rps() {
// this is only done on gfx passes
if (graphics_passes.size() == 0) {
return { expected_value };
}
// we run this after barrier gen
// loop through gfx passes in order
for (size_t i = 0; i < graphics_passes.size() - 1; i++) {
auto& pass0 = *graphics_passes[i];
auto& pass1 = *graphics_passes[i + 1];
// two gfx passes can be merged if they are
// - adjacent and both have rps
if (pass0.render_pass_index == -1 || pass1.render_pass_index == -1) {
continue;
}
// - have the same ordered set of attachments
bool can_merge = true;
auto p0res = pass0.resources.to_span(resources);
auto p1res = pass1.resources.to_span(resources);
size_t k = 0;
for (size_t j = 0; j < p0res.size(); j++) {
auto& res0 = p0res[j];
auto& link0 = res_to_links.at(res0.name);
if (!is_framebuffer_attachment(res0)) {
continue;
}
// advance attachments in p1 until we get a match or run out
for (; k < p1res.size(); k++) {
auto& res1 = p1res[k];
auto& link1 = res_to_links.at(res1.name);
// TODO: we only handle some cases here (too conservative)
bool same_access = res0.ia == res1.ia;
if (same_access && link0.next == &link1) {
break;
}
}
if (k == p1res.size()) {
can_merge = false;
}
}
if (!can_merge) {
continue;
}
// - contain only color and ds deps between them
if (pass0.post_memory_barriers.size() > 0 || pass1.pre_memory_barriers.size() > 0) {
continue;
}
for (auto& bar : pass0.post_image_barriers.to_span(image_barriers)) {
if ((bar.srcAccessMask & ~(VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT |
VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)) != 0) {
can_merge = false;
}
if ((bar.dstAccessMask & ~(VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT |
VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)) != 0) {
can_merge = false;
}
}
for (auto& bar : pass1.pre_image_barriers.to_span(image_barriers)) {
if ((bar.srcAccessMask & ~(VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT |
VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)) != 0) {
can_merge = false;
}
if ((bar.dstAccessMask & ~(VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT |
VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)) != 0) {
can_merge = false;
}
}
if (can_merge) {
rpis[pass1.render_pass_index].attachments = {};
pass1.render_pass_index = pass0.render_pass_index;
pass0.post_image_barriers = {};
pass1.pre_image_barriers = {};
}
}
return { expected_value };
}
Result<void> RGCImpl::assign_passes_to_batches() {
// cull waits
{
DomainFlags current_queue = DomainFlagBits::eNone;
std::array<uint64_t, 3> last_passes_waited = {};
// loop through all passes
for (size_t i = 0; i < partitioned_passes.size(); i++) {
auto& current_pass = partitioned_passes[i];
auto queue = (DomainFlagBits)(current_pass->domain & DomainFlagBits::eQueueMask).m_mask;
if ((DomainFlags)queue != current_queue) { // if we go into a new queue, reset wait indices
last_passes_waited = {};
current_queue = queue;
}
RelSpan<std::pair<DomainFlagBits, uint64_t>> new_waits = {};
auto sp = current_pass->relative_waits.to_span(waits);
for (auto i = 0; i < sp.size(); i++) {
auto [queue, pass_idx] = sp[i];
auto queue_idx = std::countr_zero((uint32_t)queue) - 1;
auto& last_amt = last_passes_waited[queue_idx];
if (pass_idx > last_amt) {
last_amt = pass_idx;
new_waits.append(waits, std::pair{ queue, pass_idx });
sp = current_pass->relative_waits.to_span(waits);
} else {
ordered_passes[pass_idx]->is_waited_on--;
}
}
current_pass->relative_waits = new_waits;
}
}
// assign passes to batches (within a single queue)
uint32_t batch_index = -1;
DomainFlags current_queue = DomainFlagBits::eNone;
bool needs_split = false;
bool needs_split_next = false;
for (size_t i = 0; i < partitioned_passes.size(); i++) {
auto& current_pass = partitioned_passes[i];
auto queue = (DomainFlagBits)(current_pass->domain & DomainFlagBits::eQueueMask).m_mask;
if ((DomainFlags)queue != current_queue) { // if we go into a new queue, reset batch index
current_queue = queue;
batch_index = -1;
needs_split = false;
}
if (current_pass->relative_waits.size() > 0) {
needs_split = true;
}
if (current_pass->is_waited_on > 0) {
needs_split_next = true;
}
current_pass->batch_index = (needs_split || (batch_index == -1)) ? ++batch_index : batch_index;
needs_split = needs_split_next;
needs_split_next = false;
}
return { expected_value };
}
Result<void> RGCImpl::build_waits() {
// build waits, now that we have fixed the batches
for (size_t i = 0; i < partitioned_passes.size(); i++) {
auto& current_pass = partitioned_passes[i];
auto rel_waits = current_pass->relative_waits.to_span(waits);
for (auto& wait : rel_waits) {
wait.second = ordered_passes[wait.second]->batch_index + 1; // 0 = means previous
}
}
return { expected_value };
}
Result<void> RGCImpl::build_renderpasses() {
// compile attachments
// we have to assign the proper attachments to proper slots
// the order is given by the resource binding order
for (auto& rp : rpis) {
rp.rpci.color_ref_offsets.resize(1);
rp.rpci.ds_refs.resize(1);
}
size_t previous_rp = -1;
uint32_t previous_sp = -1;
for (auto& pass_p : partitioned_passes) {
auto& pass = *pass_p;
if (pass.render_pass_index < 0) {
continue;
}
auto& rpi = rpis[pass.render_pass_index];
auto subpass_index = pass.subpass;
auto& color_attrefs = rpi.rpci.color_refs;
auto& ds_attrefs = rpi.rpci.ds_refs;
// do not process merged passes
if (previous_rp != -1 && previous_rp == pass.render_pass_index && previous_sp == pass.subpass) {
continue;
} else {
previous_rp = pass.render_pass_index;
previous_sp = pass.subpass;
}
for (auto& res : pass.resources.to_span(resources)) {
if (!is_framebuffer_attachment(res))
continue;
VkAttachmentReference attref{};
auto& attachment_info = get_bound_attachment(res.reference);
auto aspect = format_to_aspect(attachment_info.attachment.format);
ImageLayout layout;
if (res.promoted_to_general) {
layout = ImageLayout::eGeneral;
} else if (!is_write_access(res.ia)) {
layout = ImageLayout::eReadOnlyOptimalKHR;
} else {
layout = ImageLayout::eAttachmentOptimalKHR;
}
for (auto& att : rpi.attachments.to_span(rp_infos)) {
if (att.attachment_info == &attachment_info) {
att.description.initialLayout = (VkImageLayout)layout;
att.description.finalLayout = (VkImageLayout)layout;
}
}
attref.layout = (VkImageLayout)layout;
auto attachments = rpi.attachments.to_span(rp_infos);
attref.attachment = (uint32_t)std::distance(
attachments.begin(), std::find_if(attachments.begin(), attachments.end(), [&](auto& att) { return att.attachment_info == &attachment_info; }));
if ((aspect & ImageAspectFlagBits::eColor) == ImageAspectFlags{}) { // not color -> depth or depth/stencil
ds_attrefs[subpass_index] = attref;
} else {
color_attrefs.push_back(attref);
}
}
}
// compile subpass description structures
for (auto& rp : rpis) {
if (rp.attachments.size() == 0) {
continue;
}
auto& subp = rp.rpci.subpass_descriptions;
auto& color_attrefs = rp.rpci.color_refs;
auto& color_ref_offsets = rp.rpci.color_ref_offsets;
auto& resolve_attrefs = rp.rpci.resolve_refs;
auto& ds_attrefs = rp.rpci.ds_refs;
// subpasses
for (size_t i = 0; i < 1; i++) {
SubpassDescription sd;
size_t color_count = 0;
if (i < 0) {
color_count = color_ref_offsets[i + 1] - color_ref_offsets[i];
} else {
color_count = color_attrefs.size() - color_ref_offsets[i];
}
{
auto first = color_attrefs.data() + color_ref_offsets[i];
sd.colorAttachmentCount = (uint32_t)color_count;
sd.pColorAttachments = first;
}
sd.pDepthStencilAttachment = ds_attrefs[i] ? &*ds_attrefs[i] : nullptr;
sd.flags = {};
sd.inputAttachmentCount = 0;
sd.pInputAttachments = nullptr;
sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
sd.preserveAttachmentCount = 0;
sd.pPreserveAttachments = nullptr;
{
auto first = resolve_attrefs.data() + color_ref_offsets[i];
sd.pResolveAttachments = first;
}
subp.push_back(sd);
}
rp.rpci.subpassCount = (uint32_t)rp.rpci.subpass_descriptions.size();
rp.rpci.pSubpasses = rp.rpci.subpass_descriptions.data();
rp.rpci.dependencyCount = (uint32_t)rp.rpci.subpass_dependencies.size();
rp.rpci.pDependencies = rp.rpci.subpass_dependencies.data();
}
return { expected_value };
}
Result<ExecutableRenderGraph> Compiler::link(std::span<std::shared_ptr<RenderGraph>> rgs, const RenderGraphCompileOptions& compile_options) {
VUK_DO_OR_RETURN(compile(rgs, compile_options));
VUK_DO_OR_RETURN(impl->generate_barriers_and_waits());
VUK_DO_OR_RETURN(impl->merge_rps());
VUK_DO_OR_RETURN(impl->assign_passes_to_batches());
VUK_DO_OR_RETURN(impl->build_waits());
// we now have enough data to build VkRenderPasses and VkFramebuffers
VUK_DO_OR_RETURN(impl->build_renderpasses());
return { expected_value, *this };
}
std::span<ChainLink*> Compiler::get_use_chains() const {
return std::span(impl->chains);
}
MapProxy<QualifiedName, const AttachmentInfo&> Compiler::get_bound_attachments() {
return &impl->bound_attachments;
}
MapProxy<QualifiedName, const BufferInfo&> Compiler::get_bound_buffers() {
return &impl->bound_buffers;
}
ImageUsageFlags Compiler::compute_usage(const ChainLink* head) {
return impl->compute_usage(head);
}
ImageUsageFlags RGCImpl::compute_usage(const ChainLink* head) {
ImageUsageFlags usage = {};
constexpr auto access_to_usage = [](ImageUsageFlags& usage, Access acc) {
if (acc & (eMemoryRW | eColorResolveRead | eColorResolveWrite | eColorRW)) {
usage |= ImageUsageFlagBits::eColorAttachment;
}
if (acc & (eMemoryRW | eFragmentSampled | eComputeSampled | eRayTracingSampled | eVertexSampled)) {
usage |= ImageUsageFlagBits::eSampled;
}
if (acc & (eMemoryRW | eDepthStencilRW)) {
usage |= ImageUsageFlagBits::eDepthStencilAttachment;
}
if (acc & (eMemoryRW | eTransferRead)) {
usage |= ImageUsageFlagBits::eTransferSrc;
}
if (acc & (eMemoryRW | eTransferWrite | eClear)) {
usage |= ImageUsageFlagBits::eTransferDst;
}
if (acc & (eMemoryRW | eFragmentRW | eComputeRW | eRayTracingRW)) {
usage |= ImageUsageFlagBits::eStorage;
}
};
for (auto chain = head; chain != nullptr; chain = chain->next) {
Access ia = Access::eNone;
if (chain->def->pass >= 0) {
ia = get_resource(*chain->def).ia;
}
for (auto& r : chain->reads.to_span(pass_reads)) {
ia = get_resource(r).ia;
}
if (chain->undef && chain->undef->pass >= 0) {
ia = get_resource(*chain->undef).ia;
} else if (chain->undef) {
ia = get_release(chain->undef->pass).original;
}
access_to_usage(usage, ia);
}
return usage;
}
const struct AttachmentInfo& Compiler::get_chain_attachment(const ChainLink* head) {
const ChainLink* link = head;
while (link->def->pass >= 0 || link->source) {
for (; link->def->pass >= 0; link = link->prev)
;
while (link->source) {
for (link = link->source; link->def->pass > 0; link = link->prev)
;
}
}
assert(link->def->pass < 0);
return impl->get_bound_attachment(link->def->pass);
}
std::optional<QualifiedName> Compiler::get_last_use_name(const ChainLink* head) {
const ChainLink* link = head;
for (; link->next != nullptr; link = link->next)
;
if (link->reads.size()) {
auto r = link->reads.to_span(impl->pass_reads)[0];
return impl->get_resource(r).name;
}
if (link->undef) {
if (link->undef->pass >= 0) {
return impl->get_resource(*link->undef).out_name;
} else {
if (link->def->pass >= 0) {
return impl->get_resource(*link->def).out_name;
} else {
return {}; // tailed by release and def unusable
}
}
}
if (link->def) {
if (link->def->pass >= 0) {
return impl->get_resource(*link->def).out_name;
} else {
return link->type == Resource::Type::eImage ? impl->get_bound_attachment(link->def->pass).name
: impl->get_bound_buffer(link->def->pass).name; // the only def we have is the binding
}
}
return {};
}
} // namespace vuk
<file_sep>Context
=======
The Context represents the base object of the runtime, encapsulating the knowledge about the GPU (similar to a VkDevice).
Use this class to manage pipelines and other cached objects, add/remove swapchains, manage persistent descriptor sets, submit work to device and retrieve query results.
.. doxygenstruct:: vuk::ContextCreateParameters
:members:
.. doxygenclass:: vuk::Context
:members:
.. doxygenstruct:: vuk::Query
Submitting work
===============
While submitting work to the device can be performed by the user, it is usually sufficient to use a utility function that takes care of translating a RenderGraph into device execution. Note that these functions are used internally when using :cpp:class:`vuk::Future`s, and as such Futures can be used to manage submission in a more high-level fashion.
.. doxygenfunction:: vuk::execute_submit_and_present_to_one
.. doxygenfunction:: vuk::execute_submit_and_wait
.. doxygenfunction:: vuk::link_execute_submit
<file_sep>#include "bench_runner.hpp"
/* 01_triangle
* In this example we will draw a bufferless triangle, the "Hello world" of graphics programming
* For this, we will need to define our pipeline, and then submit a draw.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
struct V1 {
std::string_view description = "1 iter";
static constexpr unsigned n_iters = 1;
};
struct V2 {
std::string_view description = "100 iters";
static constexpr unsigned n_iters = 100;
};
vuk::Bench<V1, V2> x{
// The display name of this example
.base = { .name = "Dependent vs. non-dependent texture fetch",
// Setup code, ran once in the beginning
.setup =
[](vuk::BenchRunner& runner, vuk::Allocator& frame_allocator) {
// Pipelines are created by filling out a vuk::PipelineCreateInfo
// In this case, we only need the shaders, we don't care about the rest of the state
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file("../../examples/triangle.vert"), "triangle.vert");
pci.add_glsl(util::read_entire_file("../../examples/triangle.frag"), "triangle.frag");
// The pipeline is stored with a user give name for simplicity
runner.context->create_named_pipeline("triangle", pci);
},
.gui =
[](vuk::BenchRunner& runner, vuk::Allocator& frame_allocator) {
} },
.cases = { { "Dependent, small image",
[](vuk::BenchRunner& runner, vuk::Allocator& frame_allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
auto ptc = ifc.begin();
vuk::RenderGraph rg;
rg.add_pass({ .resources = { "_final"_image(vuk::eColorWrite) }, .execute = [start, end, parameters](vuk::CommandBuffer& command_buffer) {
vuk::TimedScope _{ command_buffer, start, end };
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer());
command_buffer
.set_scissor(0, vuk::Rect2D::framebuffer()) // Set the scissor area to cover the entire framebuffer
.bind_graphics_pipeline("triangle") // Recall pipeline for "triangle" and bind
.draw(3 * parameters.n_iters, 1, 0, 0); // Draw 3 vertices
} });
return rg;
} },
{ "Non-dependent, small image",
[](vuk::BenchRunner& runner, vuk::Allocator& frame_allocator, vuk::Query start, vuk::Query end, auto&& parameters) {
auto ptc = ifc.begin();
vuk::RenderGraph rg;
rg.add_pass({ .resources = { "_final"_image(vuk::eColorWrite) }, .execute = [start, end, parameters](vuk::CommandBuffer& command_buffer) {
vuk::TimedScope _{ command_buffer, start, end };
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer());
command_buffer.set_scissor(0, vuk::Rect2D::framebuffer()).bind_graphics_pipeline("triangle");
for (auto i = 0; i < parameters.n_iters; i++) {
command_buffer.draw(3, 1, 0, 0);
}
} });
return rg;
} } }
};
REGISTER_BENCH(x);
} // namespace<file_sep>#include "example_runner.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
#include <stb_image.h>
/* 11_composition
* We expand on example 5 by adding reflections to our deferred cube and FXAA.
* To do this we showcase the composition features of vuk: we extensively use Futures to build up the final rendering. Rendering to and using cubemaps/array
* images is also shown.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
vuk::Future apply_fxaa(vuk::Future source, vuk::Future dst) {
std::unique_ptr<vuk::RenderGraph> rgp = std::make_unique<vuk::RenderGraph>("fxaa");
rgp->attach_in("jagged", std::move(source));
rgp->attach_in("smooth", std::move(dst));
rgp->add_pass({ .name = "fxaa",
.resources = { "jagged"_image >> vuk::eFragmentSampled, "smooth"_image >> vuk::eColorWrite },
.execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
.bind_graphics_pipeline("fxaa");
auto res = *command_buffer.get_resource_image_attachment("smooth");
command_buffer.specialize_constants(0, (float)res.extent.extent.width).specialize_constants(1, (float)res.extent.extent.height);
command_buffer.bind_image(0, 0, "jagged").bind_sampler(0, 0, {}).draw(3, 1, 0, 0);
} });
// bidirectional inference
rgp->inference_rule("jagged", vuk::same_shape_as("smooth"));
rgp->inference_rule("smooth", vuk::same_shape_as("jagged"));
return { std::move(rgp), "smooth+" };
}
std::pair<vuk::Unique<vuk::Image>, vuk::Future> load_hdr_cubemap(vuk::Allocator& allocator, const std::string& path) {
int x, y, chans;
stbi_set_flip_vertically_on_load(true);
auto img = stbi_loadf(path.c_str(), &x, &y, &chans, STBI_rgb_alpha);
stbi_set_flip_vertically_on_load(false);
assert(img != nullptr);
vuk::ImageCreateInfo ici;
ici.format = vuk::Format::eR32G32B32A32Sfloat;
ici.extent = vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u };
ici.samples = vuk::Samples::e1;
ici.imageType = vuk::ImageType::e2D;
ici.tiling = vuk::ImageTiling::eOptimal;
ici.usage = vuk::ImageUsageFlagBits::eTransferSrc | vuk::ImageUsageFlagBits::eTransferDst | vuk::ImageUsageFlagBits::eSampled;
ici.mipLevels = 1;
ici.arrayLayers = 1;
// TODO: not use create_texture
auto [tex, tex_fut] = create_texture(allocator, vuk::Format::eR32G32B32A32Sfloat, vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u }, img, false);
stbi_image_free(img);
return { std::move(tex.image), std::move(tex_fut) };
}
const glm::mat4 capture_projection = glm::perspective(glm::radians(90.0f), 1.0f, 0.1f, 10.0f);
const glm::mat4 capture_views[] = { glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f)) };
namespace {
float angle = 0.f;
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
vuk::Unique<vuk::Image> env_cubemap, hdr_image;
vuk::ImageAttachment env_cubemap_ia;
vuk::Example x{
.name = "11_composition",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/deferred.vert").generic_string()), (root / "deferred.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/deferred_reflective.frag").generic_string()),
(root / "deferred_reflective.frag").generic_string());
runner.context->create_named_pipeline("cube_deferred_reflective", pci);
}
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/fullscreen.vert").generic_string()), (root / "fullscreen.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/deferred_resolve.frag").generic_string()), (root / "deferred_resolve.frag").generic_string());
runner.context->create_named_pipeline("deferred_resolve", pci);
}
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/fullscreen.vert").generic_string()), (root / "fullscreen.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/fxaa.frag").generic_string()), (root / "fxaa.frag").generic_string());
runner.context->create_named_pipeline("fxaa", pci);
}
// We set up the cube data, same as in example 02_cube
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
auto hdr_texture = load_hdr_cubemap(allocator, (root / "examples/the_sky_is_on_fire_1k.hdr").generic_string());
hdr_image = std::move(hdr_texture.first);
// cubemap code from @jazzfool
// hdr_texture is a 2:1 equirectangular; it needs to be converted to a cubemap
env_cubemap_ia = { .image = *env_cubemap,
.image_flags = vuk::ImageCreateFlagBits::eCubeCompatible,
.image_type = vuk::ImageType::e2D,
.usage = vuk::ImageUsageFlagBits::eSampled | vuk::ImageUsageFlagBits::eColorAttachment,
.extent = vuk::Dimension3D::absolute(1024, 1024, 1),
.format = vuk::Format::eR32G32B32A32Sfloat,
.sample_count = vuk::Samples::e1,
.view_type = vuk::ImageViewType::eCube,
.base_level = 0,
.level_count = 1,
.base_layer = 0,
.layer_count = 6 };
env_cubemap = *vuk::allocate_image(allocator, env_cubemap_ia);
env_cubemap_ia.image = *env_cubemap;
vuk::PipelineBaseCreateInfo equirectangular_to_cubemap;
equirectangular_to_cubemap.add_glsl(util::read_entire_file((root / "examples/cubemap.vert").generic_string()),
(root / "examples/cubemap.vert").generic_string());
equirectangular_to_cubemap.add_glsl(util::read_entire_file((root / "examples/equirectangular_to_cubemap.frag").generic_string()),
(root / "examples/equirectangular_to_cubemap.frag").generic_string());
runner.context->create_named_pipeline("equirectangular_to_cubemap", equirectangular_to_cubemap);
// make cubemap by rendering to individual faces - we use a layered framebuffer to achieve this
// this only requires using an attachment with layers
{
vuk::RenderGraph rg("cubegen");
rg.attach_in("hdr_texture", std::move(hdr_texture.second));
rg.attach_in("verts", std::move(vert_fut));
rg.attach_in("inds", std::move(ind_fut));
rg.attach_image("env_cubemap", env_cubemap_ia, vuk::Access::eNone);
rg.add_pass({ .resources = { "env_cubemap"_image >> vuk::eColorWrite,
"hdr_texture"_image >> vuk::eFragmentSampled,
"verts"_buffer >> vuk::eAttributeRead,
"inds"_buffer >> vuk::eIndexRead },
.execute = [=](vuk::CommandBuffer& cbuf) {
cbuf.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.broadcast_color_blend(vuk::BlendPreset::eOff)
.set_rasterization({})
.bind_vertex_buffer(
0,
*cbuf.get_resource_buffer("verts"),
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat, vuk::Ignore{ sizeof(util::Vertex) - sizeof(util::Vertex::position) } })
.bind_index_buffer(*cbuf.get_resource_buffer("inds"), vuk::IndexType::eUint32)
.bind_image(0, 2, "hdr_texture")
.bind_sampler(0,
2,
vuk::SamplerCreateInfo{ .magFilter = vuk::Filter::eLinear,
.minFilter = vuk::Filter::eLinear,
.mipmapMode = vuk::SamplerMipmapMode::eLinear,
.addressModeU = vuk::SamplerAddressMode::eClampToEdge,
.addressModeV = vuk::SamplerAddressMode::eClampToEdge,
.addressModeW = vuk::SamplerAddressMode::eClampToEdge })
.bind_graphics_pipeline("equirectangular_to_cubemap");
glm::mat4* projection = cbuf.map_scratch_buffer<glm::mat4>(0, 0);
*projection = capture_projection;
using mats = glm::mat4[6];
mats* view = cbuf.map_scratch_buffer<glm::mat4[6]>(0, 1);
memcpy(view, capture_views, sizeof(capture_views));
cbuf.draw_indexed(box.second.size(), 6, 0, 0, 0);
} });
// transition the cubemap for fragment sampling access to complete init
auto fut_in_layout = vuk::transition(vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "env_cubemap+" }, vuk::eFragmentSampled);
runner.enqueue_setup(std::move(fut_in_layout));
}
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
auto cam_pos = glm::vec3(0, 0.5, 7.5);
vp.view = glm::lookAt(cam_pos, glm::vec3(0), glm::vec3(0, 1, 0));
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 0.1f, 30.f);
vp.proj[1][1] *= -1;
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
// we are going to render the scene twice - once into a cubemap, then subsequently, we'll render it again while sampling from the cubemap
// this time we will show off rendering to individual cubemap faces
// create the cubemap in a separate rendergraph
std::shared_ptr<vuk::RenderGraph> cube_src = std::make_shared<vuk::RenderGraph>("cube_src");
cube_src->attach_image("11_cube",
{ .image_flags = vuk::ImageCreateFlagBits::eCubeCompatible,
.image_type = vuk::ImageType::e2D,
.extent = vuk::Dimension3D::absolute(1024, 1024, 1),
.format = vuk::Format::eR8G8B8A8Srgb,
.sample_count = vuk::Samples::e1,
.view_type = vuk::ImageViewType::eCube,
.level_count = 1,
.layer_count = 6 });
// we split the cubemap into faces
for (uint32_t i = 0; i < 6; i++) {
cube_src->diverge_image("11_cube", vuk::Subrange::Image{ .base_layer = i, .layer_count = 1 }, vuk::Name("11_cube_face_").append(std::to_string(i)));
}
std::shared_ptr<vuk::RenderGraph> cube_refl = std::make_shared<vuk::RenderGraph>("scene");
// for each face we do standard (example 05) deferred scene rendering
// but we resolve the deferred scene into the appropriate cubemap face
std::vector<vuk::Name> cube_face_names;
for (int i = 0; i < 6; i++) {
std::shared_ptr<vuk::RenderGraph> rg = std::make_shared<vuk::RenderGraph>("single_face_MRT");
// Here we will render the cube into 3 offscreen textures
// The intermediate offscreen textures need to be bound
// The "internal" rendering resolution is set here for one attachment, the rest infers from it
rg->attach_and_clear_image("11_position", { .format = vuk::Format::eR16G16B16A16Sfloat, .sample_count = vuk::Samples::e1 }, vuk::White<float>);
rg->attach_and_clear_image("11_normal", { .format = vuk::Format::eR16G16B16A16Sfloat }, vuk::White<float>);
rg->attach_and_clear_image("11_color", { .format = vuk::Format::eR8G8B8A8Srgb }, vuk::White<float>);
rg->attach_and_clear_image("11_depth", { .format = vuk::Format::eD32Sfloat }, vuk::DepthOne);
rg->add_pass({ .name = "single_face_MRT",
.resources = { "11_position"_image >> vuk::eColorWrite,
"11_normal"_image >> vuk::eColorWrite,
"11_color"_image >> vuk::eColorWrite,
"11_depth"_image >> vuk::eDepthStencilRW },
.execute = [i, cam_pos](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization(vuk::PipelineRasterizationStateCreateInfo{
.cullMode = vuk::CullModeFlagBits::eBack }) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
.depthWriteEnable = true,
.depthCompareOp = vuk::CompareOp::eLessOrEqual,
})
.broadcast_color_blend({})
.bind_vertex_buffer(0,
*verts,
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat,
vuk::Format::eR32G32B32Sfloat,
vuk::Ignore{ offsetof(util::Vertex, uv_coordinates) - offsetof(util::Vertex, tangent) },
vuk::Format::eR32G32Sfloat })
.bind_index_buffer(*inds, vuk::IndexType::eUint32);
command_buffer.push_constants(vuk::ShaderStageFlagBits::eFragment, 0, cam_pos).bind_graphics_pipeline("cube_deferred_reflective");
for (auto j = 0; j < 64; j++) {
if (j == 36)
continue;
command_buffer.bind_image(0, 2, env_cubemap_ia).bind_sampler(0, 2, {});
VP* VP_data = command_buffer.map_scratch_buffer<VP>(0, 0);
VP_data->proj = capture_projection;
VP_data->view = capture_views[i];
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = glm::scale(glm::mat4(1.f), glm::vec3(0.1f)) *
glm::translate(glm::mat4(1.f), 4.f * glm::vec3(4 * (j % 8 - 4), sinf(0.1f * angle + j), 4 * (j / 8 - 4)));
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
}
} });
rg->attach_in("11_cube_face", vuk::Future{ cube_src, vuk::Name("11_cube_face_").append(std::to_string(i)) });
rg->inference_rule("11_position+", vuk::same_2D_extent_as("11_cube_face"));
// The shading pass for the deferred rendering
rg->add_pass({ .name = "single_face_resolve",
// Declare that we are going to render to the final color image
// Declare that we are going to sample (in the fragment shader) from the previous attachments
.resources = { "11_cube_face"_image >> vuk::eColorWrite >> "11_cube_face+",
"11_position+"_image >> vuk::eFragmentSampled,
"11_normal+"_image >> vuk::eFragmentSampled,
"11_color+"_image >> vuk::eFragmentSampled },
.execute = [cam_pos](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
.bind_graphics_pipeline("deferred_resolve");
// Set camera position so we can do lighting
*command_buffer.map_scratch_buffer<glm::vec3>(0, 3) = cam_pos;
// We will sample using nearest neighbour
vuk::SamplerCreateInfo sci;
sci.minFilter = sci.magFilter = vuk::Filter::eNearest;
// Bind the previous attachments as sampled images
command_buffer.bind_image(0, 0, "11_position+")
.bind_sampler(0, 0, sci)
.bind_image(0, 1, "11_normal+")
.bind_sampler(0, 1, sci)
.bind_image(0, 2, "11_color+")
.bind_sampler(0, 2, sci)
.draw(3, 1, 0, 0);
} });
vuk::Future lit_fut = { std::move(rg), "11_cube_face+" };
auto cube_face_name = vuk::Name("11_deferred_face_").append(std::to_string(i));
cube_face_names.emplace_back(cube_face_name);
// we attach the cubemap face into the final rendegraph
cube_refl->attach_in(cube_face_name, std::move(lit_fut));
}
// time to render the final scene
// we collect the cubemap faces
cube_refl->converge_image_explicit(cube_face_names, "11_cuberefl");
// and do the standard deferred rendering as before, this time using the new cube map for the environment
cube_refl->attach_and_clear_image("11_position", { .format = vuk::Format::eR16G16B16A16Sfloat, .sample_count = vuk::Samples::e1 }, vuk::White<float>);
cube_refl->attach_and_clear_image("11_normal", { .format = vuk::Format::eR16G16B16A16Sfloat }, vuk::White<float>);
cube_refl->attach_and_clear_image("11_color", { .format = vuk::Format::eR8G8B8A8Srgb }, vuk::White<float>);
cube_refl->attach_and_clear_image("11_depth", { .format = vuk::Format::eD32Sfloat }, vuk::DepthOne);
cube_refl->add_pass(
{ .name = "deferred_MRT",
.resources = { "11_position"_image >> vuk::eColorWrite,
"11_normal"_image >> vuk::eColorWrite,
"11_color"_image >> vuk::eColorWrite,
"11_depth"_image >> vuk::eDepthStencilRW,
"11_cuberefl"_image >> vuk::eFragmentSampled },
.execute = [uboVP, cam_pos](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization(vuk::PipelineRasterizationStateCreateInfo{}) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
.depthWriteEnable = true,
.depthCompareOp = vuk::CompareOp::eLessOrEqual,
})
.broadcast_color_blend({})
.bind_vertex_buffer(0,
*verts,
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat,
vuk::Format::eR32G32B32Sfloat,
vuk::Ignore{ offsetof(util::Vertex, uv_coordinates) - offsetof(util::Vertex, tangent) },
vuk::Format::eR32G32Sfloat })
.bind_index_buffer(*inds, vuk::IndexType::eUint32);
command_buffer.push_constants(vuk::ShaderStageFlagBits::eFragment, 0, cam_pos).bind_graphics_pipeline("cube_deferred_reflective");
command_buffer.bind_image(0, 2, "11_cuberefl").bind_sampler(0, 2, {}).bind_buffer(0, 0, uboVP);
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = static_cast<glm::mat4>(glm::angleAxis(glm::radians(angle), glm::vec3(0.f, 1.f, 0.f)));
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
for (auto i = 0; i < 64; i++) {
if (i == 36)
continue;
command_buffer.bind_image(0, 2, env_cubemap_ia).bind_sampler(0, 2, {}).bind_buffer(0, 0, uboVP);
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = glm::scale(glm::mat4(1.f), glm::vec3(0.1f)) *
glm::translate(glm::mat4(1.f), 4.f * glm::vec3(4 * (i % 8 - 4), sinf(0.1f * angle + i), 4 * (i / 8 - 4)));
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
}
} });
cube_refl->attach_image("11_deferred", { .format = vuk::Format::eR8G8B8A8Srgb, .sample_count = vuk::Samples::e1 });
cube_refl->inference_rule("11_position+", vuk::same_extent_as("11_deferred"));
// The shading pass for the deferred rendering
cube_refl->add_pass({ .name = "deferred_resolve",
// Declare that we are going to render to the final color image
// Declare that we are going to sample (in the fragment shader) from the previous attachments
.resources = { "11_deferred"_image >> vuk::eColorWrite >> "11_deferred+",
"11_position+"_image >> vuk::eFragmentSampled,
"11_normal+"_image >> vuk::eFragmentSampled,
"11_color+"_image >> vuk::eFragmentSampled },
.execute = [cam_pos](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
.bind_graphics_pipeline("deferred_resolve");
// Set camera position so we can do lighting
*command_buffer.map_scratch_buffer<glm::vec3>(0, 3) = cam_pos;
// We will sample using nearest neighbour
vuk::SamplerCreateInfo sci;
sci.minFilter = sci.magFilter = vuk::Filter::eNearest;
// Bind the previous attachments as sampled images
command_buffer.bind_image(0, 0, "11_position+")
.bind_sampler(0, 0, sci)
.bind_image(0, 1, "11_normal+")
.bind_sampler(0, 1, sci)
.bind_image(0, 2, "11_color+")
.bind_sampler(0, 2, sci)
.draw(3, 1, 0, 0);
} });
vuk::Future lit_fut = { std::move(cube_refl), "11_deferred+" };
vuk::Future sm_fut = apply_fxaa(std::move(lit_fut), std::move(target));
angle += 10.f * ImGui::GetIO().DeltaTime;
return sm_fut;
}, // Perform cleanup for the example
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
// We release the resources manually
verts.reset();
inds.reset();
env_cubemap.reset();
hdr_image.reset();
}
};
REGISTER_EXAMPLE(x);
} // namespace
<file_sep>#pragma once
#include "vuk/Allocator.hpp"
#include "vuk/resources/DeviceNestedResource.hpp"
#include "vuk/resources/DeviceVkResource.hpp"
#include <memory>
namespace vuk {
struct DeviceSuperFrameResource;
/// @brief Represents "per-frame" resources - temporary allocations that persist through a frame. Handed out by DeviceSuperFrameResource, cannot be
/// constructed directly.
///
/// Allocations from this resource are tied to the "frame" - all allocations recycled when a DeviceFrameResource is recycled.
/// Furthermore all resources allocated are also deallocated at recycle time - it is not necessary (but not an error) to deallocate them.
struct DeviceFrameResource : DeviceNestedResource {
Result<void, AllocateException> allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) override;
void deallocate_semaphores(std::span<const VkSemaphore> src) override; // noop
Result<void, AllocateException> allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) override;
void deallocate_fences(std::span<const VkFence> src) override; // noop
Result<void, AllocateException> allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_command_buffers(std::span<const CommandBufferAllocation> src) override; // no-op, deallocated with pools
Result<void, AllocateException>
allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_command_pools(std::span<const CommandPool> dst) override; // no-op
// buffers are lockless
Result<void, AllocateException> allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_buffers(std::span<const Buffer> src) override; // no-op, linear
Result<void, AllocateException>
allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_framebuffers(std::span<const VkFramebuffer> src) override; // noop
Result<void, AllocateException> allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_images(std::span<const Image> src) override; // noop
Result<void, AllocateException>
allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_image_views(std::span<const ImageView> src) override; // noop
Result<void, AllocateException> allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) override; // noop
Result<void, AllocateException>
allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) override;
Result<void, AllocateException>
allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_descriptor_sets(std::span<const DescriptorSet> src) override;
Result<void, AllocateException>
allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst, std::span<const VkQueryPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) override; // noop
Result<void, AllocateException>
allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_timestamp_queries(std::span<const TimestampQuery> src) override; // noop
Result<void, AllocateException> allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) override;
void deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) override; // noop
void deallocate_swapchains(std::span<const VkSwapchainKHR> src) override;
Result<void, AllocateException> allocate_graphics_pipelines(std::span<GraphicsPipelineInfo> dst,
std::span<const GraphicsPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_graphics_pipelines(std::span<const GraphicsPipelineInfo> src) override;
Result<void, AllocateException>
allocate_compute_pipelines(std::span<ComputePipelineInfo> dst, std::span<const ComputePipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_compute_pipelines(std::span<const ComputePipelineInfo> src) override;
Result<void, AllocateException> allocate_ray_tracing_pipelines(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_ray_tracing_pipelines(std::span<const RayTracingPipelineInfo> src) override;
Result<void, AllocateException>
allocate_render_passes(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_render_passes(std::span<const VkRenderPass> src) override;
/// @brief Wait for the fences / timeline semaphores referencing this frame to complete
///
/// Called automatically when recycled
void wait();
/// @brief Retrieve the parent Context
/// @return the parent Context
Context& get_context() override {
return upstream->get_context();
}
protected:
VkDevice device;
uint64_t construction_frame = -1;
std::unique_ptr<struct DeviceFrameResourceImpl> impl;
friend struct DeviceSuperFrameResource;
friend struct DeviceSuperFrameResourceImpl;
DeviceFrameResource(VkDevice device, DeviceSuperFrameResource& upstream);
};
/// @brief Represents temporary allocations that persist through multiple frames, eg. history buffers. Handed out by DeviceSuperFrameResource, cannot be
/// constructed directly.
///
/// Allocations from this resource are tied to the "multi-frame" - all allocations recycled when a DeviceMultiFrameResource is recycled.
/// All resources allocated are also deallocated at recycle time - it is not necessary (but not an error) to deallocate them.
struct DeviceMultiFrameResource final : DeviceFrameResource {
Result<void, AllocateException> allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) override;
private:
uint32_t frame_lifetime;
uint32_t remaining_lifetime;
uint32_t multiframe_id;
friend struct DeviceSuperFrameResource;
friend struct DeviceSuperFrameResourceImpl;
DeviceMultiFrameResource(VkDevice device, DeviceSuperFrameResource& upstream, uint32_t frame_lifetime);
};
/// @brief DeviceSuperFrameResource is an allocator that gives out DeviceFrameResource allocators, and manages their resources
///
/// DeviceSuperFrameResource models resource lifetimes that span multiple frames - these can be allocated directly from this resource
/// Allocation of these resources are persistent, and they can be deallocated at any time - they will be recycled when the current frame is recycled
/// This resource also hands out DeviceFrameResources in a round-robin fashion.
/// The lifetime of resources allocated from those allocators is frames_in_flight number of frames (until the DeviceFrameResource is recycled).
struct DeviceSuperFrameResource : DeviceNestedResource {
DeviceSuperFrameResource(Context& ctx, uint64_t frames_in_flight);
DeviceSuperFrameResource(DeviceResource& upstream, uint64_t frames_in_flight);
void deallocate_semaphores(std::span<const VkSemaphore> src) override;
void deallocate_fences(std::span<const VkFence> src) override;
void deallocate_command_buffers(std::span<const CommandBufferAllocation> src) override;
Result<void, AllocateException>
allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_command_pools(std::span<const CommandPool> src) override;
void deallocate_buffers(std::span<const Buffer> src) override;
void deallocate_framebuffers(std::span<const VkFramebuffer> src) override;
void deallocate_images(std::span<const Image> src) override;
Result<void, AllocateException> allocate_cached_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc);
Result<void, AllocateException> allocate_cached_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc);
Result<void, AllocateException> allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_image_views(std::span<const ImageView> src) override;
void deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) override;
void deallocate_descriptor_sets(std::span<const DescriptorSet> src) override;
Result<void, AllocateException>
allocate_descriptor_pools(std::span<VkDescriptorPool> dst, std::span<const VkDescriptorPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_descriptor_pools(std::span<const VkDescriptorPool> src) override;
void deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) override;
void deallocate_timestamp_queries(std::span<const TimestampQuery> src) override; // noop
void deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) override;
void deallocate_acceleration_structures(std::span<const VkAccelerationStructureKHR> src) override;
void deallocate_swapchains(std::span<const VkSwapchainKHR> src) override;
void deallocate_graphics_pipelines(std::span<const GraphicsPipelineInfo> src) override;
void deallocate_compute_pipelines(std::span<const ComputePipelineInfo> src) override;
void deallocate_ray_tracing_pipelines(std::span<const RayTracingPipelineInfo> src) override;
void deallocate_render_passes(std::span<const VkRenderPass> src) override;
/// @brief Recycle the least-recently-used frame and return it to be used again
/// @return DeviceFrameResource for use
DeviceFrameResource& get_next_frame();
/// @brief Get a multiframe resource for the current frame with the specified frame lifetime count
/// The returned resource ensures that any resource allocated from it will be usable for at least `frame_lifetime_count`
DeviceMultiFrameResource& get_multiframe_allocator(uint32_t frame_lifetime_count);
void force_collect();
virtual ~DeviceSuperFrameResource();
const uint64_t frames_in_flight;
DeviceVkResource* direct = nullptr;
private:
DeviceFrameResource& get_last_frame();
template<class T>
void deallocate_frame(T& f);
struct DeviceSuperFrameResourceImpl* impl;
friend struct DeviceFrameResource;
};
} // namespace vuk<file_sep>#pragma once
#include "vuk/Bitset.hpp"
#include "vuk/Config.hpp"
#include "vuk/Hash.hpp"
#include "vuk/Image.hpp"
#include "vuk/Types.hpp"
#include "vuk/vuk_fwd.hpp"
#include <array>
#include <cassert>
#include <span>
#include <string.h>
#include <tuple>
#include <vector>
inline bool operator==(VkDescriptorSetLayoutBinding const& lhs, VkDescriptorSetLayoutBinding const& rhs) noexcept {
return (lhs.binding == rhs.binding) && (lhs.descriptorType == rhs.descriptorType) && (lhs.descriptorCount == rhs.descriptorCount) &&
(lhs.stageFlags == rhs.stageFlags) && (lhs.pImmutableSamplers == rhs.pImmutableSamplers);
}
namespace std {
template<class T, size_t E>
struct hash<std::span<T, E>> {
size_t operator()(std::span<T, E> const& x) const noexcept {
size_t h = 0;
for (auto& e : x) {
hash_combine(h, e);
}
return h;
}
};
}; // namespace std
namespace vuk {
enum class DescriptorType : uint8_t {
eSampler = VK_DESCRIPTOR_TYPE_SAMPLER,
eCombinedImageSampler = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
eSampledImage = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
eStorageImage = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
eUniformTexelBuffer = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,
eStorageTexelBuffer = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER,
eUniformBuffer = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
eStorageBuffer = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
eUniformBufferDynamic = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,
eStorageBufferDynamic = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC,
eInputAttachment = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT,
eInlineUniformBlockEXT = 10,
eAccelerationStructureKHR = 11,
ePendingWrite = 128
};
enum class DescriptorBindingFlagBits : VkDescriptorBindingFlags {
eUpdateAfterBind = VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT,
eUpdateUnusedWhilePending = VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT,
ePartiallyBound = VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT,
eVariableDescriptorCount = VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT
};
using DescriptorBindingFlags = Flags<DescriptorBindingFlagBits>;
inline constexpr DescriptorBindingFlags operator|(DescriptorBindingFlagBits bit0, DescriptorBindingFlagBits bit1) noexcept {
return DescriptorBindingFlags(bit0) | bit1;
}
inline constexpr DescriptorBindingFlags operator&(DescriptorBindingFlagBits bit0, DescriptorBindingFlagBits bit1) noexcept {
return DescriptorBindingFlags(bit0) & bit1;
}
inline constexpr DescriptorBindingFlags operator^(DescriptorBindingFlagBits bit0, DescriptorBindingFlagBits bit1) noexcept {
return DescriptorBindingFlags(bit0) ^ bit1;
}
struct DescriptorSetLayoutAllocInfo {
std::array<uint32_t, 12> descriptor_counts = {};
VkDescriptorSetLayout layout;
unsigned variable_count_binding = (unsigned)-1;
DescriptorType variable_count_binding_type;
unsigned variable_count_binding_max_size;
bool operator==(const DescriptorSetLayoutAllocInfo& o) const noexcept {
return layout == o.layout && descriptor_counts == o.descriptor_counts;
}
};
struct DescriptorImageInfo {
VkDescriptorImageInfo dii;
decltype(ImageView::id) image_view_id;
decltype(Sampler::id) sampler_id;
DescriptorImageInfo(Sampler s, ImageView iv, ImageLayout il) : dii{ s.payload, iv.payload, (VkImageLayout)il }, image_view_id(iv.id), sampler_id(s.id) {}
void set_sampler(Sampler s) {
dii.sampler = s.payload;
sampler_id = s.id;
}
void set_image_view(ImageView iv) {
dii.imageView = iv.payload;
image_view_id = iv.id;
}
bool operator==(const DescriptorImageInfo& o) const noexcept {
return dii.sampler == o.dii.sampler && dii.imageView == o.dii.imageView && dii.imageLayout == o.dii.imageLayout && image_view_id == o.image_view_id &&
sampler_id == o.sampler_id;
}
operator VkDescriptorImageInfo() const {
return dii;
}
};
struct ASInfo {
VkWriteDescriptorSetAccelerationStructureKHR wds{ VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR };
VkAccelerationStructureKHR as;
};
// use hand rolled variant to control bits
// memset to clear out the union
#pragma pack(push, 1)
struct DescriptorBinding {
DescriptorBinding() {}
DescriptorType type = DescriptorType(127);
union {
VkDescriptorBufferInfo buffer;
DescriptorImageInfo image;
ASInfo as;
};
bool operator==(const DescriptorBinding& o) const noexcept {
if (type != o.type)
return false;
switch (type) {
case DescriptorType::eUniformBuffer:
case DescriptorType::eStorageBuffer:
return memcmp(&buffer, &o.buffer, sizeof(VkDescriptorBufferInfo)) == 0;
case DescriptorType::eStorageImage:
case DescriptorType::eSampledImage:
case DescriptorType::eSampler:
case DescriptorType::eCombinedImageSampler:
return image == o.image;
case DescriptorType::eAccelerationStructureKHR:
return as.as == o.as.as;
default:
assert(0);
return false;
}
}
static VkDescriptorType vk_descriptor_type(DescriptorType type) {
switch (type) {
case DescriptorType::eUniformBuffer:
return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
case DescriptorType::eStorageBuffer:
return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
case DescriptorType::eStorageImage:
return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
case DescriptorType::eSampledImage:
return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
case DescriptorType::eSampler:
return VK_DESCRIPTOR_TYPE_SAMPLER;
case DescriptorType::eCombinedImageSampler:
return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
case DescriptorType::eAccelerationStructureKHR:
return VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
default:
assert(0);
return VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
}
}
};
#pragma pack(pop)
struct SetBinding {
Bitset<VUK_MAX_BINDINGS> used = {};
DescriptorBinding bindings[VUK_MAX_BINDINGS];
DescriptorSetLayoutAllocInfo* layout_info = nullptr;
uint64_t hash = 0;
SetBinding finalize(Bitset<VUK_MAX_BINDINGS> used_mask);
bool operator==(const SetBinding& o) const noexcept {
if (layout_info != o.layout_info)
return false;
return memcmp(bindings, o.bindings, VUK_MAX_BINDINGS * sizeof(DescriptorBinding)) == 0;
}
};
struct DescriptorSetLayoutCreateInfo {
VkDescriptorSetLayoutCreateInfo dslci = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
size_t index; // index of the descriptor set when used in a pipeline layout
std::vector<VkDescriptorSetLayoutBinding> bindings;
Bitset<VUK_MAX_BINDINGS> used_bindings = {}; // used for ephemeral desc sets
Bitset<VUK_MAX_BINDINGS> optional = {};
std::vector<VkDescriptorBindingFlags> flags;
bool operator==(const DescriptorSetLayoutCreateInfo& o) const noexcept {
return dslci.flags == o.dslci.flags && bindings == o.bindings && flags == o.flags;
}
};
template<>
struct create_info<DescriptorSetLayoutAllocInfo> {
using type = DescriptorSetLayoutCreateInfo;
};
struct DescriptorSet {
VkDescriptorSet descriptor_set = VK_NULL_HANDLE;
DescriptorSetLayoutAllocInfo layout_info;
bool operator==(const DescriptorSet& o) const noexcept {
return descriptor_set == o.descriptor_set;
}
};
template<>
struct create_info<DescriptorSet> {
using type = SetBinding;
};
struct DescriptorPool {
void grow(Context& ptc, DescriptorSetLayoutAllocInfo layout_alloc_info);
VkDescriptorSet acquire(Context& ptc, DescriptorSetLayoutAllocInfo layout_alloc_info);
void release(VkDescriptorSet ds);
void destroy(Context& ctx, VkDevice) const;
DescriptorPool();
~DescriptorPool();
DescriptorPool(DescriptorPool&& o) noexcept;
private:
struct DescriptorPoolImpl* impl = nullptr;
};
template<>
struct create_info<DescriptorPool> {
using type = DescriptorSetLayoutAllocInfo;
};
struct PersistentDescriptorSetCreateInfo {
DescriptorSetLayoutAllocInfo dslai;
DescriptorSetLayoutCreateInfo dslci;
uint32_t num_descriptors;
};
struct Buffer;
struct PersistentDescriptorSet {
VkDescriptorPool backing_pool;
DescriptorSetLayoutCreateInfo set_layout_create_info;
VkDescriptorSetLayout set_layout;
VkDescriptorSet backing_set;
std::vector<VkWriteDescriptorSet> wdss;
std::array<std::vector<DescriptorBinding>, VUK_MAX_BINDINGS> descriptor_bindings;
bool operator==(const PersistentDescriptorSet& other) const {
return backing_pool == other.backing_pool;
}
// all of the update_ functions are thread safe
void update_combined_image_sampler(unsigned binding, unsigned array_index, ImageView iv, Sampler sampler, ImageLayout layout);
void update_storage_image(unsigned binding, unsigned array_index, ImageView iv);
void update_uniform_buffer(unsigned binding, unsigned array_index, Buffer buf);
void update_storage_buffer(unsigned binding, unsigned array_index, Buffer buf);
void update_sampler(unsigned binding, unsigned array_index, Sampler sampler);
void update_sampled_image(unsigned binding, unsigned array_index, ImageView iv, ImageLayout layout);
void update_acceleration_structure(unsigned binding, unsigned array_index, VkAccelerationStructureKHR as);
// non-thread safe
void commit(Context& ctx);
};
} // namespace vuk
namespace std {
template<>
struct hash<vuk::SetBinding> {
size_t operator()(vuk::SetBinding const& x) const noexcept {
return x.hash;
}
};
template<>
struct hash<vuk::DescriptorSetLayoutAllocInfo> {
size_t operator()(vuk::DescriptorSetLayoutAllocInfo const& x) const noexcept {
size_t h = 0;
// TODO: should use vuk::DescriptorSetLayout here
hash_combine(h,
::hash::fnv1a::hash(
(const char*)&x.descriptor_counts[0], x.descriptor_counts.size() * sizeof(x.descriptor_counts[0]), ::hash::fnv1a::default_offset_basis),
(VkDescriptorSetLayout)x.layout);
return h;
}
};
template<>
struct hash<VkDescriptorSetLayoutBinding> {
size_t operator()(VkDescriptorSetLayoutBinding const& x) const noexcept {
size_t h = 0;
// TODO: immutable samplers
hash_combine(h, x.binding, x.descriptorCount, x.descriptorType, x.stageFlags);
return h;
}
};
template<>
struct hash<vuk::DescriptorSetLayoutCreateInfo> {
size_t operator()(vuk::DescriptorSetLayoutCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, std::span(x.bindings));
return h;
}
};
}; // namespace std
<file_sep>#pragma once
#include "vuk/Image.hpp"
#include "vuk/Types.hpp"
#include <optional>
namespace vuk {
// high level type around binding a sampled image with a sampler
struct SampledImage {
struct Global {
vuk::ImageView iv;
vuk::SamplerCreateInfo sci = {};
vuk::ImageLayout image_layout;
};
struct RenderGraphAttachment {
NameReference reference;
vuk::SamplerCreateInfo sci = {};
std::optional<vuk::ImageViewCreateInfo> ivci = {};
vuk::ImageLayout image_layout;
};
union {
Global global = {};
RenderGraphAttachment rg_attachment;
};
bool is_global;
SampledImage(Global g) : global(g), is_global(true) {}
SampledImage(RenderGraphAttachment g) : rg_attachment(g), is_global(false) {}
SampledImage(const SampledImage& o) {
*this = o;
}
SampledImage& operator=(const SampledImage& o) {
if (o.is_global) {
global = {};
global = o.global;
} else {
rg_attachment = {};
rg_attachment = o.rg_attachment;
}
is_global = o.is_global;
return *this;
}
};
} // namespace vuk
<file_sep>cmake_minimum_required(VERSION 3.7)
project(vuk LANGUAGES CXX)
include(ExternalProject)
include(FetchContent)
set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH})
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
add_library(vuk)
option(VUK_BUILD_EXAMPLES "Build examples" OFF)
option(VUK_BUILD_BENCHMARKS "Build benchmarks" OFF)
option(VUK_BUILD_DOCS "Build docs" OFF)
option(VUK_LINK_TO_LOADER "Link \"statically\" to the loader" ON)
option(VUK_USE_VULKAN_SDK "Use the Vulkan SDK to locate headers and libraries" ON)
option(VUK_USE_SHADERC "Link in shaderc for runtime compilation of GLSL shaders" ON)
option(VUK_USE_DXC "Link in DirectXShaderCompiler for runtime compilation of HLSL shaders" OFF)
option(VUK_BUILD_TESTS "Build tests" OFF)
option(VUK_FAIL_FAST "Trigger an assert upon encountering an error instead of propagating" OFF)
option(VUK_DEBUG_ALLOCATIONS "Dump VMA allocations and give them debug names" OFF)
if(CMAKE_SIZEOF_VOID_P EQUAL "4")
message(FATAL_ERROR "x86 is not supported.")
endif()
##### Using vuk with volk (or a similar library)
# step 1: turn off VUK_LINK_TO_LOADER and add_subdirectory vuk
# set(VUK_LINK_TO_LOADER OFF)
# add_subdirectory(vuk)
# step 2: replace the default <vulkan/vulkan.h> with your include
# target_compile_definitions(vuk PUBLIC VUK_CUSTOM_VULKAN_HEADER=<volk.h>)
# step 3: link vuk to the loader lib (this policy might be needed for link_libraries)
# cmake_policy(SET CMP0079 NEW)
# target_link_libraries(vuk PUBLIC volk)
#####
if(VUK_USE_VULKAN_SDK)
find_package(Vulkan REQUIRED)
if(VUK_USE_SHADERC)
add_library(shaderc UNKNOWN IMPORTED)
if(WIN32)
# use the version in the SDK
set_target_properties(shaderc PROPERTIES IMPORTED_LOCATION $ENV{VULKAN_SDK}/Lib/shaderc_shared.lib)
set_property(TARGET shaderc PROPERTY INTERFACE_INCLUDE_DIRECTORIES $ENV{VULKAN_SDK}/Include)
target_link_libraries(vuk PRIVATE shaderc)
else()
target_link_directories(vuk PUBLIC $ENV{VULKAN_SDK}/lib)
target_link_libraries(vuk PRIVATE shaderc_combined glslang MachineIndependent OSDependent OGLCompiler GenericCodeGen SPIRV SPIRV-Tools-opt SPIRV-Tools)
endif()
endif()
if (VUK_USE_DXC)
add_library(dxc UNKNOWN IMPORTED)
if (WIN32)
set_target_properties(dxc PROPERTIES IMPORTED_LOCATION $ENV{VULKAN_SDK}/Lib/dxcompiler.lib)
set_property(TARGET dxc PROPERTY INTERFACE_INCLUDE_DIRECTORIES $ENV{VULKAN_SDK}/Include)
target_link_libraries(vuk PRIVATE dxc)
else()
target_link_libraries(vuk PRIVATE dxcompiler)
endif()
endif()
else()
if (VUK_USE_SHADERC)
target_link_libraries(vuk PRIVATE shaderc_combined glslang MachineIndependent OSDependent OGLCompiler GenericCodeGen SPIRV SPIRV-Tools-opt SPIRV-Tools)
endif()
if (VUK_USE_DXC)
target_link_libraries(vuk PRIVATE dxcompiler)
endif()
endif()
target_compile_definitions(vuk PUBLIC
VUK_USE_SHADERC=$<BOOL:${VUK_USE_SHADERC}>
VUK_USE_DXC=$<BOOL:${VUK_USE_DXC}>
VUK_BUILD_TESTS=$<BOOL:${VUK_BUILD_TESTS}>
VUK_FAIL_FAST=$<BOOL:${VUK_FAIL_FAST}>
VUK_DEBUG_ALLOCATIONS=$<BOOL:${VUK_DEBUG_ALLOCATIONS}>
)
set(SPIRV_CROSS_CLI OFF CACHE BOOL "")
set(SPIRV_CROSS_ENABLE_TESTS OFF CACHE BOOL "")
set(SPIRV_CROSS_ENABLE_HLSL OFF CACHE BOOL "")
set(SPIRV_CROSS_ENABLE_MSL OFF CACHE BOOL "")
set(SPIRV_CROSS_ENABLE_CPP OFF CACHE BOOL "")
set(SPIRV_CROSS_ENABLE_REFLECT OFF CACHE BOOL "")
set(SPIRV_CROSS_ENABLE_C_API OFF CACHE BOOL "")
set(SPIRV_CROSS_ENABLE_UTIL OFF CACHE BOOL "")
add_subdirectory(ext/SPIRV-Cross)
# we don't enable this directly, because the order of flags disables /Zc:char8_t- on MSVC
#target_compile_features(vuk PUBLIC cxx_std_20)
target_sources(vuk PRIVATE
src/Pipeline.cpp
src/Program.cpp
src/Cache.cpp
src/RenderGraph.cpp
src/RenderGraphUtil.cpp
src/ExecutableRenderGraph.cpp
src/Allocator.cpp
src/Context.cpp
src/CommandBuffer.cpp
src/Descriptor.cpp
src/Util.cpp
src/Format.cpp
src/Name.cpp
src/DeviceFrameResource.cpp
src/DeviceVkResource.cpp
src/BufferAllocator.cpp
src/DeviceLinearResource.cpp
)
target_include_directories(vuk PUBLIC ext/plf_colony)
add_subdirectory(ext/robin-hood-hashing)
if (NOT TARGET fmt::fmt)
add_subdirectory(ext/fmt)
endif()
target_include_directories(vuk PRIVATE ext/concurrentqueue ext/VulkanMemoryAllocator/include)
target_include_directories(vuk PUBLIC include)
string(FIND "${CMAKE_CXX_COMPILER}" "clang++" VUK_COMPILER_CLANGPP)
if(VUK_COMPILER_CLANGPP GREATER -1)
set(VUK_COMPILER_CLANGPP ON)
else()
set(VUK_COMPILER_CLANGPP OFF)
endif()
string(FIND "${CMAKE_CXX_COMPILER}" "g++" VUK_COMPILER_GPP)
if(VUK_COMPILER_GPP GREATER -1)
set(VUK_COMPILER_GPP ON)
else()
set(VUK_COMPILER_GPP OFF)
endif()
string(FIND "${CMAKE_CXX_COMPILER}" "clang-cl" VUK_COMPILER_CLANGCL)
if(VUK_COMPILER_CLANGCL GREATER -1)
set(VUK_COMPILER_CLANGCL ON)
else()
set(VUK_COMPILER_CLANGCL OFF)
endif()
if(VUK_COMPILER_CLANGPP OR VUK_COMPILER_GPP)
target_compile_options(vuk PRIVATE -std=c++20 -fno-char8_t)
elseif(MSVC)
target_compile_options(vuk PRIVATE /std:c++20 /permissive- /Zc:char8_t-)
endif()
if(VUK_COMPILER_CLANGPP OR VUK_COMPILER_CLANGCL)
target_compile_options(vuk PRIVATE -Wno-nullability-completeness)
endif()
target_link_libraries(vuk PRIVATE spirv-cross-core robin_hood fmt::fmt)
if(VUK_LINK_TO_LOADER)
if (VUK_USE_VULKAN_SDK)
target_include_directories(vuk PUBLIC ${Vulkan_INCLUDE_DIRS})
target_link_libraries(vuk PRIVATE ${Vulkan_LIBRARIES})
else()
target_link_libraries(vuk PRIVATE vulkan)
endif()
else()
if (VUK_USE_VULKAN_SDK)
target_include_directories(vuk PUBLIC ${Vulkan_INCLUDE_DIRS})
endif()
endif()
if (WIN32)
target_compile_definitions(vuk PUBLIC NOMINMAX VC_EXTRALEAN WIN32_LEAN_AND_MEAN _CRT_SECURE_NO_WARNINGS _SCL_SECURE_NO_WARNINGS _SILENCE_CLANG_CONCEPTS_MESSAGE _SILENCE_CXX23_ALIGNED_STORAGE_DEPRECATION_WARNING)
endif()
if(VUK_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
if(VUK_BUILD_BENCHMARKS)
add_subdirectory(benchmarks)
endif()
if(VUK_BUILD_DOCS)
add_subdirectory(docs)
endif()
if(VUK_BUILD_TESTS)
add_subdirectory(ext/doctest)
target_link_libraries(vuk PUBLIC doctest::doctest)
target_sources(vuk PRIVATE src/tests/Test.cpp)
FetchContent_Declare(
vk-bootstrap
GIT_REPOSITORY https://github.com/charles-lunarg/vk-bootstrap
GIT_TAG cf8df11a0a071463009031cb474099dacffe90ed
)
FetchContent_MakeAvailable(vk-bootstrap)
include(doctest_force_link_static_lib_in_target) # until we can use cmake 3.24
add_executable(vuk-tests src/tests/Test.cpp src/tests/buffer_ops.cpp src/tests/frame_allocator.cpp src/tests/rg_errors.cpp)
#target_compile_features(vuk-tests PRIVATE cxx_std_17)
target_link_libraries(vuk-tests PRIVATE vuk doctest::doctest vk-bootstrap)
target_compile_definitions(vuk-tests PRIVATE VUK_TEST_RUNNER)
doctest_force_link_static_lib_in_target(vuk-tests vuk)
if(VUK_COMPILER_CLANGPP OR VUK_COMPILER_GPP)
target_compile_options(vuk-tests PRIVATE -std=c++20 -fno-char8_t)
elseif(MSVC)
target_compile_options(vuk-tests PRIVATE /std:c++latest /permissive- /Zc:char8_t-)
endif()
if(VUK_COMPILER_CLANGPP OR VUK_COMPILER_CLANGCL)
target_compile_options(vuk-tests PRIVATE -Wno-nullability-completeness)
endif()
else()
target_compile_definitions(vuk PRIVATE DOCTEST_CONFIG_DISABLE)
endif()
<file_sep>#include "TestContext.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/Partials.hpp"
#include <doctest/doctest.h>
using namespace vuk;
TEST_CASE("test text_context preparation") {
REQUIRE(test_context.prepare());
}
constexpr bool operator==(const std::span<uint32_t>& lhs, const std::span<uint32_t>& rhs) {
return std::equal(begin(lhs), end(lhs), begin(rhs), end(rhs));
}
constexpr bool operator==(const std::span<uint32_t>& lhs, const std::span<const uint32_t>& rhs) {
return std::equal(begin(lhs), end(lhs), begin(rhs), end(rhs));
}
constexpr bool operator==(const std::span<const uint32_t>& lhs, const std::span<const uint32_t>& rhs) {
return std::equal(begin(lhs), end(lhs), begin(rhs), end(rhs));
}
TEST_CASE("test buffer harness") {
REQUIRE(test_context.prepare());
auto data = { 1u, 2u, 3u };
auto [buf, fut] = create_buffer(*test_context.allocator, MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnTransfer, std::span(data));
auto res = fut.get<Buffer>(*test_context.allocator, test_context.compiler);
CHECK(std::span((uint32_t*)res->mapped_ptr, 3) == std::span(data));
}
TEST_CASE("test buffer upload/download") {
REQUIRE(test_context.prepare());
{
auto data = { 1u, 2u, 3u };
auto [buf, fut] = create_buffer(*test_context.allocator, MemoryUsage::eGPUonly, DomainFlagBits::eAny, std::span(data));
auto res = download_buffer(fut).get<Buffer>(*test_context.allocator, test_context.compiler);
CHECK(std::span((uint32_t*)res->mapped_ptr, 3) == std::span(data));
}
{
auto data = { 1u, 2u, 3u, 4u, 5u };
auto [buf, fut] = create_buffer(*test_context.allocator, MemoryUsage::eGPUonly, DomainFlagBits::eAny, std::span(data));
auto res = download_buffer(fut).get<Buffer>(*test_context.allocator, test_context.compiler);
CHECK(std::span((uint32_t*)res->mapped_ptr, 5) == std::span(data));
}
}<file_sep>#pragma once
#include <exception>
#include <string>
#include <cassert>
#include "vuk/Config.hpp"
namespace vuk {
struct Exception : std::exception {
std::string error_message;
Exception() {}
Exception(std::string message) : error_message(std::move(message)) {}
const char* what() const noexcept override {
return error_message.c_str();
}
virtual void throw_this() = 0;
};
struct ShaderCompilationException : Exception {
using Exception::Exception;
void throw_this() override {
throw *this;
}
};
struct RenderGraphException : Exception {
using Exception::Exception;
void throw_this() override {
throw *this;
}
};
struct VkException : Exception {
VkResult error_code;
using Exception::Exception;
VkException(VkResult res) {
error_code = res;
switch (res) {
case VK_ERROR_OUT_OF_HOST_MEMORY: {
error_message = "Out of host memory.";
break;
}
case VK_ERROR_OUT_OF_DEVICE_MEMORY: {
error_message = "Out of device memory.";
break;
}
case VK_ERROR_INITIALIZATION_FAILED: {
error_message = "Initialization failed.";
break;
}
case VK_ERROR_DEVICE_LOST: {
error_message = "Device lost.";
break;
}
case VK_ERROR_MEMORY_MAP_FAILED: {
error_message = "Memory map failed.";
break;
}
case VK_ERROR_LAYER_NOT_PRESENT: {
error_message = "Layer not present.";
break;
}
case VK_ERROR_EXTENSION_NOT_PRESENT: {
error_message = "Extension not present.";
break;
}
case VK_ERROR_FEATURE_NOT_PRESENT: {
error_message = "Feature not present.";
break;
}
case VK_ERROR_INCOMPATIBLE_DRIVER: {
error_message = "Incompatible driver.";
break;
}
case VK_ERROR_TOO_MANY_OBJECTS: {
error_message = "Too many objects.";
break;
}
case VK_ERROR_FORMAT_NOT_SUPPORTED: {
error_message = "Format not supported.";
break;
}
case VK_ERROR_UNKNOWN: {
error_message = "Error unknown.";
break;
}
case VK_SUBOPTIMAL_KHR: {
error_message = "Suboptimal.";
break;
}
case VK_ERROR_OUT_OF_DATE_KHR: {
error_message = "Out of date.";
break;
}
default:
assert(0 && "Unimplemented error.");
break;
}
}
VkResult code() const { return error_code; }
void throw_this() override {
throw *this;
}
};
struct AllocateException : VkException {
AllocateException(VkResult res) {
error_code = res;
switch (res) {
case VK_ERROR_OUT_OF_HOST_MEMORY: {
error_message = "Out of host memory.";
break;
}
case VK_ERROR_OUT_OF_DEVICE_MEMORY: {
error_message = "Out of device memory.";
break;
}
case VK_ERROR_INITIALIZATION_FAILED: {
error_message = "Initialization failed.";
break;
}
case VK_ERROR_DEVICE_LOST: {
error_message = "Device lost.";
break;
}
case VK_ERROR_MEMORY_MAP_FAILED: {
error_message = "Memory map failed.";
break;
}
case VK_ERROR_LAYER_NOT_PRESENT: {
error_message = "Layer not present.";
break;
}
case VK_ERROR_EXTENSION_NOT_PRESENT: {
error_message = "Extension not present.";
break;
}
case VK_ERROR_FEATURE_NOT_PRESENT: {
error_message = "Feature not present.";
break;
}
case VK_ERROR_INCOMPATIBLE_DRIVER: {
error_message = "Incompatible driver.";
break;
}
case VK_ERROR_TOO_MANY_OBJECTS: {
error_message = "Too many objects.";
break;
}
case VK_ERROR_FORMAT_NOT_SUPPORTED: {
error_message = "Format not supported.";
break;
}
default:
assert(0 && "Unimplemented error.");
break;
}
}
void throw_this() override {
throw *this;
}
};
} // namespace vuk
<file_sep>#pragma once
#include "vuk/Config.hpp"
#include "vuk/Image.hpp"
#include "vuk/Result.hpp"
#include "vuk/SourceLocation.hpp"
#include "vuk/vuk_fwd.hpp"
#include <span>
namespace vuk {
#define VUK_DO_OR_RETURN(what) \
if (auto res = what; !res) { \
return std::move(res); \
}
/// @endcond
struct TimelineSemaphore {
VkSemaphore semaphore;
uint64_t* value;
bool operator==(const TimelineSemaphore& other) const noexcept {
return semaphore == other.semaphore;
}
};
/// @brief DeviceResource is a polymorphic interface over allocation of GPU resources.
/// A DeviceResource must prevent reuse of cross-device resources after deallocation until CPU-GPU timelines are synchronized. GPU-only resources may be
/// reused immediately.
struct DeviceResource {
// missing here: Events (gpu only)
// gpu only
virtual Result<void, AllocateException> allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) = 0;
virtual void deallocate_semaphores(std::span<const VkSemaphore> src) = 0;
virtual Result<void, AllocateException> allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) = 0;
virtual void deallocate_fences(std::span<const VkFence> dst) = 0;
virtual Result<void, AllocateException>
allocate_command_buffers(std::span<CommandBufferAllocation> dst, std::span<const CommandBufferAllocationCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_command_buffers(std::span<const CommandBufferAllocation> dst) = 0;
virtual Result<void, AllocateException>
allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_command_pools(std::span<const CommandPool> dst) = 0;
virtual Result<void, AllocateException> allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_buffers(std::span<const Buffer> dst) = 0;
virtual Result<void, AllocateException>
allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_framebuffers(std::span<const VkFramebuffer> dst) = 0;
// gpu only
virtual Result<void, AllocateException> allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_images(std::span<const Image> dst) = 0;
virtual Result<void, AllocateException>
allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_image_views(std::span<const ImageView> src) = 0;
virtual Result<void, AllocateException> allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) = 0;
virtual void deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) = 0;
virtual Result<void, AllocateException>
allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) = 0;
virtual Result<void, AllocateException>
allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const struct DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_descriptor_sets(std::span<const DescriptorSet> src) = 0;
virtual Result<void, AllocateException>
allocate_descriptor_pools(std::span<VkDescriptorPool> dst, std::span<const VkDescriptorPoolCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_descriptor_pools(std::span<const VkDescriptorPool> src) = 0;
virtual Result<void, AllocateException>
allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst, std::span<const VkQueryPoolCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) = 0;
virtual Result<void, AllocateException>
allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_timestamp_queries(std::span<const TimestampQuery> src) = 0;
virtual Result<void, AllocateException> allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) = 0;
virtual void deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) = 0;
virtual Result<void, AllocateException> allocate_acceleration_structures(std::span<VkAccelerationStructureKHR> dst,
std::span<const VkAccelerationStructureCreateInfoKHR> cis,
SourceLocationAtFrame loc) = 0;
virtual void deallocate_acceleration_structures(std::span<const VkAccelerationStructureKHR> src) = 0;
virtual void deallocate_swapchains(std::span<const VkSwapchainKHR> src) = 0;
virtual Result<void, AllocateException>
allocate_graphics_pipelines(std::span<GraphicsPipelineInfo> dst, std::span<const GraphicsPipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_graphics_pipelines(std::span<const GraphicsPipelineInfo> src) = 0;
virtual Result<void, AllocateException>
allocate_compute_pipelines(std::span<ComputePipelineInfo> dst, std::span<const ComputePipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_compute_pipelines(std::span<const ComputePipelineInfo> src) = 0;
virtual Result<void, AllocateException> allocate_ray_tracing_pipelines(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) = 0;
virtual void deallocate_ray_tracing_pipelines(std::span<const RayTracingPipelineInfo> src) = 0;
virtual Result<void, AllocateException>
allocate_render_passes(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc) = 0;
virtual void deallocate_render_passes(std::span<const VkRenderPass> src) = 0;
virtual Context& get_context() = 0;
};
struct DeviceVkResource;
/// @brief Interface for allocating device resources
///
/// The Allocator is a concrete value type wrapping over a polymorphic DeviceResource, forwarding allocations and deallocations to it.
/// The allocation functions take spans of creation parameters and output values, reporting error through the return value of Result<void, AllocateException>.
/// The deallocation functions can't fail.
class Allocator {
public:
/// @brief Create new Allocator that wraps a DeviceResource
/// @param device_resource The DeviceResource to allocate from
explicit Allocator(DeviceResource& device_resource) : ctx(&device_resource.get_context()), device_resource(&device_resource) {}
/// @brief Allocate semaphores from this Allocator
/// @param dst Destination span to place allocated semaphores into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate(std::span<VkSemaphore> dst, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate semaphores from this Allocator
/// @param dst Destination span to place allocated semaphores into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate semaphores previously allocated from this Allocator
/// @param src Span of semaphores to be deallocated
void deallocate(std::span<const VkSemaphore> src);
/// @brief Allocate fences from this Allocator
/// @param dst Destination span to place allocated fences into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate(std::span<VkFence> dst, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate fences from this Allocator
/// @param dst Destination span to place allocated fences into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate fences previously allocated from this Allocator
/// @param src Span of fences to be deallocated
void deallocate(std::span<const VkFence> src);
/// @brief Allocate command pools from this Allocator
/// @param dst Destination span to place allocated command pools into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate command pools from this Allocator
/// @param dst Destination span to place allocated command pools into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate command pools previously allocated from this Allocator
/// @param src Span of command pools to be deallocated
void deallocate(std::span<const CommandPool> src);
/// @brief Allocate command buffers from this Allocator
/// @param dst Destination span to place allocated command buffers into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<CommandBufferAllocation> dst, std::span<const CommandBufferAllocationCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate command buffers from this Allocator
/// @param dst Destination span to place allocated command buffers into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate command buffers previously allocated from this Allocator
/// @param src Span of command buffers to be deallocated
void deallocate(std::span<const CommandBufferAllocation> src);
/// @brief Allocate buffers from this Allocator
/// @param dst Destination span to place allocated buffers into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate buffers from this Allocator
/// @param dst Destination span to place allocated buffers into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate buffers previously allocated from this Allocator
/// @param src Span of buffers to be deallocated
void deallocate(std::span<const Buffer> src);
/// @brief Allocate framebuffers from this Allocator
/// @param dst Destination span to place allocated framebuffers into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate framebuffers from this Allocator
/// @param dst Destination span to place allocated framebuffers into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate framebuffers previously allocated from this Allocator
/// @param src Span of framebuffers to be deallocated
void deallocate(std::span<const VkFramebuffer> src);
/// @brief Allocate images from this Allocator
/// @param dst Destination span to place allocated images into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate images from this Allocator
/// @param dst Destination span to place allocated images into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate images previously allocated from this Allocator
/// @param src Span of images to be deallocated
void deallocate(std::span<const Image> src);
/// @brief Allocate image views from this Allocator
/// @param dst Destination span to place allocated image views into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate image views from this Allocator
/// @param dst Destination span to place allocated image views into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate image views previously allocated from this Allocator
/// @param src Span of image views to be deallocated
void deallocate(std::span<const ImageView> src);
/// @brief Allocate persistent descriptor sets from this Allocator
/// @param dst Destination span to place allocated persistent descriptor sets into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<PersistentDescriptorSet> dst, std::span<const PersistentDescriptorSetCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate persistent descriptor sets from this Allocator
/// @param dst Destination span to place allocated persistent descriptor sets into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate persistent descriptor sets previously allocated from this Allocator
/// @param src Span of persistent descriptor sets to be deallocated
void deallocate(std::span<const PersistentDescriptorSet> src);
/// @brief Allocate descriptor sets from this Allocator
/// @param dst Destination span to place allocated descriptor sets into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate descriptor sets from this Allocator
/// @param dst Destination span to place allocated descriptor sets into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate descriptor sets from this Allocator
/// @param dst Destination span to place allocated descriptor sets into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate descriptor sets from this Allocator
/// @param dst Destination span to place allocated descriptor sets into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate descriptor sets previously allocated from this Allocator
/// @param src Span of descriptor sets to be deallocated
void deallocate(std::span<const DescriptorSet> src);
/// @brief Allocate timestamp query pools from this Allocator
/// @param dst Destination span to place allocated timestamp query pools into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<TimestampQueryPool> dst, std::span<const VkQueryPoolCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate timestamp query pools from this Allocator
/// @param dst Destination span to place allocated timestamp query pools into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst,
std::span<const VkQueryPoolCreateInfo> cis,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate timestamp query pools previously allocated from this Allocator
/// @param src Span of timestamp query pools to be deallocated
void deallocate(std::span<const TimestampQueryPool> src);
/// @brief Allocate timestamp queries from this Allocator
/// @param dst Destination span to place allocated timestamp queries into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate timestamp queries from this Allocator
/// @param dst Destination span to place allocated timestamp queries into
/// @param cis Per-element construction info
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate timestamp queries previously allocated from this Allocator
/// @param src Span of timestamp queries to be deallocated
void deallocate(std::span<const TimestampQuery> src);
/// @brief Allocate timeline semaphores from this Allocator
/// @param dst Destination span to place allocated timeline semaphores into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate timeline semaphores from this Allocator
/// @param dst Destination span to place allocated timeline semaphores into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate timeline semaphores previously allocated from this Allocator
/// @param src Span of timeline semaphores to be deallocated
void deallocate(std::span<const TimelineSemaphore> src);
/// @brief Allocate acceleration structures from this Allocator
/// @param dst Destination span to place allocated acceleration structures into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate(std::span<VkAccelerationStructureKHR> dst,
std::span<const VkAccelerationStructureCreateInfoKHR> cis,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate acceleration structures from this Allocator
/// @param dst Destination span to place allocated acceleration structures into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_acceleration_structures(std::span<VkAccelerationStructureKHR> dst,
std::span<const VkAccelerationStructureCreateInfoKHR> cis,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate acceleration structures previously allocated from this Allocator
/// @param src Span of acceleration structures to be deallocated
void deallocate(std::span<const VkAccelerationStructureKHR> src);
/// @brief Deallocate swapchains previously allocated from this Allocator
/// @param src Span of swapchains to be deallocated
void deallocate(std::span<const VkSwapchainKHR> src);
/// @brief Allocate graphics pipelines from this Allocator
/// @param dst Destination span to place allocated pipelines into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<GraphicsPipelineInfo> dst, std::span<const GraphicsPipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate graphics pipelines from this Allocator
/// @param dst Destination span to place allocated pipelines into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_graphics_pipelines(std::span<GraphicsPipelineInfo> dst,
std::span<const GraphicsPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate pipelines previously allocated from this Allocator
/// @param src Span of pipelines to be deallocated
void deallocate(std::span<const GraphicsPipelineInfo> src);
/// @brief Allocate compute pipelines from this Allocator
/// @param dst Destination span to place allocated pipelines into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<ComputePipelineInfo> dst, std::span<const ComputePipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate compute pipelines from this Allocator
/// @param dst Destination span to place allocated pipelines into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_compute_pipelines(std::span<ComputePipelineInfo> dst,
std::span<const ComputePipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate pipelines previously allocated from this Allocator
/// @param src Span of pipelines to be deallocated
void deallocate(std::span<const ComputePipelineInfo> src);
/// @brief Allocate ray tracing pipelines from this Allocator
/// @param dst Destination span to place allocated pipelines into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<RayTracingPipelineInfo> dst, std::span<const RayTracingPipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate ray tracing pipelines from this Allocator
/// @param dst Destination span to place allocated pipelines into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException> allocate_ray_tracing_pipelines(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate pipelines previously allocated from this Allocator
/// @param src Span of pipelines to be deallocated
void deallocate(std::span<const RayTracingPipelineInfo> src);
/// @brief Allocate render passes from this Allocator
/// @param dst Destination span to place allocated render passes into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Allocate render passes from this Allocator
/// @param dst Destination span to place allocated render passes into
/// @param loc Source location information
/// @return Result<void, AllocateException> : void or AllocateException if the allocation could not be performed.
Result<void, AllocateException>
allocate_render_passes(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc = VUK_HERE_AND_NOW());
/// @brief Deallocate render passes previously allocated from this Allocator
/// @param src Span of render passes to be deallocated
void deallocate(std::span<const VkRenderPass> src);
/// @brief Get the underlying DeviceResource
/// @return the underlying DeviceResource
DeviceResource& get_device_resource() {
return *device_resource;
}
/// @brief Get the parent Context
/// @return the parent Context
Context& get_context() {
return *ctx;
}
private:
Context* ctx;
DeviceResource* device_resource;
};
template<class ContainerType>
concept Container = requires(ContainerType a) {
std::begin(a);
std::end(a);
};
/// @brief Customization point for deallocation of user types
/// @tparam T
/// @param allocator
/// @param src
template<class T, size_t N>
void deallocate(Allocator& allocator, T (&src)[N]) {
allocator.deallocate(std::span<const T>{ src, N });
}
/// @brief Customization point for deallocation of user types
/// @tparam T
/// @param allocator
/// @param src
template<class T>
void deallocate(Allocator& allocator, const T& src)
requires(!Container<T>)
{
allocator.deallocate(std::span<const T>{ &src, 1 });
}
/// @brief Customization point for deallocation of user types
/// @tparam T
/// @param allocator
/// @param src
template<class T>
void deallocate(Allocator& allocator, const T& src)
requires(Container<T>)
{
allocator.deallocate(std::span(src));
}
template<typename Type>
Unique<Type>::~Unique() noexcept {
if (allocator && payload != Type{}) {
deallocate(*allocator, payload);
}
}
template<typename Type>
void Unique<Type>::reset(Type value) noexcept {
if (payload != value) {
if (allocator && payload != Type{}) {
deallocate(*allocator, std::move(payload));
}
payload = std::move(value);
}
}
} // namespace vuk<file_sep>#include "vuk/Pipeline.hpp"
#include "vuk/PipelineInstance.hpp"
#include "vuk/Program.hpp"
#include <robin_hood.h>
namespace vuk {
fixed_vector<DescriptorSetLayoutCreateInfo, VUK_MAX_SETS> PipelineBaseCreateInfo::build_descriptor_layouts(const Program& program,
const PipelineBaseCreateInfoBase& bci) {
fixed_vector<DescriptorSetLayoutCreateInfo, VUK_MAX_SETS> dslcis;
for (const auto& [index, set] : program.sets) {
// fill up unused sets, if there are holes in descriptor set order
dslcis.resize(std::max(dslcis.size(), index + 1), {});
DescriptorSetLayoutCreateInfo dslci;
dslci.index = index;
auto& bindings = dslci.bindings;
for (auto& ub : set.uniform_buffers) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = ub.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eUniformBuffer;
layoutBinding.descriptorCount = 1;
layoutBinding.stageFlags = ub.stage;
layoutBinding.pImmutableSamplers = nullptr;
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
}
}
for (auto& sb : set.storage_buffers) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = sb.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eStorageBuffer;
layoutBinding.descriptorCount = 1;
layoutBinding.stageFlags = sb.stage;
layoutBinding.pImmutableSamplers = nullptr;
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
dslci.optional.set(layoutBinding.binding, sb.is_hlsl_counter_buffer);
}
}
for (auto& tb : set.texel_buffers) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = tb.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eUniformTexelBuffer;
layoutBinding.descriptorCount = 1;
layoutBinding.stageFlags = tb.stage;
layoutBinding.pImmutableSamplers = nullptr;
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
}
}
for (auto& si : set.combined_image_samplers) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = si.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eCombinedImageSampler;
layoutBinding.descriptorCount = si.array_size == (unsigned)-1 ? 1 : si.array_size;
layoutBinding.stageFlags = si.stage;
layoutBinding.pImmutableSamplers = nullptr;
if (si.array_size == 0) {
layoutBinding.descriptorCount = bci.variable_count_max[index];
}
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
}
}
for (auto& si : set.samplers) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = si.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eSampler;
layoutBinding.descriptorCount = si.array_size == (unsigned)-1 ? 1 : si.array_size;
layoutBinding.stageFlags = si.stage;
layoutBinding.pImmutableSamplers = nullptr;
if (si.array_size == 0) {
layoutBinding.descriptorCount = bci.variable_count_max[index];
}
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
}
}
for (auto& si : set.sampled_images) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = si.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eSampledImage;
layoutBinding.descriptorCount = si.array_size == (unsigned)-1 ? 1 : si.array_size;
layoutBinding.stageFlags = si.stage;
layoutBinding.pImmutableSamplers = nullptr;
if (si.array_size == 0) {
layoutBinding.descriptorCount = bci.variable_count_max[index];
}
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
}
}
for (auto& si : set.storage_images) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = si.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eStorageImage;
layoutBinding.descriptorCount = si.array_size == (unsigned)-1 ? 1 : si.array_size;
layoutBinding.stageFlags = si.stage;
layoutBinding.pImmutableSamplers = nullptr;
if (si.array_size == 0) {
layoutBinding.descriptorCount = bci.variable_count_max[index];
}
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
}
}
for (auto& si : set.subpass_inputs) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = si.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eInputAttachment;
layoutBinding.descriptorCount = 1;
layoutBinding.stageFlags = si.stage;
layoutBinding.pImmutableSamplers = nullptr;
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
}
}
for (auto& si : set.acceleration_structures) {
VkDescriptorSetLayoutBinding layoutBinding;
layoutBinding.binding = si.binding;
layoutBinding.descriptorType = (VkDescriptorType)DescriptorType::eAccelerationStructureKHR;
layoutBinding.descriptorCount = si.array_size == (unsigned)-1 ? 1 : si.array_size;
layoutBinding.stageFlags = si.stage;
layoutBinding.pImmutableSamplers = nullptr;
if (si.array_size == 0) {
layoutBinding.descriptorCount = bci.variable_count_max[index];
}
bindings.push_back(layoutBinding);
if (layoutBinding.binding < VUK_MAX_BINDINGS) {
dslci.used_bindings.set(layoutBinding.binding, true);
}
}
// extract flags from the packed bitset
auto set_word_offset = index * VUK_MAX_BINDINGS * 4 / (sizeof(unsigned long long) * 8);
for (unsigned i = 0; i <= set.highest_descriptor_binding; i++) {
auto word = bci.binding_flags.words[set_word_offset + i * 4 / (sizeof(unsigned long long) * 8)];
if (word & ((0b1111) << i)) {
VkDescriptorBindingFlags f((word >> i) & 0b1111);
dslci.flags.resize(i + 1);
dslci.flags[i] = f;
}
}
dslcis[index] = std::move(dslci);
}
return dslcis;
}
} // namespace vuk
namespace std {
size_t hash<vuk::GraphicsPipelineInstanceCreateInfo>::operator()(vuk::GraphicsPipelineInstanceCreateInfo const& x) const noexcept {
size_t h = 0;
auto ext_hash = x.is_inline() ? robin_hood::hash_bytes(x.inline_data, x.extended_size) : robin_hood::hash_bytes(x.extended_data, x.extended_size);
hash_combine(h, x.base, reinterpret_cast<uint64_t>((VkRenderPass)x.render_pass), x.extended_size, ext_hash);
return h;
}
size_t hash<VkSpecializationMapEntry>::operator()(VkSpecializationMapEntry const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.constantID, x.offset, x.size);
return h;
}
size_t hash<vuk::ComputePipelineInstanceCreateInfo>::operator()(vuk::ComputePipelineInstanceCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.base, robin_hood::hash_bytes(x.specialization_constant_data.data(), x.specialization_info.dataSize), x.specialization_map_entries);
return h;
}
size_t hash<vuk::RayTracingPipelineInstanceCreateInfo>::operator()(vuk::RayTracingPipelineInstanceCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.base, robin_hood::hash_bytes(x.specialization_constant_data.data(), x.specialization_info.dataSize), x.specialization_map_entries);
return h;
}
size_t hash<VkPushConstantRange>::operator()(VkPushConstantRange const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.offset, x.size, (VkShaderStageFlags)x.stageFlags);
return h;
}
size_t hash<vuk::PipelineLayoutCreateInfo>::operator()(vuk::PipelineLayoutCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.pcrs, x.dslcis);
return h;
}
size_t hash<vuk::ShaderSource>::operator()(vuk::ShaderSource const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.language, robin_hood::hash_bytes(x.data_ptr, x.size));
return h;
}
}; // namespace std
<file_sep>#pragma once
#include <utility>
template<typename E>
inline constexpr auto to_integral(E e) -> typename std::underlying_type<E>::type {
return static_cast<typename std::underlying_type<E>::type>(e);
}<file_sep>#include "example_runner.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
/* 02_cube
* In this example we will draw a cube, still with a single attachment, but using vertex, index and uniform buffers.
* The cube will spin around its Y axis, which we will achieve by changing the model matrix each frame.
* This examples showcases using scratch allocations, which only live for one frame.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
// The Y rotation angle of our cube
float angle = 0.f;
// Generate vertices and indices for the cube
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
vuk::Example x{
.name = "02_cube",
// Same setup as previously
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/ubo_test.vert").generic_string()), (root / "examples/ubo_test.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle_depthshaded.frag").generic_string()),
(root / "examples/triangle_depthshaded.frag").generic_string());
pci.define("SCALE", "0.75");
allocator.get_context().create_named_pipeline("cube", pci);
// Request a GPU-only buffer allocation with specific data
// The buffer is allocated in device-local, non-host visible memory
// And enqueues a transfer operation on the graphics queue, which will copy the given data
// Finally it returns a vuk::Buffer, which holds the info for the allocation and a Future that represents the upload being completed
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
// For the example, we just ask these that these uploads complete before moving on to rendering
// In an engine, you would integrate these uploads into some explicit system
runner.enqueue_setup(std::move(vert_fut));
runner.enqueue_setup(std::move(ind_fut));
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
// This struct will represent the view-projection transform used for the cube
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
// Fill the view matrix, looking a bit from top to the center
vp.view = glm::lookAt(glm::vec3(0, 1.5, 3.5), glm::vec3(0), glm::vec3(0, 1, 0));
// Fill the projection matrix, standard perspective matrix
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 1.f, 10.f);
vp.proj[1][1] *= -1;
// Allocate and transfer view-projection transform
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
// since this memory is CPU visible (MemoryUsage::eCPUtoGPU), we don't need to wait for the future to complete
auto uboVP = *buboVP;
vuk::RenderGraph rg("02");
rg.attach_in("02_cube", std::move(target));
rg.add_pass(
{ // For this example, only a color image is needed to write to (our framebuffer)
// The name is declared, and the way it will be used in the pass (color attachment - write)
.resources = { "02_cube"_image >> vuk::eColorWrite >> "02_cube_final" },
.execute = [uboVP](vuk::CommandBuffer& command_buffer) {
command_buffer
// In vuk, all pipeline state (with the exception of the shaders) come from the command buffer
// Such state can be requested to be dynamic - dynamic state does not form part of the pipeline key, and hence cheap to change
// On desktop, dynamic scissor and viewport is of no extra cost, and worthwhile to set always
.set_dynamic_state(vuk::DynamicStateFlagBits::eScissor | vuk::DynamicStateFlagBits::eViewport)
.set_viewport(0, vuk::Rect2D::framebuffer()) // Set the viewport to cover the entire framebuffer
.set_scissor(0, vuk::Rect2D::framebuffer()) // Set the scissor area to cover the entire framebuffer
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
// The vertex format and the buffer used are bound together for this call
// The format is specified here as vuk::Packed{}, meaning we are going to make a consecutive binding
// For each element in the list, a vuk::Format signifies a binding
// And a vuk::Ignore signifies a number of bytes to be skipped
// In this case, we will bind vuk::Format::eR32G32B32Sfloat to the first location (0)
// And use the remaining vuk::Ignore-d bytes to establish the stride of the buffer
.bind_vertex_buffer(
0, *verts, 0, vuk::Packed{ vuk::Format::eR32G32B32Sfloat, vuk::Ignore{ sizeof(util::Vertex) - sizeof(util::Vertex::position) } })
// Bind the index buffer
.bind_index_buffer(*inds, vuk::IndexType::eUint32)
.bind_graphics_pipeline("cube")
// Bind the uniform buffer we allocated to (set = 0, binding = 0)
.bind_buffer(0, 0, uboVP)
.bind_buffer(0, 1, uboVP); // It is allowed to bind to slots that are not consumed by the current pipeline
// For the model matrix, we will take a shorter route
// Frequently updated uniform buffers should be in CPUtoGPU type memory, which is mapped
// So we create a typed mapping directly and write the model matrix
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = static_cast<glm::mat4>(glm::angleAxis(glm::radians(angle), glm::vec3(0.f, 1.f, 0.f)));
// We can also customize pipelines by using specialization constants
// Here we will apply a tint based on the current frame
auto current_frame = command_buffer.get_context().get_frame_count();
auto mod_frame = current_frame % 1000;
glm::vec3 tint{ 1.f, 1.f, 1.f };
if (mod_frame <= 500 && mod_frame > 250) {
tint = { 1.f, 0.5f, 0.5f };
} else if (mod_frame <= 750 && mod_frame > 500) {
tint = { 0.5f, 1.0f, 0.5f };
} else if (mod_frame > 750) {
tint = { 0.5f, 0.5f, 1.0f };
}
// Specialization constants can only be scalars, use three to make a vec3
command_buffer.specialize_constants(0, tint.x).specialize_constants(1, tint.y).specialize_constants(2, tint.z);
// The cube is drawn via indexed drawing
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
} });
// The angle is update to rotate the cube
angle += 20.f * ImGui::GetIO().DeltaTime;
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "02_cube_final" };
},
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
verts.reset();
inds.reset();
}
};
REGISTER_EXAMPLE(x);
} // namespace<file_sep>#include "example_runner.hpp"
#include <algorithm>
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
#include <numeric>
#include <random>
#include <stb_image.h>
/* 08_pipelined_compute
* In this example we will see how to run compute shaders on the graphics queue.
* To showcases this, we will render a texture to a fullscreen framebuffer,
* then display it, but scramble the pixels determined by indices in a storage buffer.
* Between these two steps, we perform some iterations of bubble sort on the indices buffer in compute.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
float time = 0.f;
auto box = util::generate_cube();
int x, y;
uint32_t speed_count = 1;
std::optional<vuk::Texture> texture_of_doge;
vuk::Unique<vuk::Buffer> scramble_buf;
std::random_device rd;
std::mt19937 g(rd());
vuk::Future scramble_buf_fut;
vuk::Future texture_of_doge_fut;
vuk::Example xample{
.name = "08_pipelined_compute",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/fullscreen.vert").generic_string()), (root / "examples/fullscreen.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/rtt.frag").generic_string()), (root / "examples/rtt.frag").generic_string());
runner.context->create_named_pipeline("rtt", pci);
}
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/fullscreen.vert").generic_string()), (root / "examples/fullscreen.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/scrambled_draw.frag").generic_string()), (root / "examples/scrambled_draw.frag").generic_string());
runner.context->create_named_pipeline("scrambled_draw", pci);
}
// creating a compute pipeline is the same as creating a graphics pipeline
{
vuk::PipelineBaseCreateInfo pbci;
pbci.add_glsl(util::read_entire_file((root / "examples/stupidsort.comp").generic_string()), "examples/stupidsort.comp");
runner.context->create_named_pipeline("stupidsort", pbci);
}
int chans;
auto doge_image = stbi_load((root / "examples/doge.png").generic_string().c_str(), &x, &y, &chans, 4);
auto [tex, tex_fut] = create_texture(allocator, vuk::Format::eR8G8B8A8Srgb, vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u }, doge_image, true);
texture_of_doge = std::move(tex);
runner.enqueue_setup(std::move(tex_fut));
// init scrambling buffer
std::vector<unsigned> indices(x * y);
std::iota(indices.begin(), indices.end(), 0);
std::shuffle(indices.begin(), indices.end(), g);
scramble_buf = *allocate_buffer(allocator, { vuk::MemoryUsage::eGPUonly, sizeof(unsigned) * x * y, 1 });
// make a GPU future
scramble_buf_fut = vuk::host_data_to_buffer(allocator, vuk::DomainFlagBits::eTransferOnTransfer, scramble_buf.get(), std::span(indices));
stbi_image_free(doge_image);
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
std::shared_ptr<vuk::RenderGraph> rgx = std::make_shared<vuk::RenderGraph>("RTT");
rgx->attach_and_clear_image(
"08_rttf",
{ .extent = vuk::Dimension3D::absolute((unsigned)x, (unsigned)y), .format = runner.swapchain->format, .sample_count = vuk::Samples::e1 },
vuk::ClearColor{ 0.f, 0.f, 0.f, 1.f });
// standard render to texture
rgx->add_pass({ .name = "rtt",
.execute_on = vuk::DomainFlagBits::eGraphicsQueue,
.resources = { "08_rttf"_image >> vuk::eColorWrite },
.execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
.bind_image(0, 0, *texture_of_doge->view)
.bind_sampler(0, 0, {})
.bind_graphics_pipeline("rtt")
.draw(3, 1, 0, 0);
} });
// make a gpu future of the above graph (render to texture) and bind to an output (rttf)
vuk::Future rttf{ rgx, "08_rttf+" };
std::shared_ptr<vuk::RenderGraph> rgp = std::make_shared<vuk::RenderGraph>("08");
rgp->attach_in("08_pipelined_compute", std::move(target));
// this pass executes outside of a renderpass
// we declare a buffer dependency and dispatch a compute shader
rgp->add_pass({ .name = "sort",
.execute_on = vuk::DomainFlagBits::eGraphicsQueue,
.resources = { "08_scramble"_buffer >> vuk::eComputeRW >> "08_scramble+" },
.execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.bind_buffer(0, 0, *command_buffer.get_resource_buffer("08_scramble"));
command_buffer.bind_compute_pipeline("stupidsort").specialize_constants(0, speed_count).dispatch(1);
// We can also customize pipelines by using specialization constants
// Here we will apply a tint based on the current frame
auto current_frame = command_buffer.get_context().get_frame_count();
auto mod_frame = current_frame % 100;
if (mod_frame == 99) {
speed_count += 256;
}
} });
rgp->add_pass({ .name = "copy",
.execute_on = vuk::DomainFlagBits::eTransferQueue,
.resources = { "08_scramble+"_buffer >> vuk::eTransferRead, "08_scramble++"_buffer >> vuk::eTransferWrite >> "08_scramble+++" },
.execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.copy_buffer("08_scramble+", "08_scramble++", sizeof(unsigned) * x * y);
} });
// put it back into the persistent buffer
rgp->add_pass({ .name = "copy_2",
.execute_on = vuk::DomainFlagBits::eTransferQueue,
.resources = { "08_scramble+++"_buffer >> vuk::eTransferRead, "08_scramble++++"_buffer >> vuk::eTransferWrite >> "08_scramble+++++" },
.execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.copy_buffer("08_scramble+++", "08_scramble++++", sizeof(unsigned) * x * y);
} });
// draw the scrambled image, with a buffer dependency on the scramble buffer
rgp->add_pass({ .name = "draw",
.execute_on = vuk::DomainFlagBits::eGraphicsQueue,
.resources = { "08_scramble+++"_buffer >> vuk::eFragmentRead,
"08_rtt"_image >> vuk::eFragmentSampled,
"08_pipelined_compute"_image >> vuk::eColorWrite >> "08_pipelined_compute_final" },
.execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
.bind_image(0, 0, "08_rtt")
.bind_sampler(0, 0, {})
.bind_buffer(0, 1, *command_buffer.get_resource_buffer("08_scramble+++"))
.bind_graphics_pipeline("scrambled_draw")
.draw(3, 1, 0, 0);
} });
time += ImGui::GetIO().DeltaTime;
// make the main rendergraph
// our two inputs are the futures - they compile into the main rendergraph
rgp->attach_in("08_rtt", std::move(rttf));
// the copy here in addition will execute on the transfer queue, and will signal the graphics to execute the rest
// we created this future in the setup code, so on the first frame it will append the computation
// but on the subsequent frames the future becomes ready (on the gpu) and this will only attach a buffer
rgp->attach_in("08_scramble", std::move(scramble_buf_fut));
// temporary buffer used for copying
rgp->attach_buffer(
"08_scramble++", **allocate_buffer(frame_allocator, { vuk::MemoryUsage::eGPUonly, sizeof(unsigned) * x * y, 1 }), vuk::Access::eNone);
// permanent buffer to keep state
rgp->attach_buffer("08_scramble++++", *scramble_buf, vuk::Access::eNone);
scramble_buf_fut = { rgp, "08_scramble+++++" };
return vuk::Future{ rgp, "08_pipelined_compute_final" };
},
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
texture_of_doge.reset();
scramble_buf.reset();
}
};
REGISTER_EXAMPLE(xample);
} // namespace
<file_sep>#include "example_runner.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
/* 03_multipass
* In this example we will build on the previous example (02_cube),
* but we will add in a second resource (a depth buffer). Furthermore we will see how to add multiple passes.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
float angle = 0.f;
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
vuk::Example x{
.name = "03_multipass",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/triangle.vert").generic_string()), (root / "examples/triangle.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle.frag").generic_string()), (root / "examples/triangle.frag").generic_string());
runner.context->create_named_pipeline("triangle", pci);
}
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/ubo_test.vert").generic_string()), (root / "examples/ubo_test.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle_depthshaded.frag").generic_string()),
(root / "examples/triangle_depthshaded.frag").generic_string());
runner.context->create_named_pipeline("cube", pci);
}
// We set up the cube data, same as in example 02_cube
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
// For the example, we just ask these that these uploads complete before moving on to rendering
// In an engine, you would integrate these uploads into some explicit system
runner.enqueue_setup(std::move(vert_fut));
runner.enqueue_setup(std::move(ind_fut));
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
vp.view = glm::lookAt(glm::vec3(0, 1.5, 3.5), glm::vec3(0), glm::vec3(0, 1, 0));
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 1.f, 10.f);
vp.proj[1][1] *= -1;
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
vuk::RenderGraph rg("03");
rg.attach_in("03_multipass", std::move(target));
// Add a pass to draw a triangle (from the first example) into the top left corner
// In this example we want to use this resource after our write, but resource names are consumed by writes
// To be able to refer to this resource with the write completed, we assign it a new name ("03_multipass+")
rg.add_pass({ .name = "pass0",
.resources = { "03_multipass"_image >> vuk::eColorWrite >> "03_multipass+" },
.execute = [&](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::relative(0, 0, 0.2f, 0.2f))
.set_scissor(0, vuk::Rect2D::relative(0, 0, 0.2f, 0.2f))
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
.bind_graphics_pipeline("triangle")
.draw(3, 1, 0, 0);
} });
// Add a pass to draw a triangle (from the first example) into the bottom right corner
// If we don't explicitly say what new name we want to give, vuk will give "<input_name>+"
// So in this case, 03_multipass++
rg.add_pass({ .name = "pass1", .resources = { "03_multipass+"_image >> vuk::eColorWrite }, .execute = [&](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::relative(0.8f, 0.8f, 0.2f, 0.2f))
.set_scissor(0, vuk::Rect2D::relative(0.8f, 0.8f, 0.2f, 0.2f))
.set_rasterization({}) // Set the default rasterization state
.broadcast_color_blend({}) // Set the default color blend state
.bind_graphics_pipeline("triangle")
.draw(3, 1, 0, 0);
} });
// Add a pass to draw a cube (from the second example) in the middle, but with depth buffering
rg.add_pass(
{ // Here a second resource is added: a depth attachment
// The example framework took care of our color image, but this attachment we will need bind later
// Depth attachments are denoted by the use vuk::eDepthStencilRW
.name = "pass2",
.resources = { "03_multipass++"_image >> vuk::eColorWrite >> "03_multipass_final", "03_depth"_image >> vuk::eDepthStencilRW },
.execute = [uboVP](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true, .depthWriteEnable = true, .depthCompareOp = vuk::CompareOp::eLessOrEqual })
.broadcast_color_blend({}) // Set the default color blend state
.bind_index_buffer(*inds, vuk::IndexType::eUint32)
.bind_graphics_pipeline("cube")
.bind_vertex_buffer(
0, *verts, 0, vuk::Packed{ vuk::Format::eR32G32B32Sfloat, vuk::Ignore{ sizeof(util::Vertex) - sizeof(util::Vertex::position) } })
.bind_buffer(0, 0, uboVP);
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = static_cast<glm::mat4>(glm::angleAxis(glm::radians(angle), glm::vec3(0.f, 1.f, 0.f)));
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
} });
angle += 360.f * ImGui::GetIO().DeltaTime;
// The rendergraph has a reference to "03_depth" resource, so we must provide the attachment
// In this case, the depth attachment is an "internal" attachment:
// we don't provide an input texture, nor do we want to save the results later
// This depth attachment will have extents matching the framebuffer (deduced from the color attachment)
// but we will need to provide the format
rg.attach_and_clear_image("03_depth", { .format = vuk::Format::eD32Sfloat }, vuk::ClearDepthStencil{ 1.0f, 0 });
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "03_multipass_final" };
},
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
verts.reset();
inds.reset();
}
};
REGISTER_EXAMPLE(x);
} // namespace<file_sep>#pragma once
#include "vuk/Allocator.hpp"
#include "vuk/Context.hpp"
#include "vuk/ImageAttachment.hpp"
#include "vuk/Types.hpp"
#include "vuk/vuk_fwd.hpp"
#include <memory>
#include <span>
#include <variant>
// futures
namespace vuk {
struct FutureBase {
FutureBase() = default;
FutureBase(Allocator&);
enum class Status {
eInitial, // default-constructed future
eSubmitted, // the rendergraph referenced by this future was submitted (result is available on device with appropriate sync)
eHostAvailable // the result is available on host, available on device without sync
} status = Status::eInitial;
DomainFlagBits initial_domain = DomainFlagBits::eNone; // the domain where we submitted this Future to
QueueResourceUse last_use; // the results of the future are available if waited for on the initial_domain
uint64_t initial_visibility; // the results of the future are available if waited for {initial_domain, initial_visibility}
std::variant<ImageAttachment, Buffer> result;
template<class T>
T& get_result() {
return std::get<T>(result);
}
};
class Future {
public:
Future() = default;
/// @brief Create a Future with ownership of a RenderGraph and bind to an output
/// @param rg
/// @param output_binding
Future(std::shared_ptr<RenderGraph> rg, Name output_binding, DomainFlags dst_domain = DomainFlagBits::eDevice);
/// @brief Create a Future with ownership of a RenderGraph and bind to an output
/// @param rg
/// @param output_binding
Future(std::shared_ptr<RenderGraph> rg, QualifiedName output_binding, DomainFlags dst_domain = DomainFlagBits::eDevice);
/// @brief Create a Future from a value, automatically making the result available on the host
/// @param value
Future(ImageAttachment value) : control(std::make_shared<FutureBase>()) {
control->result = std::move(value);
control->status = FutureBase::Status::eHostAvailable;
control->last_use.layout = ImageLayout::eUndefined;
}
/// @brief Create a Future from a value, automatically making the result available on the host
/// @param value
Future(Buffer value) : control(std::make_shared<FutureBase>()) {
control->result = std::move(value);
control->status = FutureBase::Status::eHostAvailable;
control->last_use.layout = ImageLayout::eUndefined;
}
Future(const Future&) noexcept;
Future& operator=(const Future&) noexcept;
Future(Future&&) noexcept;
Future& operator=(Future&&) noexcept;
~Future();
explicit operator bool() const {
return rg.get() != nullptr;
}
/// @brief Get status of the Future
FutureBase::Status& get_status() {
return control->status;
}
/// @brief Get the referenced RenderGraph
std::shared_ptr<RenderGraph> get_render_graph() {
return rg;
}
QualifiedName get_bound_name() {
return output_binding;
}
/// @brief Submit Future for execution
Result<void> submit(Allocator& allocator, Compiler& compiler);
/// @brief Wait for Future to complete execution on host
Result<void> wait(Allocator& allocator, Compiler& compiler);
/// @brief Wait and retrieve the result of the Future on the host
template<class T>
[[nodiscard]] Result<T> get(Allocator& allocator, Compiler& compiler);
/// @brief Get control block for Future
FutureBase* get_control() {
return control.get();
}
bool is_image() const {
return control->result.index() == 0;
}
bool is_buffer() const {
return control->result.index() == 1;
}
template<class T>
T& get_result() {
return control->get_result<T>();
}
private:
QualifiedName output_binding;
std::shared_ptr<RenderGraph> rg;
std::shared_ptr<FutureBase> control;
friend struct RenderGraph;
};
template<class... Args>
Result<void> wait_for_futures(Allocator& alloc, Compiler& compiler, Args&&... futs) {
std::array controls = { futs.get_control()... };
std::array rgs = { futs.get_render_graph()... };
std::vector<std::shared_ptr<RenderGraph>> rgs_to_run;
for (uint64_t i = 0; i < controls.size(); i++) {
auto& control = controls[i];
if (control->status == FutureBase::Status::eInitial && !rgs[i]) {
return { expected_error, RenderGraphException{} };
} else if (control->status == FutureBase::Status::eHostAvailable || control->status == FutureBase::Status::eSubmitted) {
continue;
} else {
rgs_to_run.emplace_back(rgs[i]);
}
}
if (rgs_to_run.size() != 0) {
VUK_DO_OR_RETURN(link_execute_submit(alloc, compiler, std::span(rgs_to_run)));
}
std::vector<std::pair<DomainFlags, uint64_t>> waits;
for (uint64_t i = 0; i < controls.size(); i++) {
auto& control = controls[i];
if (control->status != FutureBase::Status::eSubmitted) {
continue;
}
waits.emplace_back(control->initial_domain, control->initial_visibility);
}
if (waits.size() > 0) {
alloc.get_context().wait_for_domains(std::span(waits));
}
return { expected_value };
}
inline Result<void> wait_for_futures_explicit(Allocator& alloc, Compiler& compiler, std::span<Future> futures) {
std::vector<std::shared_ptr<RenderGraph>> rgs_to_run;
for (uint64_t i = 0; i < futures.size(); i++) {
auto control = futures[i].get_control();
if (control->status == FutureBase::Status::eInitial && !futures[i].get_render_graph()) {
return { expected_error, RenderGraphException{} };
} else if (control->status == FutureBase::Status::eHostAvailable || control->status == FutureBase::Status::eSubmitted) {
continue;
} else {
rgs_to_run.emplace_back(futures[i].get_render_graph());
}
}
if (rgs_to_run.size() != 0) {
VUK_DO_OR_RETURN(link_execute_submit(alloc, compiler, std::span(rgs_to_run)));
}
std::vector<std::pair<DomainFlags, uint64_t>> waits;
for (uint64_t i = 0; i < futures.size(); i++) {
auto control = futures[i].get_control();
if (control->status != FutureBase::Status::eSubmitted) {
continue;
}
waits.emplace_back(control->initial_domain, control->initial_visibility);
}
if (waits.size() > 0) {
alloc.get_context().wait_for_domains(std::span(waits));
}
return { expected_value };
}
} // namespace vuk<file_sep>#pragma once
#include "vuk/Config.hpp"
#include "vuk/Allocator.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/CommandBuffer.hpp"
#include "vuk/Context.hpp"
#include "vuk/RenderGraph.hpp"
#include "vuk/resources/DeviceFrameResource.hpp"
#include <VkBootstrap.h>
namespace vuk {
struct TestContext {
Compiler compiler;
bool has_rt;
VkDevice device;
VkPhysicalDevice physical_device;
VkQueue graphics_queue;
VkQueue transfer_queue;
std::optional<Context> context;
vkb::Instance vkbinstance;
vkb::Device vkbdevice;
std::optional<DeviceSuperFrameResource> sfa_resource;
std::optional<Allocator> allocator;
bool bringup() {
vkb::InstanceBuilder builder;
builder.request_validation_layers()
.set_debug_callback([](VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) -> VkBool32 {
auto ms = vkb::to_string_message_severity(messageSeverity);
auto mt = vkb::to_string_message_type(messageType);
printf("[%s: %s](user defined)\n%s\n", ms, mt, pCallbackData->pMessage);
return VK_FALSE;
})
.set_app_name("vuk_example")
.set_engine_name("vuk")
.require_api_version(1, 2, 0)
.set_app_version(0, 1, 0)
.set_headless();
auto inst_ret = builder.build();
if (!inst_ret) {
throw std::runtime_error("Couldn't initialise instance");
}
has_rt = true;
vkbinstance = inst_ret.value();
auto instance = vkbinstance.instance;
vkb::PhysicalDeviceSelector selector{ vkbinstance };
selector.set_minimum_version(1, 0)
.add_required_extension(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME)
.add_required_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME)
.add_required_extension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME)
.add_required_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
auto phys_ret = selector.select();
vkb::PhysicalDevice vkbphysical_device;
if (!phys_ret) {
has_rt = false;
vkb::PhysicalDeviceSelector selector2{ vkbinstance };
selector2.set_minimum_version(1, 0).add_required_extension(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME);
auto phys_ret2 = selector2.select();
if (!phys_ret2) {
throw std::runtime_error("Couldn't create physical device");
} else {
vkbphysical_device = phys_ret2.value();
}
} else {
vkbphysical_device = phys_ret.value();
}
physical_device = vkbphysical_device.physical_device;
vkb::DeviceBuilder device_builder{ vkbphysical_device };
VkPhysicalDeviceVulkan12Features vk12features{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES };
vk12features.timelineSemaphore = true;
vk12features.descriptorBindingPartiallyBound = true;
vk12features.descriptorBindingUpdateUnusedWhilePending = true;
vk12features.shaderSampledImageArrayNonUniformIndexing = true;
vk12features.runtimeDescriptorArray = true;
vk12features.descriptorBindingVariableDescriptorCount = true;
vk12features.hostQueryReset = true;
vk12features.bufferDeviceAddress = true;
vk12features.shaderOutputLayer = true;
VkPhysicalDeviceVulkan11Features vk11features{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES };
vk11features.shaderDrawParameters = true;
VkPhysicalDeviceFeatures2 vk10features{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR };
vk10features.features.shaderInt64 = true;
VkPhysicalDeviceSynchronization2FeaturesKHR sync_feat{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR,
.synchronization2 = true };
VkPhysicalDeviceAccelerationStructureFeaturesKHR accelFeature{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR,
.accelerationStructure = true };
VkPhysicalDeviceRayTracingPipelineFeaturesKHR rtPipelineFeature{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR,
.rayTracingPipeline = true };
device_builder = device_builder.add_pNext(&vk12features).add_pNext(&vk11features).add_pNext(&sync_feat).add_pNext(&accelFeature).add_pNext(&vk10features);
if (has_rt) {
device_builder = device_builder.add_pNext(&rtPipelineFeature);
}
auto dev_ret = device_builder.build();
if (!dev_ret) {
throw std::runtime_error("Couldn't create device");
}
vkbdevice = dev_ret.value();
graphics_queue = vkbdevice.get_queue(vkb::QueueType::graphics).value();
auto graphics_queue_family_index = vkbdevice.get_queue_index(vkb::QueueType::graphics).value();
transfer_queue = vkbdevice.get_queue(vkb::QueueType::transfer).value();
auto transfer_queue_family_index = vkbdevice.get_queue_index(vkb::QueueType::transfer).value();
device = vkbdevice.device;
ContextCreateParameters::FunctionPointers fps;
#define VUK_EX_LOAD_FP(name) fps.name = (PFN_##name)vkGetDeviceProcAddr(device, #name);
VUK_EX_LOAD_FP(vkQueueSubmit2KHR);
VUK_EX_LOAD_FP(vkCmdPipelineBarrier2KHR);
VUK_EX_LOAD_FP(vkSetDebugUtilsObjectNameEXT);
VUK_EX_LOAD_FP(vkCmdBeginDebugUtilsLabelEXT);
VUK_EX_LOAD_FP(vkCmdEndDebugUtilsLabelEXT);
if (has_rt) {
VUK_EX_LOAD_FP(vkCmdBuildAccelerationStructuresKHR);
VUK_EX_LOAD_FP(vkGetAccelerationStructureBuildSizesKHR);
VUK_EX_LOAD_FP(vkCmdTraceRaysKHR);
VUK_EX_LOAD_FP(vkCreateAccelerationStructureKHR);
VUK_EX_LOAD_FP(vkDestroyAccelerationStructureKHR);
VUK_EX_LOAD_FP(vkGetRayTracingShaderGroupHandlesKHR);
VUK_EX_LOAD_FP(vkCreateRayTracingPipelinesKHR);
}
context.emplace(ContextCreateParameters{ instance,
device,
physical_device,
graphics_queue,
graphics_queue_family_index,
VK_NULL_HANDLE,
VK_QUEUE_FAMILY_IGNORED,
transfer_queue,
transfer_queue_family_index,
fps });
const unsigned num_inflight_frames = 3;
sfa_resource.emplace(*context, num_inflight_frames);
allocator.emplace(*sfa_resource);
needs_bringup = false;
return true;
}
bool teardown() {
context->wait_idle();
context.reset();
vkb::destroy_device(vkbdevice);
vkb::destroy_instance(vkbinstance);
return true;
}
bool needs_teardown = false;
bool needs_bringup = true;
bool prepare() {
if (needs_teardown) {
if (!teardown())
return false;
}
if (needs_bringup) {
if (!bringup())
return false;
}
// resource.drop_all();
return true;
}
};
extern TestContext test_context;
} // namespace vuk<file_sep>#include "vuk/Program.hpp"
#include "vuk/Hash.hpp"
#include "vuk/ShaderSource.hpp"
#include <spirv_cross.hpp>
static auto binding_cmp = [](auto& s1, auto& s2) {
return s1.binding < s2.binding;
};
static auto binding_eq = [](auto& s1, auto& s2) {
return s1.binding == s2.binding;
};
template<class T>
void unq(T& s) {
std::sort(s.begin(), s.end(), binding_cmp);
for (auto it = s.begin(); it != s.end();) {
VkShaderStageFlags stages = it->stage;
for (auto it2 = it; it2 != s.end(); it2++) {
if (it->binding == it2->binding) {
stages |= it2->stage;
} else
break;
}
it->stage = stages;
auto it2 = it;
for (; it2 != s.end(); it2++) {
if (it->binding != it2->binding)
break;
it2->stage = stages;
}
it = it2;
}
s.erase(std::unique(s.begin(), s.end(), binding_eq), s.end());
}
vuk::Program::Type to_type(spirv_cross::SPIRType s) {
using namespace spirv_cross;
using namespace vuk;
switch (s.basetype) {
case SPIRType::Float:
switch (s.columns) {
case 1:
switch (s.vecsize) {
case 1:
return Program::Type::efloat;
case 2:
return Program::Type::evec2;
case 3:
return Program::Type::evec3;
case 4:
return Program::Type::evec4;
default:
assert("NYI" && 0);
}
break;
case 3:
return Program::Type::emat3;
case 4:
return Program::Type::emat4;
}
break;
case SPIRType::Double:
switch (s.columns) {
case 1:
switch (s.vecsize) {
case 1:
return Program::Type::edouble;
case 2:
return Program::Type::edvec2;
case 3:
return Program::Type::edvec3;
case 4:
return Program::Type::edvec4;
default:
assert("NYI" && 0);
}
break;
case 3:
return Program::Type::edmat3;
case 4:
return Program::Type::edmat4;
}
break;
case SPIRType::Int:
switch (s.vecsize) {
case 1:
return Program::Type::eint;
case 2:
return Program::Type::eivec2;
case 3:
return Program::Type::eivec3;
case 4:
return Program::Type::eivec4;
default:
assert("NYI" && 0);
}
break;
case SPIRType::UInt:
switch (s.vecsize) {
case 1:
return Program::Type::euint;
case 2:
return Program::Type::euvec2;
case 3:
return Program::Type::euvec3;
case 4:
return Program::Type::euvec4;
default:
assert("NYI" && 0);
}
break;
case SPIRType::UInt64:
switch (s.vecsize) {
case 1:
return Program::Type::euint64_t;
case 2:
return Program::Type::eu64vec2;
case 3:
return Program::Type::eu64vec3;
case 4:
return Program::Type::eu64vec4;
default:
assert("NYI" && 0);
}
break;
case SPIRType::Int64:
switch (s.vecsize) {
case 1:
return Program::Type::eint64_t;
case 2:
return Program::Type::ei64vec2;
case 3:
return Program::Type::ei64vec3;
case 4:
return Program::Type::ei64vec4;
default:
assert("NYI" && 0);
}
break;
case SPIRType::Struct:
return Program::Type::estruct;
default:
assert("NYI" && 0);
}
return Program::Type::einvalid;
}
void reflect_members(const spirv_cross::Compiler& refl, const spirv_cross::SPIRType& type, std::vector<vuk::Program::Member>& members) {
for (uint32_t i = 0; i < type.member_types.size(); i++) {
auto& t = type.member_types[i];
vuk::Program::Member m;
auto spirtype = refl.get_type(t);
m.type = to_type(spirtype);
if (m.type == vuk::Program::Type::estruct) {
m.type_name = refl.get_name(t);
if (m.type_name == "") {
m.type_name = refl.get_name(spirtype.parent_type);
}
}
m.name = refl.get_member_name(type.self, i);
m.size = refl.get_declared_struct_member_size(type, i);
m.offset = refl.type_struct_member_offset(type, i);
if (m.type == vuk::Program::Type::estruct) {
m.size = refl.get_declared_struct_size(spirtype);
reflect_members(refl, spirtype, m.members);
}
if (spirtype.array.size() > 0) {
m.array_size = spirtype.array[0];
} else {
m.array_size = 1;
}
members.push_back(m);
}
}
VkShaderStageFlagBits vuk::Program::introspect(const uint32_t* ir, size_t word_count) {
spirv_cross::Compiler refl(ir, word_count);
auto resources = refl.get_shader_resources();
auto entry_name = refl.get_entry_points_and_stages()[0];
auto entry_point = refl.get_entry_point(entry_name.name, entry_name.execution_model);
auto model = entry_point.model;
auto stage = [=]() {
switch (model) {
case spv::ExecutionModel::ExecutionModelVertex:
return VK_SHADER_STAGE_VERTEX_BIT;
case spv::ExecutionModel::ExecutionModelTessellationControl:
return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
case spv::ExecutionModel::ExecutionModelTessellationEvaluation:
return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
case spv::ExecutionModel::ExecutionModelGeometry:
return VK_SHADER_STAGE_GEOMETRY_BIT;
case spv::ExecutionModel::ExecutionModelFragment:
return VK_SHADER_STAGE_FRAGMENT_BIT;
case spv::ExecutionModel::ExecutionModelGLCompute:
return VK_SHADER_STAGE_COMPUTE_BIT;
case spv::ExecutionModel::ExecutionModelAnyHitKHR:
return VK_SHADER_STAGE_ANY_HIT_BIT_KHR;
case spv::ExecutionModel::ExecutionModelCallableKHR:
return VK_SHADER_STAGE_CALLABLE_BIT_KHR;
case spv::ExecutionModel::ExecutionModelClosestHitKHR:
return VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR;
case spv::ExecutionModel::ExecutionModelIntersectionKHR:
return VK_SHADER_STAGE_INTERSECTION_BIT_KHR;
case spv::ExecutionModel::ExecutionModelMissKHR:
return VK_SHADER_STAGE_MISS_BIT_KHR;
case spv::ExecutionModel::ExecutionModelRayGenerationKHR:
return VK_SHADER_STAGE_RAYGEN_BIT_KHR;
default:
return VK_SHADER_STAGE_VERTEX_BIT;
}
}();
stages = stage;
if (stage == VK_SHADER_STAGE_VERTEX_BIT) {
for (auto& sb : resources.stage_inputs) {
auto type = refl.get_type(sb.type_id);
auto location = refl.get_decoration(sb.id, spv::DecorationLocation);
unsigned count = 1;
if (type.array.size() > 0) {
count = type.array[0];
}
for (uint32_t i = 0; i < count; i++) {
Attribute a;
a.location = location + i;
a.name = sb.name.c_str();
a.type = to_type(type);
attributes.push_back(a);
}
}
}
// uniform buffers
for (auto& ub : resources.uniform_buffers) {
auto type = refl.get_type(ub.type_id);
auto binding = refl.get_decoration(ub.id, spv::DecorationBinding);
auto set = refl.get_decoration(ub.id, spv::DecorationDescriptorSet);
UniformBuffer un;
un.binding = binding;
un.stage = stage;
un.name = std::string(ub.name.c_str());
if (type.array.size() > 0)
un.array_size = type.array[0];
else
un.array_size = 1;
if (type.basetype == spirv_cross::SPIRType::Struct) {
reflect_members(refl, refl.get_type(ub.type_id), un.members);
}
un.size = refl.get_declared_struct_size(type);
sets[set].uniform_buffers.push_back(un);
}
for (auto& sb : resources.storage_buffers) {
auto type = refl.get_type(sb.type_id);
auto binding = refl.get_decoration(sb.id, spv::DecorationBinding);
auto set = refl.get_decoration(sb.id, spv::DecorationDescriptorSet);
StorageBuffer un;
un.binding = binding;
un.stage = stage;
un.name = sb.name.c_str();
un.min_size = refl.get_declared_struct_size(refl.get_type(sb.type_id));
if (type.basetype == spirv_cross::SPIRType::Struct) {
reflect_members(refl, refl.get_type(sb.type_id), un.members);
}
un.is_hlsl_counter_buffer = refl.buffer_is_hlsl_counter_buffer(sb.id);
sets[set].storage_buffers.push_back(un);
}
for (auto& si : resources.sampled_images) {
auto type = refl.get_type(si.type_id);
auto binding = refl.get_decoration(si.id, spv::DecorationBinding);
auto set = refl.get_decoration(si.id, spv::DecorationDescriptorSet);
CombinedImageSampler t;
t.binding = binding;
t.name = std::string(si.name.c_str());
t.stage = stage;
// maybe spirv cross bug?
t.array_size = type.array.size() == 1 ? (type.array[0] == 1 ? 0 : type.array[0]) : -1;
t.shadow = type.image.depth;
sets[set].combined_image_samplers.push_back(t);
}
for (auto& sa : resources.separate_samplers) {
auto type = refl.get_type(sa.type_id);
auto binding = refl.get_decoration(sa.id, spv::DecorationBinding);
auto set = refl.get_decoration(sa.id, spv::DecorationDescriptorSet);
Sampler t;
t.binding = binding;
t.name = std::string(sa.name.c_str());
t.stage = stage;
// maybe spirv cross bug?
t.array_size = type.array.size() == 1 ? (type.array[0] == 1 ? 0 : type.array[0]) : -1;
t.shadow = type.image.depth;
sets[set].samplers.push_back(t);
}
for (auto& si : resources.separate_images) {
auto type = refl.get_type(si.type_id);
auto binding = refl.get_decoration(si.id, spv::DecorationBinding);
auto set = refl.get_decoration(si.id, spv::DecorationDescriptorSet);
SampledImage t;
t.binding = binding;
t.name = std::string(si.name.c_str());
t.stage = stage;
// maybe spirv cross bug?
t.array_size = type.array.size() == 1 ? (type.array[0] == 1 ? 0 : type.array[0]) : -1;
sets[set].sampled_images.push_back(t);
}
for (auto& sb : resources.storage_images) {
auto type = refl.get_type(sb.type_id);
auto binding = refl.get_decoration(sb.id, spv::DecorationBinding);
auto set = refl.get_decoration(sb.id, spv::DecorationDescriptorSet);
StorageImage un;
un.binding = binding;
un.stage = stage;
un.name = sb.name.c_str();
// maybe spirv cross bug?
un.array_size = type.array.size() == 1 ? (type.array[0] == 1 ? 0 : type.array[0]) : -1;
sets[set].storage_images.push_back(un);
}
// subpass inputs
for (auto& si : resources.subpass_inputs) {
auto type = refl.get_type(si.type_id);
auto binding = refl.get_decoration(si.id, spv::DecorationBinding);
auto set = refl.get_decoration(si.id, spv::DecorationDescriptorSet);
SubpassInput s;
s.name = std::string(si.name.c_str());
s.binding = binding;
s.stage = stage;
sets[set].subpass_inputs.push_back(s);
}
// ASs
for (auto& as : resources.acceleration_structures) {
auto type = refl.get_type(as.type_id);
auto binding = refl.get_decoration(as.id, spv::DecorationBinding);
auto set = refl.get_decoration(as.id, spv::DecorationDescriptorSet);
AccelerationStructure s;
s.name = std::string(as.name.c_str());
s.binding = binding;
s.stage = stage;
s.array_size = type.array.size() == 1 ? (type.array[0] == 1 ? 0 : type.array[0]) : -1;
sets[set].acceleration_structures.push_back(s);
}
for (auto& sc : refl.get_specialization_constants()) {
spec_constants.emplace_back(SpecConstant{ sc.constant_id, to_type(refl.get_type(refl.get_constant(sc.id).constant_type)), (VkShaderStageFlags)stage });
}
// remove duplicated bindings (aliased bindings)
// TODO: we need to preserve this information somewhere
for (auto& [index, set] : sets) {
unq(set.samplers);
unq(set.sampled_images);
unq(set.combined_image_samplers);
unq(set.uniform_buffers);
unq(set.storage_buffers);
unq(set.texel_buffers);
unq(set.subpass_inputs);
unq(set.storage_images);
unq(set.acceleration_structures);
}
std::sort(spec_constants.begin(), spec_constants.end(), binding_cmp);
for (auto& [index, set] : sets) {
unsigned max_binding = 0;
for (auto& ub : set.uniform_buffers) {
max_binding = std::max(max_binding, ub.binding);
}
for (auto& ub : set.storage_buffers) {
max_binding = std::max(max_binding, ub.binding);
}
for (auto& ub : set.samplers) {
max_binding = std::max(max_binding, ub.binding);
}
for (auto& ub : set.sampled_images) {
max_binding = std::max(max_binding, ub.binding);
}
for (auto& ub : set.combined_image_samplers) {
max_binding = std::max(max_binding, ub.binding);
}
for (auto& ub : set.subpass_inputs) {
max_binding = std::max(max_binding, ub.binding);
}
for (auto& ub : set.storage_buffers) {
max_binding = std::max(max_binding, ub.binding);
}
for (auto& ub : set.acceleration_structures) {
max_binding = std::max(max_binding, ub.binding);
}
set.highest_descriptor_binding = max_binding;
}
// push constants
for (auto& si : resources.push_constant_buffers) {
auto type = refl.get_type(si.base_type_id);
VkPushConstantRange pcr;
pcr.offset = 0;
pcr.size = (uint32_t)refl.get_declared_struct_size(type);
pcr.stageFlags = stage;
push_constant_ranges.push_back(pcr);
}
if (stage == VK_SHADER_STAGE_COMPUTE_BIT) {
local_size = { refl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, 0),
refl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, 1),
refl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, 2) };
}
return stage;
}
void vuk::Program::append(const Program& o) {
attributes.insert(attributes.end(), o.attributes.begin(), o.attributes.end());
push_constant_ranges.insert(push_constant_ranges.end(), o.push_constant_ranges.begin(), o.push_constant_ranges.end());
spec_constants.insert(spec_constants.end(), o.spec_constants.begin(), o.spec_constants.end());
unq(spec_constants);
for (auto& [index, os] : o.sets) {
auto& s = sets[index];
s.samplers.insert(s.samplers.end(), os.samplers.begin(), os.samplers.end());
s.sampled_images.insert(s.sampled_images.end(), os.sampled_images.begin(), os.sampled_images.end());
s.combined_image_samplers.insert(s.combined_image_samplers.end(), os.combined_image_samplers.begin(), os.combined_image_samplers.end());
s.uniform_buffers.insert(s.uniform_buffers.end(), os.uniform_buffers.begin(), os.uniform_buffers.end());
s.storage_buffers.insert(s.storage_buffers.end(), os.storage_buffers.begin(), os.storage_buffers.end());
s.texel_buffers.insert(s.texel_buffers.end(), os.texel_buffers.begin(), os.texel_buffers.end());
s.subpass_inputs.insert(s.subpass_inputs.end(), os.subpass_inputs.begin(), os.subpass_inputs.end());
s.storage_images.insert(s.storage_images.end(), os.storage_images.begin(), os.storage_images.end());
s.acceleration_structures.insert(s.acceleration_structures.end(), os.acceleration_structures.begin(), os.acceleration_structures.end());
unq(s.samplers);
unq(s.sampled_images);
unq(s.combined_image_samplers);
unq(s.uniform_buffers);
unq(s.storage_buffers);
unq(s.texel_buffers);
unq(s.subpass_inputs);
unq(s.storage_images);
unq(s.acceleration_structures);
s.highest_descriptor_binding = std::max(s.highest_descriptor_binding, os.highest_descriptor_binding);
}
stages |= o.stages;
local_size = o.local_size;
}
size_t std::hash<vuk::ShaderModuleCreateInfo>::operator()(vuk::ShaderModuleCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.filename);
return h;
}
<file_sep>#include "example_runner.hpp"
vuk::SingleSwapchainRenderBundle bundle;
void vuk::ExampleRunner::render() {
Compiler compiler;
// the examples can all enqueue upload tasks via enqueue_setup. for simplicity, we submit and wait for all the upload tasks before moving on to the render loop
// in a real application, one would have something more complex to handle uploading data
// it is also possible to wait for the uploads on the GPU by using these uploading futures as input
vuk::wait_for_futures_explicit(*superframe_allocator, compiler, futures);
futures.clear();
// our main loop
while (!glfwWindowShouldClose(window)) {
// pump the message loop
glfwPollEvents();
while (suspend) {
glfwWaitEvents();
}
// advance the frame for the allocators and caches used by vuk
auto& frame_resource = superframe_resource->get_next_frame();
context->next_frame();
// create a frame allocator - we can allocate objects for the duration of the frame from this allocator
// all of the objects allocated from this allocator last for this frame, and get recycled automatically, so for this specific allocator, deallocation is optional
Allocator frame_allocator(frame_resource);
// acquire an image on the swapchain
bundle = *acquire_one(*context, swapchain, (*present_ready)[context->get_frame_count() % 3], (*render_complete)[context->get_frame_count() % 3]);
// create a rendergraph we will use to prepare a swapchain image for the example to render into
std::shared_ptr<RenderGraph> rg(std::make_shared<RenderGraph>("runner"));
// we bind the swapchain to name "_swp"
rg->attach_swapchain("_swp", swapchain);
// clear the "_swp" image and call the cleared image "example_target_image"
rg->clear_image("_swp", "example_target_image", vuk::ClearColor{ 0.3f, 0.5f, 0.3f, 1.0f });
// bind "example_target_image" as the output of this rendergraph
Future cleared_image_to_render_into{ std::move(rg), "example_target_image" };
// invoke the render method of the example with the cleared image
Future example_result = examples[0]->render(*this, frame_allocator, std::move(cleared_image_to_render_into));
// make a new RG that will take care of putting the swapchain image into present and releasing it from the rg
std::shared_ptr<RenderGraph> rg_p(std::make_shared<RenderGraph>("presenter"));
rg_p->attach_in("_src", std::move(example_result));
// we tell the rendergraph that _src will be used for presenting after the rendergraph
rg_p->release_for_present("_src");
// compile the RG that contains all the rendering of the example
auto erg = *compiler.link(std::span{ &rg_p, 1 }, {});
// submit the compiled commands
auto result = *execute_submit(frame_allocator, std::move(erg), std::move(bundle));
// present the results
present_to_one(*context, std::move(result));
// update window title with FPS
if (++num_frames == 16) {
auto new_time = get_time();
auto delta = new_time - old_time;
auto per_frame_time = delta / 16 * 1000;
old_time = new_time;
num_frames = 0;
set_window_title(std::string("Vuk example [") + std::to_string(per_frame_time) + " ms / " + std::to_string(1000 / per_frame_time) + " FPS]");
}
}
}
int main(int argc, char** argv) {
auto path_to_root = std::filesystem::relative(VUK_EX_PATH_ROOT, VUK_EX_PATH_TGT);
root = std::filesystem::canonical(std::filesystem::path(argv[0]).parent_path() / path_to_root);
// very simple error handling in the example framework: we don't check for errors and just let them be converted into exceptions that are caught at top level
try {
vuk::ExampleRunner::get_runner().setup();
vuk::ExampleRunner::get_runner().render();
vuk::ExampleRunner::get_runner().cleanup();
} catch (vuk::Exception& e) {
fprintf(stderr, "%s", e.what());
}
}
<file_sep>#include "example_runner.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
#include <stb_image.h>
/* 12_rt_pipeline
* This example demonstrates how to build acceleration structures and trace against them using RT pipelines. This example requires that your driver supports
* VK_KHR_ray_tracing. While there is no tight integration yet for building acceleration structures, you can already synchronize their building and raytracing
* just as graphics and compute workloads.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
float angle = 0.f;
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
vuk::Unique<VkAccelerationStructureKHR> tlas, blas;
vuk::Unique<vuk::Buffer> tlas_buf, blas_buf, tlas_scratch_buffer;
vuk::Example x{
.name = "12_rt_pipeline",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
auto& ctx = allocator.get_context();
// If the runner has detected that there is no RT support, this example won't run
if (!runner.has_rt) {
return;
}
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/rt.rgen").generic_string()), (root / "examples/rt.rgen").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/rt.rmiss").generic_string()), (root / "examples/rt.rmiss").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/rt.rchit").generic_string()), (root / "examples/rt.rchit").generic_string());
// new for RT: a hit group is a collection of shaders identified by their index in the PipelineBaseCreateInfo
// 2 => rt.rchit
pci.add_hit_group(vuk::HitGroup{ .type = vuk::HitGroupType::eTriangles, .closest_hit = 2 });
runner.context->create_named_pipeline("raytracing", pci);
}
// We set up the cube data, same as in example 02_cube
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
// BLAS building
// We build a BLAS out of our cube.
uint32_t maxPrimitiveCount = (uint32_t)box.second.size() / 3;
// Describe the mesh
VkAccelerationStructureGeometryTrianglesDataKHR triangles{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR };
triangles.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT; // vec3 vertex position data.
triangles.vertexData.deviceAddress = verts->device_address;
triangles.vertexStride = sizeof(util::Vertex);
// Describe index data (32-bit unsigned int)
triangles.indexType = VK_INDEX_TYPE_UINT32;
triangles.indexData.deviceAddress = inds->device_address;
// Indicate identity transform by setting transformData to null device pointer.
triangles.transformData = {};
triangles.maxVertex = (uint32_t)box.first.size();
// Identify the above data as containing opaque triangles.
VkAccelerationStructureGeometryKHR as_geom{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR };
as_geom.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR;
as_geom.flags = VK_GEOMETRY_OPAQUE_BIT_KHR;
as_geom.geometry.triangles = triangles;
// Find sizes
VkAccelerationStructureBuildGeometryInfoKHR blas_build_info{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR };
blas_build_info.dstAccelerationStructure = *blas;
blas_build_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
blas_build_info.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
blas_build_info.flags = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR;
blas_build_info.geometryCount = 1;
blas_build_info.pGeometries = &as_geom;
VkAccelerationStructureBuildSizesInfoKHR blas_size_info{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR };
ctx.vkGetAccelerationStructureBuildSizesKHR(
ctx.device, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &blas_build_info, &maxPrimitiveCount, &blas_size_info);
// Allocate the BLAS object and a buffer that holds the data
VkAccelerationStructureCreateInfoKHR blas_ci{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR };
blas_ci.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR;
blas_ci.size = blas_size_info.accelerationStructureSize; // Will be used to allocate memory.
blas_buf =
*vuk::allocate_buffer(allocator, { .mem_usage = vuk::MemoryUsage::eGPUonly, .size = blas_size_info.accelerationStructureSize, .alignment = 256 });
blas_ci.buffer = blas_buf->buffer;
blas_ci.offset = blas_buf->offset;
blas = vuk::Unique<VkAccelerationStructureKHR>(allocator);
allocator.allocate_acceleration_structures({ &*blas, 1 }, { &blas_ci, 1 });
// Allocate the scratch memory for the BLAS build
auto blas_scratch_buffer =
*vuk::allocate_buffer(allocator,
vuk::BufferCreateInfo{ .mem_usage = vuk::MemoryUsage::eGPUonly,
.size = blas_size_info.buildScratchSize,
.alignment = ctx.as_properties.minAccelerationStructureScratchOffsetAlignment });
// Update build information
blas_build_info.srcAccelerationStructure = VK_NULL_HANDLE;
blas_build_info.dstAccelerationStructure = *blas;
blas_build_info.scratchData.deviceAddress = blas_scratch_buffer->device_address;
// TLAS building
// We build a TLAS that refers to the BLAS we build before.
VkAccelerationStructureInstanceKHR rayInst{};
rayInst.transform = {};
rayInst.transform.matrix[0][0] = 1.f;
rayInst.transform.matrix[1][1] = 1.f;
rayInst.transform.matrix[2][2] = 1.f;
rayInst.instanceCustomIndex = 0; // gl_InstanceCustomIndexEXT
rayInst.accelerationStructureReference = blas_buf->device_address;
rayInst.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR;
rayInst.mask = 0xFF; // Only be hit if rayMask & instance.mask != 0
rayInst.instanceShaderBindingTableRecordOffset = 0; // We will use the same hit group for all objects
auto instances_buffer =
vuk::create_buffer(allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span{ &rayInst, 1 });
VkAccelerationStructureGeometryInstancesDataKHR instancesVk{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR };
instancesVk.data.deviceAddress = instances_buffer.first->device_address;
// Put the above into a VkAccelerationStructureGeometryKHR. We need to put the instances struct in a union and label it as instance data.
VkAccelerationStructureGeometryKHR topASGeometry{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR };
topASGeometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR;
topASGeometry.geometry.instances = instancesVk;
// Find sizes
VkAccelerationStructureBuildGeometryInfoKHR tlas_build_info{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR };
tlas_build_info.flags = VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR;
tlas_build_info.geometryCount = 1;
tlas_build_info.pGeometries = &topASGeometry;
tlas_build_info.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR;
tlas_build_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
uint32_t countInstance = 1;
VkAccelerationStructureBuildSizesInfoKHR tlas_size_info{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR };
ctx.vkGetAccelerationStructureBuildSizesKHR(
allocator.get_context().device, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &tlas_build_info, &countInstance, &tlas_size_info);
// Allocate the TLAS object and a buffer that holds the data
VkAccelerationStructureCreateInfoKHR tlas_ci{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR };
tlas_ci.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
tlas_ci.size = tlas_size_info.accelerationStructureSize;
tlas_buf =
*vuk::allocate_buffer(allocator, { .mem_usage = vuk::MemoryUsage::eGPUonly, .size = tlas_size_info.accelerationStructureSize, .alignment = 256 });
tlas_ci.buffer = tlas_buf->buffer;
tlas_ci.offset = tlas_buf->offset;
tlas = vuk::Unique<VkAccelerationStructureKHR>(allocator);
allocator.allocate_acceleration_structures({ &*tlas, 1 }, { &tlas_ci, 1 });
// Allocate the scratch memory
tlas_scratch_buffer = *vuk::allocate_buffer(allocator,
vuk::BufferCreateInfo{ .mem_usage = vuk::MemoryUsage::eGPUonly,
.size = tlas_size_info.buildScratchSize,
.alignment = ctx.as_properties.minAccelerationStructureScratchOffsetAlignment });
// Update build information
tlas_build_info.srcAccelerationStructure = VK_NULL_HANDLE;
tlas_build_info.dstAccelerationStructure = *tlas;
tlas_build_info.scratchData.deviceAddress = tlas_scratch_buffer->device_address;
// Build the BLAS & TLAS
vuk::RenderGraph as_build("as_build");
// We attach the vertex and index futures, which will be used for the BLAS build
as_build.attach_in("verts", std::move(vert_fut));
as_build.attach_in("inds", std::move(ind_fut));
// Synchronization happens against the AS buffers
as_build.attach_buffer("blas_buf", *blas_buf);
as_build.attach_buffer("tlas_buf", *tlas_buf);
as_build.add_pass({ .resources = { "blas_buf"_buffer >> vuk::eAccelerationStructureBuildWrite,
"verts"_buffer >> vuk::eAccelerationStructureBuildRead,
"inds"_buffer >> vuk::eAccelerationStructureBuildRead },
.execute = [maxPrimitiveCount, as_geom, blas_build_info](vuk::CommandBuffer& command_buffer) mutable {
// We make a copy of the AS geometry to not dangle when this runs.
blas_build_info.pGeometries = &as_geom;
// Describe what we are building.
VkAccelerationStructureBuildRangeInfoKHR blas_offset;
blas_offset.primitiveCount = maxPrimitiveCount;
blas_offset.firstVertex = 0;
blas_offset.primitiveOffset = 0;
blas_offset.transformOffset = 0;
const VkAccelerationStructureBuildRangeInfoKHR* pblas_offset = &blas_offset;
command_buffer.build_acceleration_structures(1, &blas_build_info, &pblas_offset);
} });
as_build.add_pass(
{ .resources = { "blas_buf+"_buffer >> vuk::eAccelerationStructureBuildRead, "tlas_buf"_buffer >> vuk::eAccelerationStructureBuildWrite },
.execute = [countInstance, topASGeometry, tlas_build_info](vuk::CommandBuffer& command_buffer) mutable {
// We make a copy of the AS geometry to not dangle when this runs.
tlas_build_info.pGeometries = &topASGeometry;
// Describe what we are building.
VkAccelerationStructureBuildRangeInfoKHR tlas_offset{ countInstance, 0, 0, 0 };
const VkAccelerationStructureBuildRangeInfoKHR* ptlas_offset = &tlas_offset;
command_buffer.build_acceleration_structures(1, &tlas_build_info, &ptlas_offset);
} });
// For the example, we just ask these that these uploads and AS building complete before moving on to rendering
// In an engine, you would integrate these uploads into some explicit system
runner.enqueue_setup(vuk::Future(std::make_shared<vuk::RenderGraph>(std::move(as_build)), "tlas_buf+"));
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
if (!runner.has_rt) {
return target;
}
struct VP {
glm::mat4 inv_view;
glm::mat4 inv_proj;
} vp;
vp.inv_view = glm::lookAt(glm::vec3(0, 1.5, 3.5), glm::vec3(0), glm::vec3(0, 1, 0));
vp.inv_proj = glm::perspective(glm::degrees(70.f), 1.f, 1.f, 100.f);
vp.inv_proj[1][1] *= -1;
vp.inv_view = glm::inverse(vp.inv_view);
vp.inv_proj = glm::inverse(vp.inv_proj);
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
// TLAS update - we make a new buffer of BLAS instances, which we use to update the TLAS later
VkAccelerationStructureInstanceKHR rayInst{};
rayInst.transform = {};
glm::mat4 model_transform = static_cast<glm::mat4>(glm::angleAxis(glm::radians(angle), glm::vec3(0.f, 1.f, 0.f)));
glm::mat3x4 reduced_model_transform = static_cast<glm::mat3x4>(model_transform);
memcpy(&rayInst.transform.matrix, &reduced_model_transform, sizeof(glm::mat3x4));
rayInst.instanceCustomIndex = 0; // gl_InstanceCustomIndexEXT
rayInst.accelerationStructureReference = blas_buf->device_address;
rayInst.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR;
rayInst.mask = 0xFF; // Only be hit if rayMask & instance.mask != 0
rayInst.instanceShaderBindingTableRecordOffset = 0; // We will use the same hit group for all objects
auto [instances_buffer, instances_fut] =
vuk::create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span{ &rayInst, 1 });
vuk::RenderGraph rg("12");
rg.attach_in("12_rt", std::move(target));
rg.attach_buffer("tlas", *tlas_buf);
// TLAS update pass
rg.add_pass({ .resources = { "tlas"_buffer >> vuk::eAccelerationStructureBuildWrite },
.execute = [inst_buf = *instances_buffer](vuk::CommandBuffer& command_buffer) {
// TLAS update
VkAccelerationStructureGeometryInstancesDataKHR instancesVk{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR };
instancesVk.data.deviceAddress = inst_buf.device_address;
VkAccelerationStructureGeometryKHR topASGeometry{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR };
topASGeometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR;
topASGeometry.geometry.instances = instancesVk;
VkAccelerationStructureBuildGeometryInfoKHR tlas_build_info{ VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR };
tlas_build_info.flags = VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR;
tlas_build_info.geometryCount = 1;
tlas_build_info.pGeometries = &topASGeometry;
tlas_build_info.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR;
tlas_build_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR;
tlas_build_info.srcAccelerationStructure = *tlas;
tlas_build_info.dstAccelerationStructure = *tlas;
tlas_build_info.scratchData.deviceAddress = tlas_scratch_buffer->device_address;
VkAccelerationStructureBuildRangeInfoKHR tlas_offset{ 1, 0, 0, 0 };
const VkAccelerationStructureBuildRangeInfoKHR* ptlas_offset = &tlas_offset;
command_buffer.build_acceleration_structures(1, &tlas_build_info, &ptlas_offset);
} });
// We use a eR8G8B8A8Unorm, as the swapchain is in sRGB which does not support storage use
rg.attach_image("12_rt_target",
vuk::ImageAttachment{ .format = vuk::Format::eR8G8B8A8Unorm, .sample_count = vuk::SampleCountFlagBits::e1, .layer_count = 1 });
// This intermediate image is the same shape as the swapchain image
rg.inference_rule("12_rt_target", vuk::same_shape_as("12_rt"));
// Synchronize against the TLAS buffer to run this pass after the TLAS update has completed
rg.add_pass({ .resources = { "12_rt_target"_image >> vuk::eRayTracingWrite, "tlas+"_buffer >> vuk::eRayTracingRead },
.execute = [uboVP](vuk::CommandBuffer& command_buffer) {
command_buffer.bind_acceleration_structure(0, 0, *tlas)
.bind_image(0, 1, "12_rt_target")
.bind_buffer(0, 2, uboVP)
.bind_ray_tracing_pipeline("raytracing");
// Launch one ray per pixel in the intermediate image
auto extent = command_buffer.get_resource_image_attachment("12_rt_target")->extent;
command_buffer.trace_rays(extent.extent.width, extent.extent.height, 1);
} });
// Perform a blit of the intermediate image onto the swapchain (this will also do the non-linear encoding for us, although we lost some precision when
// we rendered into Unorm)
rg.add_pass({ .resources = { "12_rt_target+"_image >> vuk::eTransferRead, "12_rt"_image >> vuk::eTransferWrite >> "12_rt_final" },
.execute = [](vuk::CommandBuffer& command_buffer) {
vuk::ImageBlit blit;
blit.srcSubresource.aspectMask = vuk::ImageAspectFlagBits::eColor;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.srcSubresource.mipLevel = 0;
blit.dstSubresource = blit.srcSubresource;
auto extent = command_buffer.get_resource_image_attachment("12_rt_target+")->extent;
blit.srcOffsets[1] = vuk::Offset3D{ static_cast<int>(extent.extent.width), static_cast<int>(extent.extent.height), 1 };
blit.dstOffsets[1] = blit.srcOffsets[1];
command_buffer.blit_image("12_rt_target+", "12_rt", blit, vuk::Filter::eNearest);
} });
angle += 20.f * ImGui::GetIO().DeltaTime;
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "12_rt_final" };
},
// Perform cleanup for the example
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
verts.reset();
inds.reset();
tlas.reset();
tlas_buf.reset();
blas.reset();
blas_buf.reset();
tlas_scratch_buffer.reset();
}
};
REGISTER_EXAMPLE(x);
} // namespace<file_sep>#pragma once
#include "vuk/Name.hpp"
namespace vuk {
class Context;
class Allocator;
class CommandBuffer;
struct Swapchain;
using SwapchainRef = Swapchain*;
class LegacyGPUAllocator;
struct ShaderSource;
// 0b00111 -> 3
inline uint32_t num_leading_ones(uint32_t mask) noexcept {
#ifdef __has_builtin
#if __has_builtin(__builtin_clz)
return (31 ^ __builtin_clz(mask)) + 1;
#else
#error "__builtin_clz not available"
#endif
#else
unsigned long lz;
if (!_BitScanReverse(&lz, mask))
return 0;
return lz + 1;
#endif
}
// return a/b rounded to infinity
constexpr uint64_t idivceil(uint64_t a, uint64_t b) noexcept {
return (a + b - 1) / b;
}
struct Exception;
struct ShaderCompilationException;
struct RenderGraphException;
struct AllocateException;
struct PresentException;
struct VkException;
template<class V, class E = Exception>
struct Result;
template<class T>
class Unique;
struct FramebufferCreateInfo;
struct BufferCreateInfo;
struct Buffer;
struct Query;
struct TimestampQuery;
struct TimestampQueryPool;
struct TimestampQueryCreateInfo;
struct CommandBufferAllocationCreateInfo;
struct CommandBufferAllocation;
struct SetBinding;
struct DescriptorSet;
struct PersistentDescriptorSetCreateInfo;
struct PersistentDescriptorSet;
struct ShaderModule;
struct PipelineBaseCreateInfo;
struct PipelineBaseInfo;
struct Program;
struct GraphicsPipelineInfo;
struct GraphicsPipelineInstanceCreateInfo;
struct ComputePipelineInfo;
struct ComputePipelineInstanceCreateInfo;
struct RayTracingPipelineInfo;
struct RayTracingPipelineInstanceCreateInfo;
struct RenderPassCreateInfo;
struct FutureBase;
class Future;
struct Compiler;
} // namespace vuk
<file_sep>cmake_minimum_required(VERSION 3.7)
project(vuk-examples)
if(NOT VUK_USE_SHADERC)
message(FATAL_ERROR "Building vuk examples require shaderc for building shaders, enable VUK_USE_SHADERC")
endif()
FetchContent_Declare(
vk-bootstrap
GIT_REPOSITORY https://github.com/charles-lunarg/vk-bootstrap
GIT_TAG 8e61b2d81c3f5f84339735085ff5651f71bbe1e7
)
FetchContent_MakeAvailable(vk-bootstrap)
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
FetchContent_Declare(
glfw
GIT_REPOSITORY https://github.com/glfw/glfw
GIT_TAG 3.3.6
)
FetchContent_MakeAvailable(glfw)
FetchContent_Declare(
glm
GIT_REPOSITORY https://github.com/g-truc/glm
GIT_TAG cc98465e3508535ba8c7f6208df934c156a018dc
)
FetchContent_MakeAvailable(glm)
add_library(vuk-example-framework)
#message(FATAL_ERROR $<TARGET_FILE_DIR:vuk-example-framework>)
SET(imgui_sources ../ext/imgui/imgui.cpp ../ext/imgui/imgui_draw.cpp ../ext/imgui/imgui_demo.cpp ../ext/imgui/imgui_widgets.cpp ../ext/imgui/imgui_tables.cpp ../ext/imgui/backends/imgui_impl_glfw.cpp)
target_sources(vuk-example-framework PRIVATE imgui.cpp stbi.cpp ${imgui_sources})
target_include_directories(vuk-example-framework SYSTEM PUBLIC ../ext/stb ../ext/imgui)
target_compile_definitions(vuk-example-framework PUBLIC GLM_FORCE_SIZE_FUNC GLM_FORCE_EXPLICIT_CTOR GLM_ENABLE_EXPERIMENTAL GLM_FORCE_RADIANS GLM_FORCE_DEPTH_ZERO_TO_ONE)
if(VUK_COMPILER_CLANGPP OR VUK_COMPILER_GPP)
target_compile_options(vuk-example-framework PUBLIC -std=c++20 -fno-char8_t)
elseif(MSVC)
target_compile_options(vuk-example-framework PUBLIC /std:c++20 /permissive- /Zc:char8_t-)
endif()
target_link_libraries(vuk-example-framework PUBLIC vuk vk-bootstrap glfw glm)
add_executable(vuk_all_examples)
target_sources(vuk_all_examples PRIVATE example_browser.cpp)
target_link_libraries(vuk_all_examples PRIVATE vuk-example-framework)
target_compile_definitions(vuk_all_examples PUBLIC VUK_EX_PATH_TGT="$<TARGET_FILE_DIR:vuk_all_examples>" VUK_EX_PATH_ROOT="${CMAKE_SOURCE_DIR}")
add_library(vuk_example_runner_single OBJECT example_runner_single.cpp)
target_link_libraries(vuk_example_runner_single PRIVATE vuk-example-framework)
target_compile_definitions(vuk-example-framework PUBLIC VUK_EX_PATH_TGT="$<TARGET_FILE_DIR:vuk_all_examples>" VUK_EX_PATH_ROOT="${CMAKE_SOURCE_DIR}")
function(ADD_EXAMPLE name)
set(FULL_NAME "vuk_example_${name}")
add_executable(${FULL_NAME})
add_library(${FULL_NAME}_obj OBJECT "${name}.cpp")
target_link_libraries(${FULL_NAME}_obj PUBLIC vuk-example-framework)
target_link_libraries(${FULL_NAME} PRIVATE ${FULL_NAME}_obj vuk_example_runner_single)
target_link_libraries(vuk_all_examples PRIVATE ${FULL_NAME}_obj)
endfunction(ADD_EXAMPLE)
ADD_EXAMPLE(01_triangle)
ADD_EXAMPLE(02_cube)
ADD_EXAMPLE(03_multipass)
ADD_EXAMPLE(04_texture)
ADD_EXAMPLE(05_deferred)
ADD_EXAMPLE(06_msaa)
ADD_EXAMPLE(07_commands)
ADD_EXAMPLE(08_pipelined_compute)
ADD_EXAMPLE(09_persistent_descriptorset)
ADD_EXAMPLE(10_baby_renderer)
ADD_EXAMPLE(11_composition)
ADD_EXAMPLE(12_rt_pipeline)
<file_sep>#include "Cache.hpp"
#include "RenderPass.hpp"
#include "vuk/Allocator.hpp"
#include "vuk/Context.hpp"
#include "vuk/PipelineInstance.hpp"
#include "vuk/Query.hpp"
#include "vuk/resources/DeviceVkResource.hpp"
#include <atomic>
#include <math.h>
#include <mutex>
#include <plf_colony.h>
#include <queue>
#include <robin_hood.h>
#include <string_view>
namespace vuk {
struct ContextImpl {
template<class T>
struct FN {
static T create_fn(void* ctx, const create_info_t<T>& ci) {
return reinterpret_cast<Context*>(ctx)->create(ci);
}
static void destroy_fn(void* ctx, const T& v) {
return reinterpret_cast<Context*>(ctx)->destroy(v);
}
};
VkDevice device;
std::unique_ptr<DeviceVkResource> device_vk_resource;
Allocator direct_allocator;
Cache<PipelineBaseInfo> pipelinebase_cache;
Cache<DescriptorPool> pool_cache;
Cache<Sampler> sampler_cache;
Cache<ShaderModule> shader_modules;
Cache<DescriptorSetLayoutAllocInfo> descriptor_set_layouts;
Cache<VkPipelineLayout> pipeline_layouts;
std::mutex begin_frame_lock;
std::atomic<size_t> frame_counter = 0;
std::atomic<size_t> unique_handle_id_counter = 0;
std::mutex named_pipelines_lock;
robin_hood::unordered_flat_map<Name, PipelineBaseInfo*> named_pipelines;
std::atomic<uint64_t> query_id_counter = 0;
VkPhysicalDeviceProperties physical_device_properties;
std::mutex swapchains_lock;
plf::colony<Swapchain> swapchains;
std::mutex query_lock;
robin_hood::unordered_map<Query, uint64_t> timestamp_result_map;
void collect(uint64_t absolute_frame) {
// collect rarer resources
static constexpr uint32_t cache_collection_frequency = 16;
auto remainder = absolute_frame % cache_collection_frequency;
switch (remainder) {
/*case 3:
ptc.impl->sampler_cache.collect(cache_collection_frequency); break;*/ // sampler cache can't be collected due to persistent descriptor sets
case 4:
pipeline_layouts.collect(absolute_frame, cache_collection_frequency);
break;
/* case 5:
pipelinebase_cache.collect(absolute_frame, cache_collection_frequency);
break;*/ // can't be collected since we keep the pointer around in PipelineInfos
case 6:
pool_cache.collect(absolute_frame, cache_collection_frequency);
break;
}
}
ContextImpl(Context& ctx) :
device(ctx.device),
device_vk_resource(std::make_unique<DeviceVkResource>(ctx)),
direct_allocator(*device_vk_resource.get()),
pipelinebase_cache(&ctx, &FN<struct PipelineBaseInfo>::create_fn, &FN<struct PipelineBaseInfo>::destroy_fn),
pool_cache(&ctx, &FN<struct DescriptorPool>::create_fn, &FN<struct DescriptorPool>::destroy_fn),
sampler_cache(&ctx, &FN<Sampler>::create_fn, &FN<Sampler>::destroy_fn),
shader_modules(&ctx, &FN<struct ShaderModule>::create_fn, &FN<struct ShaderModule>::destroy_fn),
descriptor_set_layouts(&ctx, &FN<struct DescriptorSetLayoutAllocInfo>::create_fn, &FN<struct DescriptorSetLayoutAllocInfo>::destroy_fn),
pipeline_layouts(&ctx, &FN<VkPipelineLayout>::create_fn, &FN<VkPipelineLayout>::destroy_fn) {
ctx.vkGetPhysicalDeviceProperties(ctx.physical_device, &physical_device_properties);
}
};
} // namespace vuk
<file_sep>#pragma once
#include "vuk/Config.hpp"
#include <GLFW/glfw3.h>
inline GLFWwindow* create_window_glfw(const char* title, bool resize = true) {
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
if (!resize)
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
return glfwCreateWindow(1024, 1024, title, NULL, NULL);
}
inline void destroy_window_glfw(GLFWwindow* window) {
glfwDestroyWindow(window);
glfwTerminate();
}
inline VkSurfaceKHR create_surface_glfw(VkInstance instance, GLFWwindow* window) {
VkSurfaceKHR surface = nullptr;
VkResult err = glfwCreateWindowSurface(instance, window, NULL, &surface);
if (err) {
const char* error_msg;
int ret = glfwGetError(&error_msg);
if (ret != 0) {
throw error_msg;
}
surface = nullptr;
}
return surface;
}
<file_sep>#pragma once
#include "vuk/Allocator.hpp"
#include "vuk/Config.hpp"
namespace vuk {
/// @brief Device resource that performs direct allocation from the resources from the Vulkan runtime.
struct DeviceVkResource final : DeviceResource {
DeviceVkResource(Context& ctx);
~DeviceVkResource();
Result<void, AllocateException> allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) override;
void deallocate_semaphores(std::span<const VkSemaphore> src) override;
Result<void, AllocateException> allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) override;
void deallocate_fences(std::span<const VkFence> src) override;
Result<void, AllocateException> allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_command_buffers(std::span<const CommandBufferAllocation> dst) override;
Result<void, AllocateException>
allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_command_pools(std::span<const CommandPool> src) override;
Result<void, AllocateException> allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_buffers(std::span<const Buffer> src) override;
Result<void, AllocateException>
allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_framebuffers(std::span<const VkFramebuffer> src) override;
Result<void, AllocateException> allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_images(std::span<const Image> src) override;
Result<void, AllocateException>
allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_image_views(std::span<const ImageView> src) override;
Result<void, AllocateException> allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) override;
Result<void, AllocateException>
allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) override;
Result<void, AllocateException>
allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_descriptor_sets(std::span<const DescriptorSet> src) override;
Result<void, AllocateException>
allocate_descriptor_pools(std::span<VkDescriptorPool> dst, std::span<const VkDescriptorPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_descriptor_pools(std::span<const VkDescriptorPool> src) override;
Result<void, AllocateException>
allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst, std::span<const VkQueryPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) override;
Result<void, AllocateException>
allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_timestamp_queries(std::span<const TimestampQuery> src) override; // no-op, deallocate pools
Result<void, AllocateException> allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) override;
void deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) override;
Result<void, AllocateException> allocate_acceleration_structures(std::span<VkAccelerationStructureKHR> dst,
std::span<const VkAccelerationStructureCreateInfoKHR> cis,
SourceLocationAtFrame loc) override;
void deallocate_acceleration_structures(std::span<const VkAccelerationStructureKHR> src) override;
void deallocate_swapchains(std::span<const VkSwapchainKHR> src) override;
Result<void, AllocateException> allocate_graphics_pipelines(std::span<GraphicsPipelineInfo> dst,
std::span<const GraphicsPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_graphics_pipelines(std::span<const GraphicsPipelineInfo> src) override;
Result<void, AllocateException>
allocate_compute_pipelines(std::span<ComputePipelineInfo> dst, std::span<const ComputePipelineInstanceCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_compute_pipelines(std::span<const ComputePipelineInfo> src) override;
Result<void, AllocateException> allocate_ray_tracing_pipelines(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_ray_tracing_pipelines(std::span<const RayTracingPipelineInfo> src) override;
Result<void, AllocateException>
allocate_render_passes(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_render_passes(std::span<const VkRenderPass> src) override;
Context& get_context() override {
return *ctx;
}
Context* ctx;
VkDevice device;
private:
struct DeviceVkResourceImpl* impl;
};
} // namespace vuk<file_sep>.. vuk documentation master file, created by
sphinx-quickstart on Thu Dec 3 19:06:20 2020.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to vuk's documentation!
===============================
Quickstart
==========
1. Grab the vuk repository
2. Compile the examples
3. Run the example browser and get a feel for the library::
git clone http://github.com/martty/vuk
cd vuk
git submodule init
git submodule update --recursive
mkdir build
cd build
mkdir debug
cd debug
cmake ../.. -G Ninja
cmake --build .
./vuk_all_examples
(if building with a multi-config generator, do not make the `debug` folder)
.. toctree::
:maxdepth: 2
:caption: Topics:
topics/context
topics/allocators
topics/rendergraph
topics/commandbuffer
Background
==========
vuk was initially conceived based on the rendergraph articles of themaister (https://themaister.net/blog/2017/08/15/render-graphs-and-vulkan-a-deep-dive/). In essence the idea is to describe work undertaken during a frame in advance in a high level manner, then the library takes care of low-level details, such as insertion of synchronization (barriers) and managing resource states (image layouts). This over time evolved to a somewhat complete Vulkan runtime - you can use the facilities afforded by vuk's runtime without even using the rendergraph part. The runtime presents a more easily approachable interface to Vulkan, abstracting over common pain points of pipeline management, state setting and descriptors. The rendergraph part has grown to become more powerful than simple 'autosync' abstraction - it allows expressing complex dependencies via `vuk::Future` and allows powerful optimisation opportunities for the backend (even if those are to be implemented).
Alltogether vuk presents a vision of GPU development that embraces compilation - the idea that knowledge about optimisation of programs can be encoded into to tools (compilers) and this way can be insitutionalised, which allows a broader range of programs and programmers to take advantage of these. The future developments will focus on this backend(Vulkan, DX12, etc.)-agnostic form of representing graphics programs and their optimisation.
As such vuk is in active development, and will change in API and behaviour as we better understand the shape of the problem. With that being said, vuk is already usable to base projects off of - with the occasional refactoring. For support or feedback, please join the Discord server or use Github issues - we would be very happy to hear your thoughts!
Indices and tables
==================
* :ref:`genindex`
<file_sep>#pragma once
#include "Cache.hpp"
#include "CreateInfo.hpp"
#include "vuk/Image.hpp"
#include "vuk/ShortAlloc.hpp"
#include "vuk/Types.hpp"
#include "vuk/vuk_fwd.hpp"
#include <optional>
#include <tuple>
#include <vector>
inline bool operator==(VkAttachmentDescription const& lhs, VkAttachmentDescription const& rhs) noexcept {
return (lhs.flags == rhs.flags) && (lhs.format == rhs.format) && (lhs.samples == rhs.samples) && (lhs.loadOp == rhs.loadOp) && (lhs.storeOp == rhs.storeOp) &&
(lhs.stencilLoadOp == rhs.stencilLoadOp) && (lhs.stencilStoreOp == rhs.stencilStoreOp) && (lhs.initialLayout == rhs.initialLayout) &&
(lhs.finalLayout == rhs.finalLayout);
}
inline bool operator==(VkSubpassDependency const& lhs, VkSubpassDependency const& rhs) noexcept {
return (lhs.srcSubpass == rhs.srcSubpass) && (lhs.dstSubpass == rhs.dstSubpass) && (lhs.srcStageMask == rhs.srcStageMask) &&
(lhs.dstStageMask == rhs.dstStageMask) && (lhs.srcAccessMask == rhs.srcAccessMask) && (lhs.dstAccessMask == rhs.dstAccessMask) &&
(lhs.dependencyFlags == rhs.dependencyFlags);
}
inline bool operator==(VkAttachmentReference const& lhs, VkAttachmentReference const& rhs) noexcept {
return (lhs.attachment == rhs.attachment) && (lhs.layout == rhs.layout);
}
namespace vuk {
struct SubpassDescription : public VkSubpassDescription {
SubpassDescription() : VkSubpassDescription{} {}
bool operator==(const SubpassDescription& o) const noexcept {
return std::tie(flags, pipelineBindPoint) == std::tie(o.flags, o.pipelineBindPoint);
}
};
struct RenderPassCreateInfo : public VkRenderPassCreateInfo {
RenderPassCreateInfo() : VkRenderPassCreateInfo{ .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO } {}
std::vector<VkAttachmentDescription> attachments;
std::vector<vuk::SubpassDescription> subpass_descriptions;
std::vector<VkSubpassDependency> subpass_dependencies;
std::vector<VkAttachmentReference> color_refs;
std::vector<VkAttachmentReference> resolve_refs;
std::vector<std::optional<VkAttachmentReference>> ds_refs;
std::vector<size_t> color_ref_offsets;
bool operator==(const RenderPassCreateInfo& o) const noexcept {
return std::forward_as_tuple(flags, attachments, subpass_descriptions, subpass_dependencies, color_refs, color_ref_offsets, ds_refs, resolve_refs) ==
std::forward_as_tuple(
o.flags, o.attachments, o.subpass_descriptions, o.subpass_dependencies, o.color_refs, o.color_ref_offsets, o.ds_refs, o.resolve_refs);
}
};
template<>
struct create_info<VkRenderPass> {
using type = vuk::RenderPassCreateInfo;
};
struct FramebufferCreateInfo : public VkFramebufferCreateInfo {
FramebufferCreateInfo() : VkFramebufferCreateInfo{ .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO } {}
std::vector<vuk::ImageView> attachments;
vuk::Samples sample_count = vuk::Samples::eInfer;
bool operator==(const FramebufferCreateInfo& o) const noexcept {
return std::tie(flags, attachments, width, height, renderPass, layers, sample_count) ==
std::tie(o.flags, o.attachments, o.width, o.height, o.renderPass, o.layers, o.sample_count);
}
};
template<>
struct create_info<VkFramebuffer> {
using type = vuk::FramebufferCreateInfo;
};
} // namespace vuk
namespace std {
template<>
struct hash<vuk::SubpassDescription> {
size_t operator()(vuk::SubpassDescription const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.flags, x.pipelineBindPoint);
return h;
}
};
template<>
struct hash<vuk::RenderPassCreateInfo> {
size_t operator()(vuk::RenderPassCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.flags, x.attachments, x.color_refs, x.color_ref_offsets, x.ds_refs, x.subpass_dependencies, x.subpass_descriptions);
return h;
}
};
template<>
struct hash<vuk::FramebufferCreateInfo> {
size_t operator()(vuk::FramebufferCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.flags, x.attachments, x.width, x.height, x.layers);
return h;
}
};
} // namespace std
<file_sep>#pragma once
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/CommandBuffer.hpp"
#include "vuk/Future.hpp"
#include "vuk/RenderGraph.hpp"
#include "vuk/SourceLocation.hpp"
#include <math.h>
#include <span>
namespace vuk {
/// @brief Fill a buffer with host data
/// @param allocator Allocator to use for temporary allocations
/// @param copy_domain The domain where the copy should happen (when dst is mapped, the copy happens on host)
/// @param buffer Buffer to fill
/// @param src_data pointer to source data
/// @param size size of source data
inline Future host_data_to_buffer(Allocator& allocator, DomainFlagBits copy_domain, Buffer dst, const void* src_data, size_t size) {
// host-mapped buffers just get memcpys
if (dst.mapped_ptr) {
memcpy(dst.mapped_ptr, src_data, size);
return { std::move(dst) };
}
auto src = *allocate_buffer(allocator, BufferCreateInfo{ MemoryUsage::eCPUonly, size, 1 });
::memcpy(src->mapped_ptr, src_data, size);
std::shared_ptr<RenderGraph> rgp = std::make_shared<RenderGraph>("host_data_to_buffer");
rgp->add_pass({ .name = "BUFFER UPLOAD",
.execute_on = copy_domain,
.resources = { "_dst"_buffer >> vuk::Access::eTransferWrite, "_src"_buffer >> vuk::Access::eTransferRead },
.execute = [size](vuk::CommandBuffer& command_buffer) {
command_buffer.copy_buffer("_src", "_dst", size);
} });
rgp->attach_buffer("_src", *src, vuk::Access::eNone);
rgp->attach_buffer("_dst", dst, vuk::Access::eNone);
return { std::move(rgp), "_dst+" };
}
/// @brief Fill a buffer with host data
/// @param allocator Allocator to use for temporary allocations
/// @param copy_domain The domain where the copy should happen (when dst is mapped, the copy happens on host)
/// @param dst Buffer to fill
/// @param data source data
template<class T>
Future host_data_to_buffer(Allocator& allocator, DomainFlagBits copy_domain, Buffer dst, std::span<T> data) {
return host_data_to_buffer(allocator, copy_domain, dst, data.data(), data.size_bytes());
}
/// @brief Download a buffer to GPUtoCPU memory
/// @param buffer_src Buffer to download
inline Future download_buffer(Future buffer_src) {
std::shared_ptr<RenderGraph> rgp = std::make_shared<RenderGraph>("download_buffer");
rgp->attach_in("src", std::move(buffer_src));
rgp->attach_buffer("dst", Buffer{ .memory_usage = MemoryUsage::eGPUtoCPU });
rgp->inference_rule("dst", same_size_as("src"));
rgp->add_pass(
{ .name = "copy", .resources = { "src"_buffer >> eTransferRead, "dst"_buffer >> eTransferWrite }, .execute = [](vuk::CommandBuffer& command_buffer) {
command_buffer.copy_buffer("src", "dst", VK_WHOLE_SIZE);
} });
return { rgp, "dst+" };
}
/// @brief Fill an image with host data
/// @param allocator Allocator to use for temporary allocations
/// @param copy_domain The domain where the copy should happen (when dst is mapped, the copy happens on host)
/// @param image ImageAttachment to fill
/// @param src_data pointer to source data
inline Future host_data_to_image(Allocator& allocator, DomainFlagBits copy_domain, ImageAttachment image, const void* src_data) {
size_t alignment = format_to_texel_block_size(image.format);
assert(image.extent.sizing == Sizing::eAbsolute);
size_t size = compute_image_size(image.format, static_cast<Extent3D>(image.extent.extent));
auto src = *allocate_buffer(allocator, BufferCreateInfo{ MemoryUsage::eCPUonly, size, alignment });
::memcpy(src->mapped_ptr, src_data, size);
BufferImageCopy bc;
bc.imageOffset = { 0, 0, 0 };
bc.bufferRowLength = 0;
bc.bufferImageHeight = 0;
bc.imageExtent = static_cast<Extent3D>(image.extent.extent);
bc.imageSubresource.aspectMask = format_to_aspect(image.format);
bc.imageSubresource.mipLevel = image.base_level;
bc.imageSubresource.baseArrayLayer = image.base_layer;
assert(image.layer_count == 1); // unsupported yet
bc.imageSubresource.layerCount = image.layer_count;
std::shared_ptr<RenderGraph> rgp = std::make_shared<RenderGraph>("host_data_to_image");
rgp->add_pass({ .name = "IMAGE UPLOAD",
.execute_on = copy_domain,
.resources = { "_dst"_image >> vuk::Access::eTransferWrite, "_src"_buffer >> vuk::Access::eTransferRead },
.execute = [bc](vuk::CommandBuffer& command_buffer) {
command_buffer.copy_buffer_to_image("_src", "_dst", bc);
} });
rgp->attach_buffer("_src", *src, vuk::Access::eNone);
rgp->attach_image("_dst", image, vuk::Access::eNone);
return { std::move(rgp), "_dst+" };
}
/// @brief Transition image for given access - useful to force certain access across different RenderGraphs linked by Futures
/// @param image input Future of ImageAttachment
/// @param dst_access Access to have in the future
inline Future transition(Future image, Access dst_access) {
std::shared_ptr<RenderGraph> rgp = std::make_shared<RenderGraph>("transition");
rgp->add_pass({ .name = "TRANSITION",
.execute_on = DomainFlagBits::eDevice,
.resources = { "_src"_image >> dst_access >> "_src+" },
.type = PassType::eForcedAccess });
rgp->attach_in("_src", std::move(image));
return { std::move(rgp), "_src+" };
}
/// @brief Generate mips for given ImageAttachment
/// @param image input Future of ImageAttachment
/// @param base_mip source mip level
/// @param num_mips number of mip levels to generate
inline Future generate_mips(Future image, uint32_t base_mip, uint32_t num_mips) {
std::shared_ptr<RenderGraph> rgp = std::make_shared<RenderGraph>("generate_mips");
rgp->attach_in("_src", std::move(image));
Name mip = Name("_mip_");
std::vector<Name> diverged_names;
for (uint32_t miplevel = base_mip; miplevel < (base_mip + num_mips); miplevel++) {
Name div_name = mip.append(std::to_string(miplevel));
if (miplevel != base_mip) {
diverged_names.push_back(div_name.append("+"));
} else {
diverged_names.push_back(div_name);
}
rgp->diverge_image("_src", { .base_level = miplevel, .level_count = 1 }, div_name);
}
for (uint32_t miplevel = base_mip + 1; miplevel < (base_mip + num_mips); miplevel++) {
uint32_t dmiplevel = miplevel - base_mip;
Name mip_src_name = mip.append(std::to_string(miplevel - 1));
auto mip_dst = std::to_string(miplevel);
Name mip_dst_name = mip.append(std::to_string(miplevel));
if (miplevel != base_mip + 1) {
mip_src_name = mip_src_name.append("+");
}
Resource src_res(mip_src_name, Resource::Type::eImage, Access::eTransferRead);
Resource dst_res(mip_dst_name, Resource::Type::eImage, Access::eTransferWrite, mip_dst_name.append("+"));
rgp->add_pass({ .name = Name("MIP").append(mip_dst),
.execute_on = DomainFlagBits::eGraphicsOnGraphics,
.resources = { src_res, dst_res },
.execute = [mip_src_name, mip_dst_name, dmiplevel, miplevel](CommandBuffer& command_buffer) {
ImageBlit blit;
auto src_ia = *command_buffer.get_resource_image_attachment(mip_src_name);
auto dim = src_ia.extent;
assert(dim.sizing == Sizing::eAbsolute);
auto extent = dim.extent;
blit.srcSubresource.aspectMask = format_to_aspect(src_ia.format);
blit.srcSubresource.baseArrayLayer = src_ia.base_layer;
blit.srcSubresource.layerCount = src_ia.layer_count;
blit.srcSubresource.mipLevel = miplevel - 1;
blit.srcOffsets[0] = Offset3D{ 0 };
blit.srcOffsets[1] = Offset3D{ std::max((int32_t)extent.width >> (dmiplevel - 1), 1),
std::max((int32_t)extent.height >> (dmiplevel - 1), 1),
(int32_t)1 };
blit.dstSubresource = blit.srcSubresource;
blit.dstSubresource.mipLevel = miplevel;
blit.dstOffsets[0] = Offset3D{ 0 };
blit.dstOffsets[1] =
Offset3D{ std::max((int32_t)extent.width >> (dmiplevel), 1), std::max((int32_t)extent.height >> (dmiplevel), 1), (int32_t)1 };
command_buffer.blit_image(mip_src_name, mip_dst_name, blit, Filter::eLinear);
} });
}
rgp->converge_image_explicit(diverged_names, "_src+");
return { std::move(rgp), "_src+" };
}
/// @brief Allocates & fills a buffer with explicitly managed lifetime
/// @param allocator Allocator to allocate this Buffer from
/// @param mem_usage Where to allocate the buffer (host visible buffers will be automatically mapped)
template<class T>
std::pair<Unique<Buffer>, Future> create_buffer(Allocator& allocator, vuk::MemoryUsage memory_usage, DomainFlagBits domain, std::span<T> data, size_t alignment = 1) {
Unique<Buffer> buf(allocator);
BufferCreateInfo bci{ memory_usage, sizeof(T) * data.size(), alignment };
auto ret = allocator.allocate_buffers(std::span{ &*buf, 1 }, std::span{ &bci, 1 }); // TODO: dropping error
Buffer b = buf.get();
return { std::move(buf), host_data_to_buffer(allocator, domain, b, data) };
}
/// @brief Allocates & fills an image, creates default ImageView for it (legacy)
/// @param allocator Allocator to allocate this Texture from
/// @param format Format of the image
/// @param extent Extent3D of the image
/// @param data pointer to data to fill the image with
/// @param should_generate_mips if true, all mip levels are generated from the 0th level
inline std::pair<Texture, Future> create_texture(Allocator& allocator, Format format, Extent3D extent, void* data, bool should_generate_mips, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
ImageCreateInfo ici;
ici.format = format;
ici.extent = extent;
ici.samples = Samples::e1;
ici.initialLayout = ImageLayout::eUndefined;
ici.tiling = ImageTiling::eOptimal;
ici.usage = ImageUsageFlagBits::eTransferSrc | ImageUsageFlagBits::eTransferDst | ImageUsageFlagBits::eSampled;
ici.mipLevels = should_generate_mips ? (uint32_t)log2f((float)std::max(extent.width, extent.height)) + 1 : 1;
ici.arrayLayers = 1;
auto tex = allocator.get_context().allocate_texture(allocator, ici, loc);
auto upload_fut = host_data_to_image(allocator, DomainFlagBits::eTransferQueue, ImageAttachment::from_texture(tex), data);
auto mipgen_fut = ici.mipLevels > 1 ? generate_mips(std::move(upload_fut), 0, ici.mipLevels) : std::move(upload_fut);
std::shared_ptr<RenderGraph> rgp = std::make_shared<RenderGraph>("create_texture");
rgp->add_pass({ .name = "TRANSITION",
.execute_on = DomainFlagBits::eGraphicsQueue,
.resources = { "_src"_image >> Access::eFragmentSampled >> "_src+" },
.type = PassType::eForcedAccess });
rgp->attach_in("_src", std::move(mipgen_fut));
auto on_gfx = Future{ std::move(rgp), "_src+" };
return { std::move(tex), std::move(on_gfx) };
}
} // namespace vuk
<file_sep>#include <filesystem>
#include <fmt/format.h>
#include <fstream>
#include <shaderc/shaderc.hpp>
#include <sstream>
namespace vuk {
/// @brief This default includer will look in the current working directory of the app and relative to the includer file to resolve includes
class ShadercDefaultIncluder : public shaderc::CompileOptions::IncluderInterface {
struct IncludeData {
std::string source;
std::string content;
};
std::filesystem::path base_path = std::filesystem::current_path();
public:
// Handles shaderc_include_resolver_fn callbacks.
shaderc_include_result* GetInclude(const char* requested_source, shaderc_include_type type, const char* requesting_source, size_t include_depth) override {
auto data = new IncludeData;
auto path = base_path / requested_source;
auto alternative_path = std::filesystem::absolute(std::filesystem::path(requesting_source).remove_filename() / requested_source);
std::ostringstream buf;
if (std::ifstream input(path); input) {
buf << input.rdbuf();
data->content = buf.str();
data->source = path.string();
} else if (input = std::ifstream(alternative_path); input) {
buf << input.rdbuf();
data->content = buf.str();
data->source = alternative_path.string();
} else {
data->content = fmt::format("file could not be read (tried: {}; {})", path.string().c_str(), alternative_path.string().c_str());
}
shaderc_include_result* result = new shaderc_include_result;
result->user_data = data;
result->source_name = data->source.c_str();
result->source_name_length = data->source.size();
result->content = data->content.c_str();
result->content_length = data->content.size();
return result;
}
// Handles shaderc_include_result_release_fn callbacks.
void ReleaseInclude(shaderc_include_result* data) override {
delete static_cast<IncludeData*>(data->user_data);
delete data;
}
};
} // namespace vuk<file_sep>#include "example_runner.hpp"
#include <algorithm>
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
#include <numeric>
#include <optional>
#include <random>
#include <stb_image.h>
/* 09_persistent_descriptorset
* In this example we will see how to create persistent descriptorsets.
* Normal descriptorsets are completely managed by vuk, and are cached based on their contents.
* However, this behaviour is not helpful if you plan to keep the descriptorsets around, or if they have many elements (such as "bindless").
* For these scenarios, you can create and explicitly manage descriptorsets.
* Here we first generate two additional textures from the one we load: the first by Y flipping using blitting and the second by
* running a compute shader on it. Afterwards we create the persistent set and write the three images into it.
* Later, we draw three cubes and fetch the texture based on the base instance.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
// The Y rotation angle of our cube
float angle = 0.f;
// Generate vertices and indices for the cube
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
std::optional<vuk::Texture> texture_of_doge, variant1, variant2;
vuk::Unique<vuk::PersistentDescriptorSet> pda;
vuk::Example xample{
.name = "09_persistent_descriptorset",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
vuk::Context& ctx = allocator.get_context();
{
vuk::PipelineBaseCreateInfo pci;
pci.add_glsl(util::read_entire_file((root / "examples/bindless.vert").generic_string()), (root / "examples/bindless.vert").generic_string());
pci.add_glsl(util::read_entire_file((root / "examples/triangle_tex_bindless.frag").generic_string()), (root / "examples/triangle_tex_bindless.frag").generic_string());
// Flag this binding as partially bound, so that we don't need to set all the array elements
pci.set_binding_flags(1, 0, vuk::DescriptorBindingFlagBits::ePartiallyBound);
// Set the binding #0 in set #1 as a variable count binding, and set the maximum number of descriptors
pci.set_variable_count_binding(1, 0, 1024);
runner.context->create_named_pipeline("bindless_cube", pci);
}
// creating a compute pipeline that inverts an image
{
vuk::PipelineBaseCreateInfo pbci;
pbci.add_glsl(util::read_entire_file((root / "examples/invert.comp").generic_string()), "examples/invert.comp");
runner.context->create_named_pipeline("invert", pbci);
}
// Use STBI to load the image
int x, y, chans;
auto doge_image = stbi_load((root / "examples/doge.png").generic_string().c_str(), &x, &y, &chans, 4);
// Similarly to buffers, we allocate the image and enqueue the upload
auto [tex, tex_fut] = create_texture(allocator, vuk::Format::eR8G8B8A8Srgb, vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u }, doge_image, false);
texture_of_doge = std::move(tex);
stbi_image_free(doge_image);
// We set up the cube data, same as in example 02_cube
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
// For the example, we just ask these that these uploads complete before moving on to rendering
// In an engine, you would integrate these uploads into some explicit system
runner.enqueue_setup(std::move(vert_fut));
runner.enqueue_setup(std::move(ind_fut));
// Let's create two variants of the doge image
vuk::ImageCreateInfo ici;
ici.format = vuk::Format::eR8G8B8A8Srgb;
ici.extent = vuk::Extent3D{ (unsigned)x, (unsigned)y, 1 };
ici.samples = vuk::Samples::e1;
ici.imageType = vuk::ImageType::e2D;
ici.initialLayout = vuk::ImageLayout::eUndefined;
ici.tiling = vuk::ImageTiling::eOptimal;
ici.usage = vuk::ImageUsageFlagBits::eTransferDst | vuk::ImageUsageFlagBits::eSampled;
ici.mipLevels = ici.arrayLayers = 1;
variant1 = ctx.allocate_texture(allocator, ici);
ici.format = vuk::Format::eR8G8B8A8Unorm;
ici.usage = vuk::ImageUsageFlagBits::eStorage | vuk::ImageUsageFlagBits::eSampled;
variant2 = ctx.allocate_texture(allocator, ici);
// Make a RenderGraph to process the loaded image
vuk::RenderGraph rg("PP");
rg.add_pass({ .name = "preprocess",
.resources = { "09_doge"_image >> (vuk::eTransferRead | vuk::eComputeSampled),
"09_v1"_image >> vuk::eTransferWrite,
"09_v2"_image >> vuk::eComputeWrite },
.execute = [x, y](vuk::CommandBuffer& command_buffer) {
// For the first image, flip the image on the Y axis using a blit
vuk::ImageBlit blit;
blit.srcSubresource.aspectMask = vuk::ImageAspectFlagBits::eColor;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.srcSubresource.mipLevel = 0;
blit.srcOffsets[0] = vuk::Offset3D{ 0, 0, 0 };
blit.srcOffsets[1] = vuk::Offset3D{ x, y, 1 };
blit.dstSubresource = blit.srcSubresource;
blit.dstOffsets[0] = vuk::Offset3D{ x, y, 0 };
blit.dstOffsets[1] = vuk::Offset3D{ 0, 0, 1 };
command_buffer.blit_image("09_doge", "09_v1", blit, vuk::Filter::eLinear);
// For the second image, invert the colours in compute
command_buffer.bind_image(0, 0, "09_doge")
.bind_sampler(0, 0, {})
.bind_image(0, 1, "09_v2")
.bind_compute_pipeline("invert")
.dispatch_invocations(x, y);
} });
// Bind the resources for the variant generation
// We specify the initial and final access
// The texture we have created is already in ShaderReadOptimal, but we need it in General during the pass, and we need it back to ShaderReadOptimal
// afterwards
rg.attach_in("09_doge", std::move(tex_fut));
rg.attach_image("09_v1", vuk::ImageAttachment::from_texture(*variant1), vuk::eNone);
rg.release("09_v1+", vuk::eFragmentSampled);
rg.attach_image("09_v2", vuk::ImageAttachment::from_texture(*variant2), vuk::eNone);
rg.release("09_v2+", vuk::eFragmentSampled);
// enqueue running the preprocessing rendergraph and force 09_doge to be sampleable later
auto fut = vuk::transition(vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "09_doge" }, vuk::eFragmentSampled);
runner.enqueue_setup(std::move(fut));
// Create persistent descriptorset for a pipeline and set index
pda = ctx.create_persistent_descriptorset(allocator, *runner.context->get_named_pipeline("bindless_cube"), 1, 64);
vuk::Sampler default_sampler = ctx.acquire_sampler({}, ctx.get_frame_count());
// Enqueue updates to the descriptors in the array
// This records the writes internally, but does not execute them
// Updating can be done in parallel from different threads, only the commit call has to be synchronized
pda->update_combined_image_sampler(0, 0, texture_of_doge->view.get(), default_sampler, vuk::ImageLayout::eReadOnlyOptimalKHR);
pda->update_combined_image_sampler(0, 1, variant1->view.get(), default_sampler, vuk::ImageLayout::eReadOnlyOptimalKHR);
pda->update_combined_image_sampler(0, 2, variant2->view.get(), default_sampler, vuk::ImageLayout::eReadOnlyOptimalKHR);
// Execute the writes
pda->commit(ctx);
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
vp.view = glm::lookAt(glm::vec3(0, 1.5, 3.5), glm::vec3(0), glm::vec3(0, 1, 0));
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 1.f, 10.f);
vp.proj[1][1] *= -1;
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
vuk::RenderGraph rg("09");
rg.attach_in("09_persistent_descriptorset", std::move(target));
// Set up the pass to draw the textured cube, with a color and a depth attachment
rg.add_pass({ .name = "forward",
.resources = { "09_persistent_descriptorset"_image >> vuk::eColorWrite >> "09_persistent_descriptorset_final",
"09_depth"_image >> vuk::eDepthStencilRW },
.execute = [uboVP](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
.depthWriteEnable = true,
.depthCompareOp = vuk::CompareOp::eLessOrEqual,
})
.broadcast_color_blend({}) // Set the default color blend state
.bind_vertex_buffer(0,
*verts,
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat,
vuk::Ignore{ offsetof(util::Vertex, uv_coordinates) - sizeof(util::Vertex::position) },
vuk::Format::eR32G32Sfloat })
.bind_index_buffer(*inds, vuk::IndexType::eUint32)
.bind_persistent(1, pda.get())
.bind_graphics_pipeline("bindless_cube")
.bind_buffer(0, 0, uboVP);
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = static_cast<glm::mat4>(glm::angleAxis(glm::radians(angle), glm::vec3(0.f, 1.f, 0.f)));
// Draw 3 cubes, assign them different base instance to identify them in the shader
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0)
.draw_indexed(box.second.size(), 1, 0, 0, 1)
.draw_indexed(box.second.size(), 1, 0, 0, 2);
} });
angle += 10.f * ImGui::GetIO().DeltaTime;
rg.attach_and_clear_image("09_depth", { .format = vuk::Format::eD32Sfloat }, vuk::ClearDepthStencil{ 1.0f, 0 });
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "09_persistent_descriptorset_final" };
},
// Perform cleanup for the example
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
// We release the resources manually
verts.reset();
inds.reset();
texture_of_doge.reset();
variant1.reset();
variant2.reset();
pda.reset();
}
};
REGISTER_EXAMPLE(xample);
} // namespace<file_sep>#pragma once
#include "vuk/Buffer.hpp"
#include "vuk/Config.hpp"
#include "vuk/SourceLocation.hpp"
#include "vuk/Types.hpp"
#include <array>
#include <atomic>
#include <memory>
#include <mutex>
#include <utility>
#include <vector>
#include <vk_mem_alloc.h>
#include <plf_colony.h>
namespace vuk {
struct DeviceResource;
struct LinearSegment {
Buffer buffer;
size_t num_blocks;
uint64_t base_address = 0;
};
struct BufferLinearAllocator {
DeviceResource* upstream;
std::mutex mutex;
std::atomic<int> current_buffer = -1;
std::atomic<uint64_t> needle = 0;
MemoryUsage mem_usage;
BufferUsageFlags usage;
// TODO: convert to deque
std::array<LinearSegment, 256> available_allocations; // up to 4 GB of allocations with the default block_size
std::array<LinearSegment, 256> used_allocations; // up to 4 GB of allocations with the default block_size
size_t available_allocation_count = 0;
size_t used_allocation_count = 0;
size_t block_size;
BufferLinearAllocator(DeviceResource& upstream, MemoryUsage mem_usage, BufferUsageFlags buf_usage, size_t block_size = 1024 * 1024 * 16) :
upstream(&upstream),
mem_usage(mem_usage),
usage(buf_usage),
block_size(block_size) {}
~BufferLinearAllocator();
Result<void, AllocateException> grow(size_t num_blocks, SourceLocationAtFrame source);
Result<Buffer, AllocateException> allocate_buffer(size_t size, size_t alignment, SourceLocationAtFrame source);
// trim the amount of memory to the currently used amount
void trim();
// return all resources to available
void reset();
// explicitly release resources
void free();
};
struct BufferBlock {
Buffer buffer = {};
size_t allocation_count = 0;
};
struct SubAllocation {
size_t block_index;
VmaVirtualAllocation allocation;
};
struct BufferSubAllocator {
DeviceResource* upstream;
MemoryUsage mem_usage;
BufferUsageFlags usage;
std::vector<BufferBlock> blocks;
VmaVirtualBlock virtual_alloc;
std::mutex mutex;
size_t block_size;
BufferSubAllocator(DeviceResource& upstream, MemoryUsage mem_usage, BufferUsageFlags buf_usage, size_t block_size);
~BufferSubAllocator();
Result<Buffer, AllocateException> allocate_buffer(size_t size, size_t alignment, SourceLocationAtFrame source);
void deallocate_buffer(const Buffer& buf);
};
}; // namespace vuk
<file_sep>#pragma once
#include "vuk/Allocator.hpp"
#include "vuk/Buffer.hpp"
#include "vuk/Exception.hpp"
#include "vuk/ImageAttachment.hpp"
#include "vuk/Descriptor.hpp"
#include "vuk/Query.hpp"
#include "vuk/SourceLocation.hpp"
namespace vuk {
/// @brief Allocate a single semaphore from an Allocator
/// @param allocator Allocator to use
/// @param loc Source location information
/// @return Semaphore in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<VkSemaphore>, AllocateException> allocate_semaphore(Allocator& allocator, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<VkSemaphore> sema(allocator);
if (auto res = allocator.allocate_semaphores(std::span{ &sema.get(), 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(sema) };
}
/// @brief Allocate a single timeline semaphore from an Allocator
/// @param allocator Allocator to use
/// @param loc Source location information
/// @return Timeline semaphore in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<TimelineSemaphore>, AllocateException> allocate_timeline_semaphore(Allocator& allocator,
SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<TimelineSemaphore> sema(allocator);
if (auto res = allocator.allocate_timeline_semaphores(std::span{ &sema.get(), 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(sema) };
}
/// @brief Allocate a single command pool from an Allocator
/// @param allocator Allocator to use
/// @param cpci Command pool creation parameters
/// @param loc Source location information
/// @return Command pool in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<CommandPool>, AllocateException>
allocate_command_pool(Allocator& allocator, const VkCommandPoolCreateInfo& cpci, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<CommandPool> cp(allocator);
if (auto res = allocator.allocate_command_pools(std::span{ &cp.get(), 1 }, std::span{ &cpci, 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(cp) };
}
/// @brief Allocate a single command buffer from an Allocator
/// @param allocator Allocator to use
/// @param cbci Command buffer creation parameters
/// @param loc Source location information
/// @return Command buffer in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<CommandBufferAllocation>, AllocateException>
allocate_command_buffer(Allocator& allocator, const CommandBufferAllocationCreateInfo& cbci, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<CommandBufferAllocation> hlcb(allocator);
if (auto res = allocator.allocate_command_buffers(std::span{ &hlcb.get(), 1 }, std::span{ &cbci, 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(hlcb) };
}
/// @brief Allocate a single fence from an Allocator
/// @param allocator Allocator to use
/// @param loc Source location information
/// @return Fence in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<VkFence>, AllocateException> allocate_fence(Allocator& allocator, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<VkFence> fence(allocator);
if (auto res = allocator.allocate_fences(std::span{ &fence.get(), 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(fence) };
}
/// @brief Allocate a single GPU-only buffer from an Allocator
/// @param allocator Allocator to use
/// @param bci Buffer creation parameters
/// @param loc Source location information
/// @return GPU-only buffer in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<Buffer>, AllocateException>
allocate_buffer(Allocator& allocator, const BufferCreateInfo& bci, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<Buffer> buf(allocator);
if (auto res = allocator.allocate_buffers(std::span{ &buf.get(), 1 }, std::span{ &bci, 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(buf) };
}
/// @brief Allocate a single image from an Allocator
/// @param allocator Allocator to use
/// @param ici Image creation parameters
/// @param loc Source location information
/// @return Image in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<Image>, AllocateException>
allocate_image(Allocator& allocator, const ImageCreateInfo& ici, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<Image> img(allocator);
if (auto res = allocator.allocate_images(std::span{ &img.get(), 1 }, std::span{ &ici, 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(img) };
}
/// @brief Allocate a single image from an Allocator
/// @param allocator Allocator to use
/// @param attachment ImageAttachment to make the Image from
/// @param loc Source location information
/// @return Image in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<Image>, AllocateException>
allocate_image(Allocator& allocator, const ImageAttachment& attachment, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<Image> img(allocator);
ImageCreateInfo ici;
ici.format = vuk::Format(attachment.format);
ici.imageType = attachment.image_type;
ici.flags = attachment.image_flags;
ici.arrayLayers = attachment.layer_count;
ici.samples = attachment.sample_count.count;
ici.tiling = attachment.tiling;
ici.mipLevels = attachment.level_count;
ici.usage = attachment.usage;
assert(attachment.extent.sizing == Sizing::eAbsolute);
ici.extent = static_cast<vuk::Extent3D>(attachment.extent.extent);
VkImageFormatListCreateInfo listci = { VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO };
if (attachment.allow_srgb_unorm_mutable) {
auto unorm_fmt = srgb_to_unorm(attachment.format);
auto srgb_fmt = unorm_to_srgb(attachment.format);
VkFormat formats[2] = { (VkFormat)attachment.format, unorm_fmt == vuk::Format::eUndefined ? (VkFormat)srgb_fmt : (VkFormat)unorm_fmt };
listci.pViewFormats = formats;
listci.viewFormatCount = formats[1] == VK_FORMAT_UNDEFINED ? 1 : 2;
if (listci.viewFormatCount > 1) {
ici.flags |= vuk::ImageCreateFlagBits::eMutableFormat;
ici.pNext = &listci;
}
}
if (auto res = allocator.allocate_images(std::span{ &img.get(), 1 }, std::span{ &ici, 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(img) };
}
/// @brief Allocate a single image view from an Allocator
/// @param allocator Allocator to use
/// @param ivci Image view creation parameters
/// @param loc Source location information
/// @return ImageView in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<ImageView>, AllocateException>
allocate_image_view(Allocator& allocator, const ImageViewCreateInfo& ivci, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<ImageView> iv(allocator);
if (auto res = allocator.allocate_image_views(std::span{ &iv.get(), 1 }, std::span{ &ivci, 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(iv) };
}
/// @brief Allocate a single image view from an Allocator
/// @param allocator Allocator to use
/// @param attachment ImageAttachment to make the ImageView from
/// @param loc Source location information
/// @return ImageView in a RAII wrapper (Unique<T>) or AllocateException on error
inline Result<Unique<ImageView>, AllocateException>
allocate_image_view(Allocator& allocator, const ImageAttachment& attachment, SourceLocationAtFrame loc = VUK_HERE_AND_NOW()) {
Unique<ImageView> iv(allocator);
ImageViewCreateInfo ivci;
assert(attachment.image);
ivci.flags = attachment.image_view_flags;
ivci.image = attachment.image.image;
ivci.viewType = attachment.view_type;
ivci.format = vuk::Format(attachment.format);
ivci.components = attachment.components;
ivci.view_usage = attachment.usage;
ImageSubresourceRange& isr = ivci.subresourceRange;
isr.aspectMask = format_to_aspect(ivci.format);
isr.baseArrayLayer = attachment.base_layer;
isr.layerCount = attachment.layer_count;
isr.baseMipLevel = attachment.base_level;
isr.levelCount = attachment.level_count;
if (auto res = allocator.allocate_image_views(std::span{ &iv.get(), 1 }, std::span{ &ivci, 1 }, loc); !res) {
return { expected_error, res.error() };
}
return { expected_value, std::move(iv) };
}
} // namespace vuk<file_sep>#pragma once
#include <cassert>
#include "../src/CreateInfo.hpp"
#include "Types.hpp"
namespace vuk {
struct Image {
VkImage image = VK_NULL_HANDLE;
void* allocation = nullptr;
constexpr explicit operator bool() const noexcept {
return image != VK_NULL_HANDLE;
}
constexpr bool operator==(const Image&) const = default;
};
using Sampler = Handle<VkSampler>;
enum class ImageTiling {
eOptimal = VK_IMAGE_TILING_OPTIMAL,
eLinear = VK_IMAGE_TILING_LINEAR,
eDrmFormatModifierEXT = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT
};
enum class ImageType { e1D = VK_IMAGE_TYPE_1D, e2D = VK_IMAGE_TYPE_2D, e3D = VK_IMAGE_TYPE_3D, eInfer };
enum class ImageUsageFlagBits : VkImageUsageFlags {
eTransferSrc = VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
eTransferDst = VK_IMAGE_USAGE_TRANSFER_DST_BIT,
eSampled = VK_IMAGE_USAGE_SAMPLED_BIT,
eStorage = VK_IMAGE_USAGE_STORAGE_BIT,
eColorAttachment = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
eDepthStencilAttachment = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
eTransientAttachment = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT,
eInputAttachment = VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT,
eShadingRateImageNV = VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV,
eFragmentDensityMapEXT = VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT,
eInfer = 1024
};
using ImageUsageFlags = Flags<ImageUsageFlagBits>;
inline constexpr ImageUsageFlags operator|(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept {
return ImageUsageFlags(bit0) | bit1;
}
inline constexpr ImageUsageFlags operator&(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept {
return ImageUsageFlags(bit0) & bit1;
}
inline constexpr ImageUsageFlags operator^(ImageUsageFlagBits bit0, ImageUsageFlagBits bit1) noexcept {
return ImageUsageFlags(bit0) ^ bit1;
}
enum class ImageCreateFlagBits : VkImageCreateFlags {
eSparseBinding = VK_IMAGE_CREATE_SPARSE_BINDING_BIT,
eSparseResidency = VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT,
eSparseAliased = VK_IMAGE_CREATE_SPARSE_ALIASED_BIT,
eMutableFormat = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,
eCubeCompatible = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT,
eAlias = VK_IMAGE_CREATE_ALIAS_BIT,
eSplitInstanceBindRegions = VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT,
e2DArrayCompatible = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT,
eBlockTexelViewCompatible = VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT,
eExtendedUsage = VK_IMAGE_CREATE_EXTENDED_USAGE_BIT,
eProtected = VK_IMAGE_CREATE_PROTECTED_BIT,
eDisjoint = VK_IMAGE_CREATE_DISJOINT_BIT,
eCornerSampledNV = VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV,
eSampleLocationsCompatibleDepthEXT = VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT,
eSubsampledEXT = VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT,
e2DArrayCompatibleKHR = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR,
eAliasKHR = VK_IMAGE_CREATE_ALIAS_BIT_KHR,
eBlockTexelViewCompatibleKHR = VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR,
eDisjointKHR = VK_IMAGE_CREATE_DISJOINT_BIT_KHR,
eExtendedUsageKHR = VK_IMAGE_CREATE_EXTENDED_USAGE_BIT_KHR,
eSplitInstanceBindRegionsKHR = VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR
};
using ImageCreateFlags = Flags<ImageCreateFlagBits>;
inline constexpr ImageCreateFlags operator|(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept {
return ImageCreateFlags(bit0) | bit1;
}
inline constexpr ImageCreateFlags operator&(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept {
return ImageCreateFlags(bit0) & bit1;
}
inline constexpr ImageCreateFlags operator^(ImageCreateFlagBits bit0, ImageCreateFlagBits bit1) noexcept {
return ImageCreateFlags(bit0) ^ bit1;
}
enum class ImageLayout {
eUndefined = VK_IMAGE_LAYOUT_UNDEFINED,
eGeneral = VK_IMAGE_LAYOUT_GENERAL,
eColorAttachmentOptimal = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
eDepthStencilAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
eDepthStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
eShaderReadOnlyOptimal = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
eTransferSrcOptimal = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
eTransferDstOptimal = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
ePreinitialized = VK_IMAGE_LAYOUT_PREINITIALIZED,
eDepthReadOnlyStencilAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL,
eDepthAttachmentStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL,
eDepthAttachmentOptimal = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
eDepthReadOnlyOptimal = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL,
eStencilAttachmentOptimal = VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL,
eStencilReadOnlyOptimal = VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL,
ePresentSrcKHR = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
eSharedPresentKHR = VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR,
eShadingRateOptimalNV = VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV,
eFragmentDensityMapOptimalEXT = VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT,
eDepthAttachmentOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL_KHR,
eDepthAttachmentStencilReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR,
eDepthReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL_KHR,
eDepthReadOnlyStencilAttachmentOptimalKHR = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR,
eStencilAttachmentOptimalKHR = VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR,
eStencilReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL_KHR,
eReadOnlyOptimalKHR = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL_KHR,
eReadOnlyOptimal = VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL,
eAttachmentOptimalKHR = VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR,
eAttachmentOptimal = VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL
};
enum class SharingMode { eExclusive = VK_SHARING_MODE_EXCLUSIVE, eConcurrent = VK_SHARING_MODE_CONCURRENT };
struct ImageCreateInfo {
static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
VkStructureType sType = structureType;
const void* pNext = {};
ImageCreateFlags flags = {};
ImageType imageType = ImageType::e2D;
Format format = Format::eUndefined;
Extent3D extent = {};
uint32_t mipLevels = 1;
uint32_t arrayLayers = 1;
SampleCountFlagBits samples = SampleCountFlagBits::e1;
ImageTiling tiling = ImageTiling::eOptimal;
ImageUsageFlags usage = {};
SharingMode sharingMode = SharingMode::eExclusive;
uint32_t queueFamilyIndexCount = {};
const uint32_t* pQueueFamilyIndices = {};
ImageLayout initialLayout = ImageLayout::eUndefined;
operator VkImageCreateInfo const&() const noexcept {
return *reinterpret_cast<const VkImageCreateInfo*>(this);
}
operator VkImageCreateInfo&() noexcept {
return *reinterpret_cast<VkImageCreateInfo*>(this);
}
bool operator==(ImageCreateInfo const& rhs) const noexcept {
return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (imageType == rhs.imageType) && (format == rhs.format) &&
(extent == rhs.extent) && (mipLevels == rhs.mipLevels) && (arrayLayers == rhs.arrayLayers) && (samples == rhs.samples) && (tiling == rhs.tiling) &&
(usage == rhs.usage) && (sharingMode == rhs.sharingMode) && (queueFamilyIndexCount == rhs.queueFamilyIndexCount) &&
(pQueueFamilyIndices == rhs.pQueueFamilyIndices) && (initialLayout == rhs.initialLayout);
}
};
static_assert(sizeof(ImageCreateInfo) == sizeof(VkImageCreateInfo), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<ImageCreateInfo>::value, "struct wrapper is not a standard layout!");
template<>
struct create_info<Image> {
using type = ImageCreateInfo;
};
struct ImageWithIdentity {
Image image;
};
struct CachedImageIdentifier {
ImageCreateInfo ici;
uint32_t id;
uint32_t multi_frame_index;
bool operator==(const CachedImageIdentifier&) const = default;
};
template<>
struct create_info<ImageWithIdentity> {
using type = CachedImageIdentifier;
};
enum class ImageViewCreateFlagBits : VkImageViewCreateFlags { eFragmentDensityMapDynamicEXT = VK_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT };
enum class ImageViewType : uint32_t {
e1D = VK_IMAGE_VIEW_TYPE_1D,
e2D = VK_IMAGE_VIEW_TYPE_2D,
e3D = VK_IMAGE_VIEW_TYPE_3D,
eCube = VK_IMAGE_VIEW_TYPE_CUBE,
e1DArray = VK_IMAGE_VIEW_TYPE_1D_ARRAY,
e2DArray = VK_IMAGE_VIEW_TYPE_2D_ARRAY,
eCubeArray = VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
eInfer
};
using ImageViewCreateFlags = Flags<ImageViewCreateFlagBits>;
enum class ComponentSwizzle : uint32_t {
eIdentity = VK_COMPONENT_SWIZZLE_IDENTITY,
eZero = VK_COMPONENT_SWIZZLE_ZERO,
eOne = VK_COMPONENT_SWIZZLE_ONE,
eR = VK_COMPONENT_SWIZZLE_R,
eG = VK_COMPONENT_SWIZZLE_G,
eB = VK_COMPONENT_SWIZZLE_B,
eA = VK_COMPONENT_SWIZZLE_A,
eInfer
};
struct ComponentMapping {
ComponentSwizzle r = ComponentSwizzle::eIdentity;
ComponentSwizzle g = ComponentSwizzle::eIdentity;
ComponentSwizzle b = ComponentSwizzle::eIdentity;
ComponentSwizzle a = ComponentSwizzle::eIdentity;
operator VkComponentMapping const&() const noexcept {
return *reinterpret_cast<const VkComponentMapping*>(this);
}
operator VkComponentMapping&() noexcept {
return *reinterpret_cast<VkComponentMapping*>(this);
}
constexpr bool operator==(const ComponentMapping&) const = default;
};
static_assert(sizeof(ComponentMapping) == sizeof(VkComponentMapping), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<ComponentMapping>::value, "struct wrapper is not a standard layout!");
enum class ImageAspectFlagBits : VkImageAspectFlags {
eColor = VK_IMAGE_ASPECT_COLOR_BIT,
eDepth = VK_IMAGE_ASPECT_DEPTH_BIT,
eStencil = VK_IMAGE_ASPECT_STENCIL_BIT,
eMetadata = VK_IMAGE_ASPECT_METADATA_BIT,
ePlane0 = VK_IMAGE_ASPECT_PLANE_0_BIT,
ePlane1 = VK_IMAGE_ASPECT_PLANE_1_BIT,
ePlane2 = VK_IMAGE_ASPECT_PLANE_2_BIT,
eMemoryPlane0EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT,
eMemoryPlane1EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT,
eMemoryPlane2EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT,
eMemoryPlane3EXT = VK_IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT,
ePlane0KHR = VK_IMAGE_ASPECT_PLANE_0_BIT_KHR,
ePlane1KHR = VK_IMAGE_ASPECT_PLANE_1_BIT_KHR,
ePlane2KHR = VK_IMAGE_ASPECT_PLANE_2_BIT_KHR
};
using ImageAspectFlags = Flags<ImageAspectFlagBits>;
inline constexpr ImageAspectFlags operator|(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept {
return ImageAspectFlags(bit0) | bit1;
}
inline constexpr ImageAspectFlags operator&(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept {
return ImageAspectFlags(bit0) & bit1;
}
inline constexpr ImageAspectFlags operator^(ImageAspectFlagBits bit0, ImageAspectFlagBits bit1) noexcept {
return ImageAspectFlags(bit0) ^ bit1;
}
struct ImageSubresourceRange {
ImageAspectFlags aspectMask = {};
uint32_t baseMipLevel = 0;
uint32_t levelCount = 1;
uint32_t baseArrayLayer = 0;
uint32_t layerCount = 1;
operator VkImageSubresourceRange const&() const noexcept {
return *reinterpret_cast<const VkImageSubresourceRange*>(this);
}
operator VkImageSubresourceRange&() noexcept {
return *reinterpret_cast<VkImageSubresourceRange*>(this);
}
bool operator==(ImageSubresourceRange const& rhs) const noexcept {
return (aspectMask == rhs.aspectMask) && (baseMipLevel == rhs.baseMipLevel) && (levelCount == rhs.levelCount) && (baseArrayLayer == rhs.baseArrayLayer) &&
(layerCount == rhs.layerCount);
}
bool operator!=(ImageSubresourceRange const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(sizeof(ImageSubresourceRange) == sizeof(VkImageSubresourceRange), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<ImageSubresourceRange>::value, "struct wrapper is not a standard layout!");
struct ImageViewCreateInfo {
static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
VkStructureType sType = structureType;
const void* pNext = {};
ImageViewCreateFlags flags = {};
VkImage image = {};
ImageViewType viewType = ImageViewType::e2D;
Format format = Format::eUndefined;
ComponentMapping components = {};
ImageSubresourceRange subresourceRange = {};
vuk::ImageUsageFlags view_usage = {}; // added for vuk
operator VkImageViewCreateInfo const&() const noexcept {
return *reinterpret_cast<const VkImageViewCreateInfo*>(this);
}
operator VkImageViewCreateInfo&() noexcept {
return *reinterpret_cast<VkImageViewCreateInfo*>(this);
}
bool operator==(ImageViewCreateInfo const& rhs) const noexcept {
return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (image == rhs.image) && (viewType == rhs.viewType) &&
(format == rhs.format) && (components == rhs.components) && (subresourceRange == rhs.subresourceRange);
}
bool operator!=(ImageViewCreateInfo const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(std::is_standard_layout<ImageViewCreateInfo>::value, "struct wrapper is not a standard layout!");
#pragma pack(push, 1)
struct CompressedImageViewCreateInfo {
uint32_t flags : 2;
ImageViewType viewType : 3 = ImageViewType::e2D;
ComponentSwizzle r_swizzle : 3 = ComponentSwizzle::eIdentity;
ComponentSwizzle g_swizzle : 3 = ComponentSwizzle::eIdentity;
ComponentSwizzle b_swizzle : 3 = ComponentSwizzle::eIdentity;
ComponentSwizzle a_swizzle : 3 = ComponentSwizzle::eIdentity;
uint32_t padding : 4 = 0;
uint32_t aspectMask : 11 = {}; // 27 bits ~ pad to 4 bytes
uint32_t baseMipLevel : 16 = 0;
uint32_t levelCount : 16 = 1;
uint32_t baseArrayLayer : 16 = 0;
uint32_t layerCount : 16 = 1;
VkImageUsageFlags view_usage : 10; // 8 bytes
VkImage image = {}; // 16 bytes
Format format = Format::eUndefined; // 32 bytes in total
CompressedImageViewCreateInfo(ImageViewCreateInfo ivci) {
assert(ivci.pNext == nullptr && "Compression does not support pNextended IVCIs");
flags = ivci.flags.m_mask;
viewType = ivci.viewType;
r_swizzle = ivci.components.r;
g_swizzle = ivci.components.g;
b_swizzle = ivci.components.b;
a_swizzle = ivci.components.a;
aspectMask = ivci.subresourceRange.aspectMask.m_mask;
baseMipLevel = ivci.subresourceRange.baseMipLevel;
levelCount = ivci.subresourceRange.levelCount;
baseArrayLayer = ivci.subresourceRange.baseArrayLayer;
layerCount = ivci.subresourceRange.layerCount;
image = ivci.image;
format = ivci.format;
view_usage = (VkImageUsageFlags)ivci.view_usage;
}
explicit operator ImageViewCreateInfo() const noexcept {
ImageViewCreateInfo ivci;
ivci.flags = (ImageViewCreateFlags)flags;
ivci.viewType = (ImageViewType)viewType;
ivci.components.r = (ComponentSwizzle)r_swizzle;
ivci.components.g = (ComponentSwizzle)g_swizzle;
ivci.components.b = (ComponentSwizzle)b_swizzle;
ivci.components.a = (ComponentSwizzle)a_swizzle;
ivci.subresourceRange = { .aspectMask = (ImageAspectFlags)aspectMask,
.baseMipLevel = baseMipLevel,
.levelCount = levelCount,
.baseArrayLayer = baseArrayLayer,
.layerCount = layerCount };
ivci.image = image;
ivci.format = (Format)format;
ivci.view_usage = (ImageUsageFlags)view_usage;
return ivci;
}
constexpr bool operator==(CompressedImageViewCreateInfo const& rhs) const noexcept = default;
};
#pragma pack(pop)
using ImageView = Handle<VkImageView>;
template<>
struct create_info<ImageView> {
using type = CompressedImageViewCreateInfo;
};
enum class SamplerCreateFlagBits : VkSamplerCreateFlags {
eSubsampledEXT = VK_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT,
eSubsampledCoarseReconstructionEXT = VK_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT
};
using SamplerCreateFlags = Flags<SamplerCreateFlagBits>;
enum class Filter { eNearest = VK_FILTER_NEAREST, eLinear = VK_FILTER_LINEAR, eCubicIMG = VK_FILTER_CUBIC_IMG, eCubicEXT = VK_FILTER_CUBIC_EXT };
enum class SamplerMipmapMode { eNearest = VK_SAMPLER_MIPMAP_MODE_NEAREST, eLinear = VK_SAMPLER_MIPMAP_MODE_LINEAR };
enum class SamplerAddressMode {
eRepeat = VK_SAMPLER_ADDRESS_MODE_REPEAT,
eMirroredRepeat = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT,
eClampToEdge = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
eClampToBorder = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
eMirrorClampToEdge = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE,
eMirrorClampToEdgeKHR = VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE_KHR
};
enum class CompareOp {
eNever = VK_COMPARE_OP_NEVER,
eLess = VK_COMPARE_OP_LESS,
eEqual = VK_COMPARE_OP_EQUAL,
eLessOrEqual = VK_COMPARE_OP_LESS_OR_EQUAL,
eGreater = VK_COMPARE_OP_GREATER,
eNotEqual = VK_COMPARE_OP_NOT_EQUAL,
eGreaterOrEqual = VK_COMPARE_OP_GREATER_OR_EQUAL,
eAlways = VK_COMPARE_OP_ALWAYS
};
enum class BorderColor {
eFloatTransparentBlack = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
eIntTransparentBlack = VK_BORDER_COLOR_INT_TRANSPARENT_BLACK,
eFloatOpaqueBlack = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
eIntOpaqueBlack = VK_BORDER_COLOR_INT_OPAQUE_BLACK,
eFloatOpaqueWhite = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
eIntOpaqueWhite = VK_BORDER_COLOR_INT_OPAQUE_WHITE,
eFloatCustomEXT = VK_BORDER_COLOR_FLOAT_CUSTOM_EXT,
eIntCustomEXT = VK_BORDER_COLOR_INT_CUSTOM_EXT
};
struct SamplerCreateInfo {
static constexpr VkStructureType structureType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
VkStructureType sType = structureType;
const void* pNext = {};
SamplerCreateFlags flags = {};
Filter magFilter = Filter::eNearest;
Filter minFilter = Filter::eNearest;
SamplerMipmapMode mipmapMode = SamplerMipmapMode::eNearest;
SamplerAddressMode addressModeU = SamplerAddressMode::eRepeat;
SamplerAddressMode addressModeV = SamplerAddressMode::eRepeat;
SamplerAddressMode addressModeW = SamplerAddressMode::eRepeat;
float mipLodBias = {};
Bool32 anisotropyEnable = {};
float maxAnisotropy = {};
Bool32 compareEnable = {};
CompareOp compareOp = CompareOp::eNever;
float minLod = 0.f;
float maxLod = VK_LOD_CLAMP_NONE;
BorderColor borderColor = BorderColor::eFloatTransparentBlack;
Bool32 unnormalizedCoordinates = {};
operator VkSamplerCreateInfo const&() const noexcept {
return *reinterpret_cast<const VkSamplerCreateInfo*>(this);
}
operator VkSamplerCreateInfo&() noexcept {
return *reinterpret_cast<VkSamplerCreateInfo*>(this);
}
bool operator==(SamplerCreateInfo const& rhs) const noexcept {
return (sType == rhs.sType) && (pNext == rhs.pNext) && (flags == rhs.flags) && (magFilter == rhs.magFilter) && (minFilter == rhs.minFilter) &&
(mipmapMode == rhs.mipmapMode) && (addressModeU == rhs.addressModeU) && (addressModeV == rhs.addressModeV) && (addressModeW == rhs.addressModeW) &&
(mipLodBias == rhs.mipLodBias) && (anisotropyEnable == rhs.anisotropyEnable) && (maxAnisotropy == rhs.maxAnisotropy) &&
(compareEnable == rhs.compareEnable) && (compareOp == rhs.compareOp) && (minLod == rhs.minLod) && (maxLod == rhs.maxLod) &&
(borderColor == rhs.borderColor) && (unnormalizedCoordinates == rhs.unnormalizedCoordinates);
}
bool operator!=(SamplerCreateInfo const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(sizeof(SamplerCreateInfo) == sizeof(VkSamplerCreateInfo), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<SamplerCreateInfo>::value, "struct wrapper is not a standard layout!");
template<>
struct create_info<Sampler> {
using type = vuk::SamplerCreateInfo;
};
struct Texture {
Unique<Image> image;
Unique<ImageView> view;
Extent3D extent;
Format format;
Samples sample_count;
uint32_t level_count;
uint32_t layer_count;
};
ImageAspectFlags format_to_aspect(Format format) noexcept;
}; // namespace vuk
namespace std {
template<>
struct hash<vuk::ImageView> {
size_t operator()(vuk::ImageView const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.id, reinterpret_cast<uint64_t>(x.payload));
return h;
}
};
} // namespace std
<file_sep>#include "vuk/Image.hpp"
#include <cassert>
namespace vuk {
uint32_t format_to_texel_block_size(Format format) noexcept {
switch (format) {
case Format::eR4G4UnormPack8:
case Format::eR8Unorm:
case Format::eR8Snorm:
case Format::eR8Uscaled:
case Format::eR8Sscaled:
case Format::eR8Uint:
case Format::eR8Sint:
case Format::eR8Srgb:
return 1;
case Format::eR4G4B4A4UnormPack16:
case Format::eB4G4R4A4UnormPack16:
case Format::eR5G6B5UnormPack16:
case Format::eB5G6R5UnormPack16:
case Format::eR5G5B5A1UnormPack16:
case Format::eB5G5R5A1UnormPack16:
case Format::eA1R5G5B5UnormPack16:
case Format::eR8G8Unorm:
case Format::eR8G8Snorm:
case Format::eR8G8Uscaled:
case Format::eR8G8Sscaled:
case Format::eR8G8Uint:
case Format::eR8G8Sint:
case Format::eR8G8Srgb:
case Format::eR16Unorm:
case Format::eR16Snorm:
case Format::eR16Uscaled:
case Format::eR16Sscaled:
case Format::eR16Uint:
case Format::eR16Sint:
case Format::eR16Sfloat:
case Format::eR10X6UnormPack16:
case Format::eR12X4UnormPack16:
return 2;
case Format::eR8G8B8Unorm:
case Format::eR8G8B8Snorm:
case Format::eR8G8B8Uscaled:
case Format::eR8G8B8Sscaled:
case Format::eR8G8B8Uint:
case Format::eR8G8B8Sint:
case Format::eR8G8B8Srgb:
case Format::eB8G8R8Unorm:
case Format::eB8G8R8Snorm:
case Format::eB8G8R8Uscaled:
case Format::eB8G8R8Sscaled:
case Format::eB8G8R8Uint:
case Format::eB8G8R8Sint:
case Format::eB8G8R8Srgb:
return 3;
case Format::eR8G8B8A8Unorm:
case Format::eR8G8B8A8Snorm:
case Format::eR8G8B8A8Uscaled:
case Format::eR8G8B8A8Sscaled:
case Format::eR8G8B8A8Uint:
case Format::eR8G8B8A8Sint:
case Format::eR8G8B8A8Srgb:
case Format::eB8G8R8A8Unorm:
case Format::eB8G8R8A8Snorm:
case Format::eB8G8R8A8Uscaled:
case Format::eB8G8R8A8Sscaled:
case Format::eB8G8R8A8Uint:
case Format::eB8G8R8A8Sint:
case Format::eB8G8R8A8Srgb:
case Format::eA8B8G8R8UnormPack32:
case Format::eA8B8G8R8SnormPack32:
case Format::eA8B8G8R8UscaledPack32:
case Format::eA8B8G8R8SscaledPack32:
case Format::eA8B8G8R8UintPack32:
case Format::eA8B8G8R8SintPack32:
case Format::eA8B8G8R8SrgbPack32:
case Format::eA2R10G10B10UnormPack32:
case Format::eA2R10G10B10SnormPack32:
case Format::eA2R10G10B10UscaledPack32:
case Format::eA2R10G10B10SscaledPack32:
case Format::eA2R10G10B10UintPack32:
case Format::eA2R10G10B10SintPack32:
case Format::eA2B10G10R10UnormPack32:
case Format::eA2B10G10R10SnormPack32:
case Format::eA2B10G10R10UscaledPack32:
case Format::eA2B10G10R10SscaledPack32:
case Format::eA2B10G10R10UintPack32:
case Format::eA2B10G10R10SintPack32:
case Format::eR16G16Unorm:
case Format::eR16G16Snorm:
case Format::eR16G16Uscaled:
case Format::eR16G16Sscaled:
case Format::eR16G16Uint:
case Format::eR16G16Sint:
case Format::eR16G16Sfloat:
case Format::eR32Uint:
case Format::eR32Sint:
case Format::eR32Sfloat:
case Format::eB10G11R11UfloatPack32:
case Format::eE5B9G9R9UfloatPack32:
case Format::eR10X6G10X6Unorm2Pack16:
case Format::eR12X4G12X4Unorm2Pack16:
return 4;
case Format::eG8B8G8R8422Unorm:
return 4;
case Format::eB8G8R8G8422Unorm:
return 4;
case Format::eR16G16B16Unorm:
case Format::eR16G16B16Snorm:
case Format::eR16G16B16Uscaled:
case Format::eR16G16B16Sscaled:
case Format::eR16G16B16Uint:
case Format::eR16G16B16Sint:
case Format::eR16G16B16Sfloat:
return 6;
case Format::eR16G16B16A16Unorm:
case Format::eR16G16B16A16Snorm:
case Format::eR16G16B16A16Uscaled:
case Format::eR16G16B16A16Sscaled:
case Format::eR16G16B16A16Uint:
case Format::eR16G16B16A16Sint:
case Format::eR16G16B16A16Sfloat:
case Format::eR32G32Uint:
case Format::eR32G32Sint:
case Format::eR32G32Sfloat:
case Format::eR64Uint:
case Format::eR64Sint:
case Format::eR64Sfloat:
return 8;
case Format::eR10X6G10X6B10X6A10X6Unorm4Pack16:
return 8;
case Format::eG10X6B10X6G10X6R10X6422Unorm4Pack16:
return 8;
case Format::eB10X6G10X6R10X6G10X6422Unorm4Pack16:
return 8;
case Format::eR12X4G12X4B12X4A12X4Unorm4Pack16:
return 8;
case Format::eG12X4B12X4G12X4R12X4422Unorm4Pack16:
return 8;
case Format::eB12X4G12X4R12X4G12X4422Unorm4Pack16:
return 8;
case Format::eG16B16G16R16422Unorm:
return 8;
case Format::eB16G16R16G16422Unorm:
return 8;
case Format::eR32G32B32Uint:
case Format::eR32G32B32Sint:
case Format::eR32G32B32Sfloat:
return 12;
case Format::eR32G32B32A32Uint:
case Format::eR32G32B32A32Sint:
case Format::eR32G32B32A32Sfloat:
case Format::eR64G64Uint:
case Format::eR64G64Sint:
case Format::eR64G64Sfloat:
return 16;
case Format::eR64G64B64Uint:
case Format::eR64G64B64Sint:
case Format::eR64G64B64Sfloat:
return 24;
case Format::eR64G64B64A64Uint:
case Format::eR64G64B64A64Sint:
case Format::eR64G64B64A64Sfloat:
return 32;
case Format::eBc1RgbUnormBlock:
case Format::eBc1RgbSrgbBlock:
return 8;
case Format::eBc1RgbaUnormBlock:
case Format::eBc1RgbaSrgbBlock:
return 8;
case Format::eBc2UnormBlock:
case Format::eBc2SrgbBlock:
return 16;
case Format::eBc3UnormBlock:
case Format::eBc3SrgbBlock:
return 16;
case Format::eBc4UnormBlock:
case Format::eBc4SnormBlock:
return 8;
case Format::eBc5UnormBlock:
case Format::eBc5SnormBlock:
return 16;
case Format::eBc6HUfloatBlock:
case Format::eBc6HSfloatBlock:
return 16;
case Format::eBc7UnormBlock:
case Format::eBc7SrgbBlock:
return 16;
case Format::eEtc2R8G8B8UnormBlock:
case Format::eEtc2R8G8B8SrgbBlock:
return 8;
case Format::eEtc2R8G8B8A1UnormBlock:
case Format::eEtc2R8G8B8A1SrgbBlock:
return 8;
case Format::eEtc2R8G8B8A8UnormBlock:
case Format::eEtc2R8G8B8A8SrgbBlock:
return 8;
case Format::eEacR11UnormBlock:
case Format::eEacR11SnormBlock:
return 8;
case Format::eEacR11G11UnormBlock:
case Format::eEacR11G11SnormBlock:
return 16;
case Format::eAstc4x4UnormBlock:
case Format::eAstc4x4SfloatBlockEXT:
case Format::eAstc4x4SrgbBlock:
return 16;
case Format::eAstc5x4UnormBlock:
case Format::eAstc5x4SfloatBlockEXT:
case Format::eAstc5x4SrgbBlock:
return 16;
case Format::eAstc5x5UnormBlock:
case Format::eAstc5x5SfloatBlockEXT:
case Format::eAstc5x5SrgbBlock:
return 16;
case Format::eAstc6x5UnormBlock:
case Format::eAstc6x5SfloatBlockEXT:
case Format::eAstc6x5SrgbBlock:
return 16;
case Format::eAstc6x6UnormBlock:
case Format::eAstc6x6SfloatBlockEXT:
case Format::eAstc6x6SrgbBlock:
return 16;
case Format::eAstc8x5UnormBlock:
case Format::eAstc8x5SfloatBlockEXT:
case Format::eAstc8x5SrgbBlock:
return 16;
case Format::eAstc8x6UnormBlock:
case Format::eAstc8x6SfloatBlockEXT:
case Format::eAstc8x6SrgbBlock:
return 16;
case Format::eAstc8x8UnormBlock:
case Format::eAstc8x8SfloatBlockEXT:
case Format::eAstc8x8SrgbBlock:
return 16;
case Format::eAstc10x5UnormBlock:
case Format::eAstc10x5SfloatBlockEXT:
case Format::eAstc10x5SrgbBlock:
return 16;
case Format::eAstc10x6UnormBlock:
case Format::eAstc10x6SfloatBlockEXT:
case Format::eAstc10x6SrgbBlock:
return 16;
case Format::eAstc10x8UnormBlock:
case Format::eAstc10x8SfloatBlockEXT:
case Format::eAstc10x8SrgbBlock:
return 16;
case Format::eAstc10x10UnormBlock:
case Format::eAstc10x10SfloatBlockEXT:
case Format::eAstc10x10SrgbBlock:
return 16;
case Format::eAstc12x10UnormBlock:
case Format::eAstc12x10SfloatBlockEXT:
case Format::eAstc12x10SrgbBlock:
return 16;
case Format::eAstc12x12UnormBlock:
case Format::eAstc12x12SfloatBlockEXT:
case Format::eAstc12x12SrgbBlock:
return 16;
case Format::eD16Unorm:
return 2;
case Format::eX8D24UnormPack32:
return 4;
case Format::eD32Sfloat:
return 4;
case Format::eS8Uint:
return 1;
case Format::eD16UnormS8Uint:
return 3;
case Format::eD24UnormS8Uint:
return 4;
case Format::eD32SfloatS8Uint:
return 5;
default:
assert(0 && "format cannot be used with this function.");
return 0;
}
}
Extent3D format_to_texel_block_extent(Format format) noexcept {
switch (format) {
case Format::eR4G4UnormPack8:
case Format::eR8Unorm:
case Format::eR8Snorm:
case Format::eR8Uscaled:
case Format::eR8Sscaled:
case Format::eR8Uint:
case Format::eR8Sint:
case Format::eR8Srgb:
case Format::eR4G4B4A4UnormPack16:
case Format::eB4G4R4A4UnormPack16:
case Format::eR5G6B5UnormPack16:
case Format::eB5G6R5UnormPack16:
case Format::eR5G5B5A1UnormPack16:
case Format::eB5G5R5A1UnormPack16:
case Format::eA1R5G5B5UnormPack16:
case Format::eR8G8Unorm:
case Format::eR8G8Snorm:
case Format::eR8G8Uscaled:
case Format::eR8G8Sscaled:
case Format::eR8G8Uint:
case Format::eR8G8Sint:
case Format::eR8G8Srgb:
case Format::eR16Unorm:
case Format::eR16Snorm:
case Format::eR16Uscaled:
case Format::eR16Sscaled:
case Format::eR16Uint:
case Format::eR16Sint:
case Format::eR16Sfloat:
case Format::eR10X6UnormPack16:
case Format::eR12X4UnormPack16:
case Format::eR8G8B8Unorm:
case Format::eR8G8B8Snorm:
case Format::eR8G8B8Uscaled:
case Format::eR8G8B8Sscaled:
case Format::eR8G8B8Uint:
case Format::eR8G8B8Sint:
case Format::eR8G8B8Srgb:
case Format::eB8G8R8Unorm:
case Format::eB8G8R8Snorm:
case Format::eB8G8R8Uscaled:
case Format::eB8G8R8Sscaled:
case Format::eB8G8R8Uint:
case Format::eB8G8R8Sint:
case Format::eB8G8R8Srgb:
case Format::eR8G8B8A8Unorm:
case Format::eR8G8B8A8Snorm:
case Format::eR8G8B8A8Uscaled:
case Format::eR8G8B8A8Sscaled:
case Format::eR8G8B8A8Uint:
case Format::eR8G8B8A8Sint:
case Format::eR8G8B8A8Srgb:
case Format::eB8G8R8A8Unorm:
case Format::eB8G8R8A8Snorm:
case Format::eB8G8R8A8Uscaled:
case Format::eB8G8R8A8Sscaled:
case Format::eB8G8R8A8Uint:
case Format::eB8G8R8A8Sint:
case Format::eB8G8R8A8Srgb:
case Format::eA8B8G8R8UnormPack32:
case Format::eA8B8G8R8SnormPack32:
case Format::eA8B8G8R8UscaledPack32:
case Format::eA8B8G8R8SscaledPack32:
case Format::eA8B8G8R8UintPack32:
case Format::eA8B8G8R8SintPack32:
case Format::eA8B8G8R8SrgbPack32:
case Format::eA2R10G10B10UnormPack32:
case Format::eA2R10G10B10SnormPack32:
case Format::eA2R10G10B10UscaledPack32:
case Format::eA2R10G10B10SscaledPack32:
case Format::eA2R10G10B10UintPack32:
case Format::eA2R10G10B10SintPack32:
case Format::eA2B10G10R10UnormPack32:
case Format::eA2B10G10R10SnormPack32:
case Format::eA2B10G10R10UscaledPack32:
case Format::eA2B10G10R10SscaledPack32:
case Format::eA2B10G10R10UintPack32:
case Format::eA2B10G10R10SintPack32:
case Format::eR16G16Unorm:
case Format::eR16G16Snorm:
case Format::eR16G16Uscaled:
case Format::eR16G16Sscaled:
case Format::eR16G16Uint:
case Format::eR16G16Sint:
case Format::eR16G16Sfloat:
case Format::eR32Uint:
case Format::eR32Sint:
case Format::eR32Sfloat:
case Format::eB10G11R11UfloatPack32:
case Format::eE5B9G9R9UfloatPack32:
case Format::eR10X6G10X6Unorm2Pack16:
case Format::eR12X4G12X4Unorm2Pack16:
case Format::eG8B8G8R8422Unorm:
case Format::eB8G8R8G8422Unorm:
case Format::eR16G16B16Unorm:
case Format::eR16G16B16Snorm:
case Format::eR16G16B16Uscaled:
case Format::eR16G16B16Sscaled:
case Format::eR16G16B16Uint:
case Format::eR16G16B16Sint:
case Format::eR16G16B16Sfloat:
case Format::eR16G16B16A16Unorm:
case Format::eR16G16B16A16Snorm:
case Format::eR16G16B16A16Uscaled:
case Format::eR16G16B16A16Sscaled:
case Format::eR16G16B16A16Uint:
case Format::eR16G16B16A16Sint:
case Format::eR16G16B16A16Sfloat:
case Format::eR32G32Uint:
case Format::eR32G32Sint:
case Format::eR32G32Sfloat:
case Format::eR64Uint:
case Format::eR64Sint:
case Format::eR64Sfloat:
case Format::eR10X6G10X6B10X6A10X6Unorm4Pack16:
case Format::eG10X6B10X6G10X6R10X6422Unorm4Pack16:
case Format::eB10X6G10X6R10X6G10X6422Unorm4Pack16:
case Format::eR12X4G12X4B12X4A12X4Unorm4Pack16:
case Format::eG12X4B12X4G12X4R12X4422Unorm4Pack16:
case Format::eB12X4G12X4R12X4G12X4422Unorm4Pack16:
case Format::eG16B16G16R16422Unorm:
case Format::eB16G16R16G16422Unorm:
case Format::eR32G32B32Uint:
case Format::eR32G32B32Sint:
case Format::eR32G32B32Sfloat:
case Format::eR32G32B32A32Uint:
case Format::eR32G32B32A32Sint:
case Format::eR32G32B32A32Sfloat:
case Format::eR64G64Uint:
case Format::eR64G64Sint:
case Format::eR64G64Sfloat:
case Format::eR64G64B64Uint:
case Format::eR64G64B64Sint:
case Format::eR64G64B64Sfloat:
case Format::eR64G64B64A64Uint:
case Format::eR64G64B64A64Sint:
case Format::eR64G64B64A64Sfloat:
return { 1, 1, 1 };
case Format::eBc1RgbUnormBlock:
case Format::eBc1RgbSrgbBlock:
return { 4, 4, 1 };
case Format::eBc1RgbaUnormBlock:
case Format::eBc1RgbaSrgbBlock:
return { 4, 4, 1 };
case Format::eBc2UnormBlock:
case Format::eBc2SrgbBlock:
return { 4, 4, 1 };
case Format::eBc3UnormBlock:
case Format::eBc3SrgbBlock:
return { 4, 4, 1 };
case Format::eBc4UnormBlock:
case Format::eBc4SnormBlock:
return { 4, 4, 1 };
case Format::eBc5UnormBlock:
case Format::eBc5SnormBlock:
return { 4, 4, 1 };
case Format::eBc6HUfloatBlock:
case Format::eBc6HSfloatBlock:
return { 4, 4, 1 };
case Format::eBc7UnormBlock:
case Format::eBc7SrgbBlock:
return { 4, 4, 1 };
case Format::eEtc2R8G8B8UnormBlock:
case Format::eEtc2R8G8B8SrgbBlock:
return { 4, 4, 1 };
case Format::eEtc2R8G8B8A1UnormBlock:
case Format::eEtc2R8G8B8A1SrgbBlock:
return { 4, 4, 1 };
case Format::eEtc2R8G8B8A8UnormBlock:
case Format::eEtc2R8G8B8A8SrgbBlock:
return { 4, 4, 1 };
case Format::eEacR11UnormBlock:
case Format::eEacR11SnormBlock:
return { 4, 4, 1 };
case Format::eEacR11G11UnormBlock:
case Format::eEacR11G11SnormBlock:
return { 4, 4, 1 };
case Format::eAstc4x4UnormBlock:
case Format::eAstc4x4SfloatBlockEXT:
case Format::eAstc4x4SrgbBlock:
return { 4, 4, 1 };
case Format::eAstc5x4UnormBlock:
case Format::eAstc5x4SfloatBlockEXT:
case Format::eAstc5x4SrgbBlock:
return { 5, 4, 1 };
case Format::eAstc5x5UnormBlock:
case Format::eAstc5x5SfloatBlockEXT:
case Format::eAstc5x5SrgbBlock:
return { 5, 5, 1 };
case Format::eAstc6x5UnormBlock:
case Format::eAstc6x5SfloatBlockEXT:
case Format::eAstc6x5SrgbBlock:
return { 6, 5, 1 };
case Format::eAstc6x6UnormBlock:
case Format::eAstc6x6SfloatBlockEXT:
case Format::eAstc6x6SrgbBlock:
return { 6, 6, 1 };
case Format::eAstc8x5UnormBlock:
case Format::eAstc8x5SfloatBlockEXT:
case Format::eAstc8x5SrgbBlock:
return { 8, 5, 1 };
case Format::eAstc8x6UnormBlock:
case Format::eAstc8x6SfloatBlockEXT:
case Format::eAstc8x6SrgbBlock:
return { 8, 6, 1 };
case Format::eAstc8x8UnormBlock:
case Format::eAstc8x8SfloatBlockEXT:
case Format::eAstc8x8SrgbBlock:
return { 8, 8, 1 };
case Format::eAstc10x5UnormBlock:
case Format::eAstc10x5SfloatBlockEXT:
case Format::eAstc10x5SrgbBlock:
return { 10, 5, 1 };
case Format::eAstc10x6UnormBlock:
case Format::eAstc10x6SfloatBlockEXT:
case Format::eAstc10x6SrgbBlock:
return { 10, 6, 1 };
case Format::eAstc10x8UnormBlock:
case Format::eAstc10x8SfloatBlockEXT:
case Format::eAstc10x8SrgbBlock:
return { 10, 8, 1 };
case Format::eAstc10x10UnormBlock:
case Format::eAstc10x10SfloatBlockEXT:
case Format::eAstc10x10SrgbBlock:
return { 10, 10, 1 };
case Format::eAstc12x10UnormBlock:
case Format::eAstc12x10SfloatBlockEXT:
case Format::eAstc12x10SrgbBlock:
return { 12, 10, 1 };
case Format::eAstc12x12UnormBlock:
case Format::eAstc12x12SfloatBlockEXT:
case Format::eAstc12x12SrgbBlock:
return { 12, 12, 1 };
case Format::eD16Unorm:
case Format::eX8D24UnormPack32:
case Format::eD32Sfloat:
case Format::eS8Uint:
case Format::eD16UnormS8Uint:
case Format::eD24UnormS8Uint:
case Format::eD32SfloatS8Uint:
return { 1, 1, 1 };
default:
assert(0 && "format cannot be used with this function.");
return { 0, 0, 0 };
}
}
uint32_t compute_image_size(Format format, Extent3D extent) noexcept {
auto block_extent = format_to_texel_block_extent(format);
auto extent_in_blocks = Extent3D{ (extent.width + block_extent.width - 1) / block_extent.width,
(extent.height + block_extent.height - 1) / block_extent.height,
(extent.depth + block_extent.depth - 1) / block_extent.depth };
return extent_in_blocks.width * extent_in_blocks.height * extent_in_blocks.depth * format_to_texel_block_size(format);
}
ImageAspectFlags format_to_aspect(Format format) noexcept {
switch (format) {
case Format::eD16Unorm:
case Format::eD32Sfloat:
case Format::eX8D24UnormPack32:
return ImageAspectFlagBits::eDepth;
case Format::eD16UnormS8Uint:
case Format::eD24UnormS8Uint:
case Format::eD32SfloatS8Uint:
return ImageAspectFlagBits::eDepth | ImageAspectFlagBits::eStencil;
case Format::eS8Uint:
return ImageAspectFlagBits::eStencil;
default:
return ImageAspectFlagBits::eColor;
}
}
std::string_view format_to_sv(Format format) noexcept {
switch (format) {
case Format::eR4G4UnormPack8:
return "R4G4UnormPack8";
case Format::eR8Unorm:
return "R8Unorm";
case Format::eR8Snorm:
return "R8Snorm";
case Format::eR8Uscaled:
return "R8Uscaled";
case Format::eR8Sscaled:
return "R8Sscaled";
case Format::eR8Uint:
return "R8Uint";
case Format::eR8Sint:
return "R8Sint";
case Format::eR8Srgb:
return "R8Srgb";
case Format::eR4G4B4A4UnormPack16:
return "R4G4B4A4UnormPack16";
case Format::eB4G4R4A4UnormPack16:
return "B4G4R4A4UnormPack16";
case Format::eR5G6B5UnormPack16:
return "R5G6B5UnormPack16";
case Format::eB5G6R5UnormPack16:
return "B5G6R5UnormPack16";
case Format::eR5G5B5A1UnormPack16:
return "R5G5B5A1UnormPack16";
case Format::eB5G5R5A1UnormPack16:
return "B5G5R5A1UnormPack16";
case Format::eA1R5G5B5UnormPack16:
return "A1R5G5B5UnormPack16";
case Format::eR8G8Unorm:
return "R8G8Unorm";
case Format::eR8G8Snorm:
return "R8G8Snorm";
case Format::eR8G8Uscaled:
return "R8G8Uscaled";
case Format::eR8G8Sscaled:
return "R8G8Sscaled";
case Format::eR8G8Uint:
return "R8G8Uint";
case Format::eR8G8Sint:
return "R8G8Sint";
case Format::eR8G8Srgb:
return "R8G8Srgb";
case Format::eR16Unorm:
return "R16Unorm";
case Format::eR16Snorm:
return "R16Snorm";
case Format::eR16Uscaled:
return "R16Uscaled";
case Format::eR16Sscaled:
return "R16Sscaled";
case Format::eR16Uint:
return "R16Uint";
case Format::eR16Sint:
return "R16Sint";
case Format::eR16Sfloat:
return "R16Sfloat";
case Format::eR10X6UnormPack16:
return "R10X6UnormPack16";
case Format::eR12X4UnormPack16:
return "R12X4UnormPack16";
case Format::eR8G8B8Unorm:
return "R8G8B8Unorm";
case Format::eR8G8B8Snorm:
return "R8G8B8Snorm";
case Format::eR8G8B8Uscaled:
return "R8G8B8Uscaled";
case Format::eR8G8B8Sscaled:
return "R8G8B8Sscaled";
case Format::eR8G8B8Uint:
return "R8G8B8Uint";
case Format::eR8G8B8Sint:
return "R8G8B8Sint";
case Format::eR8G8B8Srgb:
return "R8G8B8Srgb";
case Format::eB8G8R8Unorm:
return "B8G8R8Unorm";
case Format::eB8G8R8Snorm:
return "B8G8R8Snorm";
case Format::eB8G8R8Uscaled:
return "B8G8R8Uscaled";
case Format::eB8G8R8Sscaled:
return "B8G8R8Sscaled";
case Format::eB8G8R8Uint:
return "B8G8R8Uint";
case Format::eB8G8R8Sint:
return "B8G8R8Sint";
case Format::eB8G8R8Srgb:
return "B8G8R8Srgb";
case Format::eR8G8B8A8Unorm:
return "R8G8B8A8Unorm";
case Format::eR8G8B8A8Snorm:
return "R8G8B8A8Snorm";
case Format::eR8G8B8A8Uscaled:
return "R8G8B8A8Uscaled";
case Format::eR8G8B8A8Sscaled:
return "R8G8B8A8Sscaled";
case Format::eR8G8B8A8Uint:
return "R8G8B8A8Uint";
case Format::eR8G8B8A8Sint:
return "R8G8B8A8Sint";
case Format::eR8G8B8A8Srgb:
return "R8G8B8A8Srgb";
case Format::eB8G8R8A8Unorm:
return "B8G8R8A8Unorm";
case Format::eB8G8R8A8Snorm:
return "B8G8R8A8Snorm";
case Format::eB8G8R8A8Uscaled:
return "B8G8R8A8Uscaled";
case Format::eB8G8R8A8Sscaled:
return "B8G8R8A8Sscaled";
case Format::eB8G8R8A8Uint:
return "B8G8R8A8Uint";
case Format::eB8G8R8A8Sint:
return "B8G8R8A8Sint";
case Format::eB8G8R8A8Srgb:
return "B8G8R8A8Srgb";
case Format::eA8B8G8R8UnormPack32:
return "A8B8G8R8UnormPack32";
case Format::eA8B8G8R8SnormPack32:
return "A8B8G8R8SnormPack32";
case Format::eA8B8G8R8UscaledPack32:
return "A8B8G8R8UscaledPack32";
case Format::eA8B8G8R8SscaledPack32:
return "A8B8G8R8SscaledPack32";
case Format::eA8B8G8R8UintPack32:
return "A8B8G8R8UintPack32";
case Format::eA8B8G8R8SintPack32:
return "A8B8G8R8SintPack32";
case Format::eA8B8G8R8SrgbPack32:
return "A8B8G8R8SrgbPack32";
case Format::eA2R10G10B10UnormPack32:
return "A2R10G10B10UnormPack32";
case Format::eA2R10G10B10SnormPack32:
return "A2R10G10B10SnormPack32";
case Format::eA2R10G10B10UscaledPack32:
return "A2R10G10B10UscaledPack32";
case Format::eA2R10G10B10SscaledPack32:
return "A2R10G10B10SscaledPack32";
case Format::eA2R10G10B10UintPack32:
return "A2R10G10B10UintPack32";
case Format::eA2R10G10B10SintPack32:
return "A2R10G10B10SintPack32";
case Format::eA2B10G10R10UnormPack32:
return "A2B10G10R10UnormPack32";
case Format::eA2B10G10R10SnormPack32:
return "A2B10G10R10SnormPack32";
case Format::eA2B10G10R10UscaledPack32:
return "A2B10G10R10UscaledPack32";
case Format::eA2B10G10R10SscaledPack32:
return "A2B10G10R10SscaledPack32";
case Format::eA2B10G10R10UintPack32:
return "A2B10G10R10UintPack32";
case Format::eA2B10G10R10SintPack32:
return "A2B10G10R10SintPack32";
case Format::eR16G16Unorm:
return "R16G16Unorm";
case Format::eR16G16Snorm:
return "R16G16Snorm";
case Format::eR16G16Uscaled:
return "R16G16Uscaled";
case Format::eR16G16Sscaled:
return "R16G16Sscaled";
case Format::eR16G16Uint:
return "R16G16Uint";
case Format::eR16G16Sint:
return "R16G16Sint";
case Format::eR16G16Sfloat:
return "R16G16Sfloat";
case Format::eR32Uint:
return "R32Uint";
case Format::eR32Sint:
return "R32Sint";
case Format::eR32Sfloat:
return "R32Sfloat";
case Format::eB10G11R11UfloatPack32:
return "B10G11R11UfloatPack32";
case Format::eE5B9G9R9UfloatPack32:
return "E5B9G9R9UfloatPack32";
case Format::eR10X6G10X6Unorm2Pack16:
return "R10X6G10X6Unorm2Pack16";
case Format::eR12X4G12X4Unorm2Pack16:
return "R12X4G12X4Unorm2Pack16";
case Format::eG8B8G8R8422Unorm:
return "G8B8G8R8422Unorm";
case Format::eB8G8R8G8422Unorm:
return "B8G8R8G8422Unorm";
case Format::eR16G16B16Unorm:
return "R16G16B16Unorm";
case Format::eR16G16B16Snorm:
return "R16G16B16Snorm";
case Format::eR16G16B16Uscaled:
return "R16G16B16Uscaled";
case Format::eR16G16B16Sscaled:
return "R16G16B16Sscaled";
case Format::eR16G16B16Uint:
return "R16G16B16Uint";
case Format::eR16G16B16Sint:
return "R16G16B16Sint";
case Format::eR16G16B16Sfloat:
return "R16G16B16Sfloat";
case Format::eR16G16B16A16Unorm:
return "R16G16B16A16Unorm";
case Format::eR16G16B16A16Snorm:
return "R16G16B16A16Snorm";
case Format::eR16G16B16A16Uscaled:
return "R16G16B16A16Uscaled";
case Format::eR16G16B16A16Sscaled:
return "R16G16B16A16Sscaled";
case Format::eR16G16B16A16Uint:
return "R16G16B16A16Uint";
case Format::eR16G16B16A16Sint:
return "R16G16B16A16Sint";
case Format::eR16G16B16A16Sfloat:
return "R16G16B16A16Sfloat";
case Format::eR32G32Uint:
return "R32G32Uint";
case Format::eR32G32Sint:
return "R32G32Sint";
case Format::eR32G32Sfloat:
return "R32G32Sfloat";
case Format::eR64Uint:
return "R64Uint";
case Format::eR64Sint:
return "R64Sint";
case Format::eR64Sfloat:
return "R64Sfloat";
case Format::eR10X6G10X6B10X6A10X6Unorm4Pack16:
return "R10X6G10X6B10X6A10X6Unorm4Pack16";
case Format::eG10X6B10X6G10X6R10X6422Unorm4Pack16:
return "G10X6B10X6G10X6R10X6422Unorm4Pack16";
case Format::eB10X6G10X6R10X6G10X6422Unorm4Pack16:
return "B10X6G10X6R10X6G10X6422Unorm4Pack16";
case Format::eR12X4G12X4B12X4A12X4Unorm4Pack16:
return "R12X4G12X4B12X4A12X4Unorm4Pack16";
case Format::eG12X4B12X4G12X4R12X4422Unorm4Pack16:
return "G12X4B12X4G12X4R12X4422Unorm4Pack16";
case Format::eB12X4G12X4R12X4G12X4422Unorm4Pack16:
return "B12X4G12X4R12X4G12X4422Unorm4Pack16";
case Format::eG16B16G16R16422Unorm:
return "G16B16G16R16422Unorm";
case Format::eB16G16R16G16422Unorm:
return "B16G16R16G16422Unorm";
case Format::eR32G32B32Uint:
return "R32G32B32Uint";
case Format::eR32G32B32Sint:
return "R32G32B32Sint";
case Format::eR32G32B32Sfloat:
return "R32G32B32Sfloat";
case Format::eR32G32B32A32Uint:
return "R32G32B32A32Uint";
case Format::eR32G32B32A32Sint:
return "R32G32B32A32Sint";
case Format::eR32G32B32A32Sfloat:
return "R32G32B32A32Sfloat";
case Format::eR64G64Uint:
return "R64G64Uint";
case Format::eR64G64Sint:
return "R64G64Sint";
case Format::eR64G64Sfloat:
return "R64G64Sfloat";
case Format::eR64G64B64Uint:
return "R64G64B64Uint";
case Format::eR64G64B64Sint:
return "R64G64B64Sint";
case Format::eR64G64B64Sfloat:
return "R64G64B64Sfloat";
case Format::eR64G64B64A64Uint:
return "R64G64B64A64Uint";
case Format::eR64G64B64A64Sint:
return "R64G64B64A64Sint";
case Format::eR64G64B64A64Sfloat:
return "R64G64B64A64Sfloat";
case Format::eBc1RgbUnormBlock:
return "Bc1RgbUnormBlock";
case Format::eBc1RgbSrgbBlock:
return "Bc1RgbSrgbBlock";
case Format::eBc1RgbaUnormBlock:
return "Bc1RgbaUnormBlock";
case Format::eBc1RgbaSrgbBlock:
return "Bc1RgbaSrgbBlock";
case Format::eBc2UnormBlock:
return "Bc2UnormBlock";
case Format::eBc2SrgbBlock:
return "Bc2SrgbBlock";
case Format::eBc3UnormBlock:
return "Bc3UnormBlock";
case Format::eBc3SrgbBlock:
return "Bc3SrgbBlock";
case Format::eBc4UnormBlock:
return "Bc4UnormBlock";
case Format::eBc4SnormBlock:
return "Bc4SnormBlock";
case Format::eBc5UnormBlock:
return "Bc5UnormBlock";
case Format::eBc5SnormBlock:
return "Bc5SnormBlock";
case Format::eBc6HUfloatBlock:
return "Bc6HUfloatBlock";
case Format::eBc6HSfloatBlock:
return "Bc6HSfloatBlock";
case Format::eBc7UnormBlock:
return "Bc7UnormBlock";
case Format::eBc7SrgbBlock:
return "Bc7SrgbBlock";
case Format::eEtc2R8G8B8UnormBlock:
return "Etc2R8G8B8UnormBlock";
case Format::eEtc2R8G8B8SrgbBlock:
return "Etc2R8G8B8SrgbBlock";
case Format::eEtc2R8G8B8A1UnormBlock:
return "Etc2R8G8B8A1UnormBlock";
case Format::eEtc2R8G8B8A1SrgbBlock:
return "Etc2R8G8B8A1SrgbBlock";
case Format::eEtc2R8G8B8A8UnormBlock:
return "Etc2R8G8B8A8UnormBlock";
case Format::eEtc2R8G8B8A8SrgbBlock:
return "Etc2R8G8B8A8SrgbBlock";
case Format::eEacR11UnormBlock:
return "EacR11UnormBlock";
case Format::eEacR11SnormBlock:
return "EacR11SnormBlock";
case Format::eEacR11G11UnormBlock:
return "EacR11G11UnormBlock";
case Format::eEacR11G11SnormBlock:
return "EacR11G11SnormBlock";
case Format::eAstc4x4UnormBlock:
return "Astc4x4UnormBlock";
case Format::eAstc4x4SfloatBlockEXT:
return "Astc4x4SfloatBlockEXT";
case Format::eAstc4x4SrgbBlock:
return "Astc4x4SrgbBlock";
case Format::eAstc5x4UnormBlock:
return "Astc5x4UnormBlock";
case Format::eAstc5x4SfloatBlockEXT:
return "Astc5x4SfloatBlockEXT";
case Format::eAstc5x4SrgbBlock:
return "Astc5x4SrgbBlock";
case Format::eAstc5x5UnormBlock:
return "Astc5x5UnormBlock";
case Format::eAstc5x5SfloatBlockEXT:
return "Astc5x5SfloatBlockEXT";
case Format::eAstc5x5SrgbBlock:
return "Astc5x5SrgbBlock";
case Format::eAstc6x5UnormBlock:
return "Astc6x5UnormBlock";
case Format::eAstc6x5SfloatBlockEXT:
return "Astc6x5SfloatBlockEXT";
case Format::eAstc6x5SrgbBlock:
return "Astc6x5SrgbBlock";
case Format::eAstc6x6UnormBlock:
return "Astc6x6UnormBlock";
case Format::eAstc6x6SfloatBlockEXT:
return "Astc6x6SfloatBlockEXT";
case Format::eAstc6x6SrgbBlock:
return "Astc6x6SrgbBlock";
case Format::eAstc8x5UnormBlock:
return "Astc8x5UnormBlock";
case Format::eAstc8x5SfloatBlockEXT:
return "Astc8x5SfloatBlockEXT";
case Format::eAstc8x5SrgbBlock:
return "Astc8x5SrgbBlock";
case Format::eAstc8x6UnormBlock:
return "Astc8x6UnormBlock";
case Format::eAstc8x6SfloatBlockEXT:
return "Astc8x6SfloatBlockEXT";
case Format::eAstc8x6SrgbBlock:
return "Astc8x6SrgbBlock";
case Format::eAstc8x8UnormBlock:
return "Astc8x8UnormBlock";
case Format::eAstc8x8SfloatBlockEXT:
return "Astc8x8SfloatBlockEXT";
case Format::eAstc8x8SrgbBlock:
return "Astc8x8SrgbBlock";
case Format::eAstc10x5UnormBlock:
return "Astc10x5UnormBlock";
case Format::eAstc10x5SfloatBlockEXT:
return "Astc10x5SfloatBlockEXT";
case Format::eAstc10x5SrgbBlock:
return "Astc10x5SrgbBlock";
case Format::eAstc10x6UnormBlock:
return "Astc10x6UnormBlock";
case Format::eAstc10x6SfloatBlockEXT:
return "Astc10x6SfloatBlockEXT";
case Format::eAstc10x6SrgbBlock:
return "Astc10x6SrgbBlock";
case Format::eAstc10x8UnormBlock:
return "Astc10x8UnormBlock";
case Format::eAstc10x8SfloatBlockEXT:
return "Astc10x8SfloatBlockEXT";
case Format::eAstc10x8SrgbBlock:
return "Astc10x8SrgbBlock";
case Format::eAstc10x10UnormBlock:
return "Astc10x10UnormBlock";
case Format::eAstc10x10SfloatBlockEXT:
return "Astc10x10SfloatBlockEXT";
case Format::eAstc10x10SrgbBlock:
return "Astc10x10SrgbBlock";
case Format::eAstc12x10UnormBlock:
return "Astc12x10UnormBlock";
case Format::eAstc12x10SfloatBlockEXT:
return "Astc12x10SfloatBlockEXT";
case Format::eAstc12x10SrgbBlock:
return "Astc12x10SrgbBlock";
case Format::eAstc12x12UnormBlock:
return "Astc12x12UnormBlock";
case Format::eAstc12x12SfloatBlockEXT:
return "Astc12x12SfloatBlockEXT";
case Format::eAstc12x12SrgbBlock:
return "Astc12x12SrgbBlock";
case Format::eD16Unorm:
return "D16Unorm";
case Format::eX8D24UnormPack32:
return "X8D24UnormPack32";
case Format::eD32Sfloat:
return "D32Sfloat";
case Format::eS8Uint:
return "S8Uint";
case Format::eD16UnormS8Uint:
return "D16UnormS8Uint";
case Format::eD24UnormS8Uint:
return "D24UnormS8Uint";
case Format::eD32SfloatS8Uint:
return "D32SfloatS8Uint";
default:
assert(0 && "format cannot be used with this function.");
return "";
}
}
bool is_format_srgb(Format format) noexcept {
switch (format) {
case Format::eR8Srgb:
case Format::eR8G8Srgb:
case Format::eR8G8B8Srgb:
case Format::eB8G8R8Srgb:
case Format::eR8G8B8A8Srgb:
case Format::eB8G8R8A8Srgb:
case Format::eA8B8G8R8SrgbPack32:
case Format::eBc1RgbSrgbBlock:
case Format::eBc1RgbaSrgbBlock:
case Format::eBc2SrgbBlock:
case Format::eBc3SrgbBlock:
case Format::eBc7SrgbBlock:
case Format::eEtc2R8G8B8SrgbBlock:
case Format::eEtc2R8G8B8A1SrgbBlock:
case Format::eEtc2R8G8B8A8SrgbBlock:
case Format::eAstc4x4SrgbBlock:
case Format::eAstc5x4SrgbBlock:
case Format::eAstc5x5SrgbBlock:
case Format::eAstc6x5SrgbBlock:
case Format::eAstc6x6SrgbBlock:
case Format::eAstc8x5SrgbBlock:
case Format::eAstc8x6SrgbBlock:
case Format::eAstc8x8SrgbBlock:
case Format::eAstc10x5SrgbBlock:
case Format::eAstc10x6SrgbBlock:
case Format::eAstc10x8SrgbBlock:
case Format::eAstc10x10SrgbBlock:
case Format::eAstc12x10SrgbBlock:
case Format::eAstc12x12SrgbBlock:
case Format::ePvrtc12BppSrgbBlockIMG:
case Format::ePvrtc14BppSrgbBlockIMG:
case Format::ePvrtc22BppSrgbBlockIMG:
case Format::ePvrtc24BppSrgbBlockIMG:
return true;
default:
return false;
}
}
vuk::Format unorm_to_srgb(vuk::Format format) noexcept {
switch (format) {
case Format::eR8Unorm:
return Format::eR8Srgb;
case Format::eR8G8Unorm:
return Format::eR8G8Srgb;
case Format::eR8G8B8Unorm:
return Format::eR8G8B8Srgb;
case Format::eB8G8R8Unorm:
return Format::eB8G8R8Srgb;
case Format::eR8G8B8A8Unorm:
return Format::eR8G8B8A8Srgb;
case Format::eB8G8R8A8Unorm:
return Format::eB8G8R8A8Srgb;
case Format::eA8B8G8R8UnormPack32:
return Format::eA8B8G8R8SrgbPack32;
case Format::eBc1RgbUnormBlock:
return Format::eBc1RgbSrgbBlock;
case Format::eBc1RgbaUnormBlock:
return Format::eBc1RgbaSrgbBlock;
case Format::eBc2UnormBlock:
return Format::eBc2SrgbBlock;
case Format::eBc3UnormBlock:
return Format::eBc3SrgbBlock;
case Format::eBc7UnormBlock:
return Format::eBc7SrgbBlock;
case Format::eEtc2R8G8B8UnormBlock:
return Format::eEtc2R8G8B8SrgbBlock;
case Format::eEtc2R8G8B8A1UnormBlock:
return Format::eEtc2R8G8B8A1SrgbBlock;
case Format::eEtc2R8G8B8A8UnormBlock:
return Format::eEtc2R8G8B8A8SrgbBlock;
case Format::eAstc4x4UnormBlock:
return Format::eAstc4x4SrgbBlock;
case Format::eAstc5x4UnormBlock:
return Format::eAstc5x4SrgbBlock;
case Format::eAstc5x5UnormBlock:
return Format::eAstc5x5SrgbBlock;
case Format::eAstc6x5UnormBlock:
return Format::eAstc6x5SrgbBlock;
case Format::eAstc6x6UnormBlock:
return Format::eAstc6x6SrgbBlock;
case Format::eAstc8x5UnormBlock:
return Format::eAstc8x5SrgbBlock;
case Format::eAstc8x6UnormBlock:
return Format::eAstc8x6SrgbBlock;
case Format::eAstc8x8UnormBlock:
return Format::eAstc8x8SrgbBlock;
case Format::eAstc10x5UnormBlock:
return Format::eAstc10x5SrgbBlock;
case Format::eAstc10x6UnormBlock:
return Format::eAstc10x6SrgbBlock;
case Format::eAstc10x8UnormBlock:
return Format::eAstc10x8SrgbBlock;
case Format::eAstc10x10UnormBlock:
return Format::eAstc10x10SrgbBlock;
case Format::eAstc12x10UnormBlock:
return Format::eAstc12x10SrgbBlock;
case Format::eAstc12x12UnormBlock:
return Format::eAstc12x12SrgbBlock;
case Format::ePvrtc12BppUnormBlockIMG:
return Format::ePvrtc12BppSrgbBlockIMG;
case Format::ePvrtc14BppUnormBlockIMG:
return Format::ePvrtc14BppSrgbBlockIMG;
case Format::ePvrtc22BppUnormBlockIMG:
return Format::ePvrtc22BppSrgbBlockIMG;
case Format::ePvrtc24BppUnormBlockIMG:
return Format::ePvrtc24BppSrgbBlockIMG;
default:
return Format::eUndefined;
}
}
vuk::Format srgb_to_unorm(vuk::Format format) noexcept {
switch (format) {
case Format::eR8Srgb:
return Format::eR8Unorm;
case Format::eR8G8Srgb:
return Format::eR8G8Unorm;
case Format::eR8G8B8Srgb:
return Format::eR8G8B8Unorm;
case Format::eB8G8R8Srgb:
return Format::eB8G8R8Unorm;
case Format::eR8G8B8A8Srgb:
return Format::eR8G8B8A8Unorm;
case Format::eB8G8R8A8Srgb:
return Format::eB8G8R8A8Unorm;
case Format::eA8B8G8R8SrgbPack32:
return Format::eA8B8G8R8UnormPack32;
case Format::eBc1RgbSrgbBlock:
return Format::eBc1RgbUnormBlock;
case Format::eBc1RgbaSrgbBlock:
return Format::eBc1RgbaUnormBlock;
case Format::eBc2SrgbBlock:
return Format::eBc2UnormBlock;
case Format::eBc3SrgbBlock:
return Format::eBc3UnormBlock;
case Format::eBc7SrgbBlock:
return Format::eBc7UnormBlock;
case Format::eEtc2R8G8B8SrgbBlock:
return Format::eEtc2R8G8B8UnormBlock;
case Format::eEtc2R8G8B8A1SrgbBlock:
return Format::eEtc2R8G8B8A1UnormBlock;
case Format::eEtc2R8G8B8A8SrgbBlock:
return Format::eEtc2R8G8B8A8UnormBlock;
case Format::eAstc4x4SrgbBlock:
return Format::eAstc4x4UnormBlock;
case Format::eAstc5x4SrgbBlock:
return Format::eAstc5x4UnormBlock;
case Format::eAstc5x5SrgbBlock:
return Format::eAstc5x5UnormBlock;
case Format::eAstc6x5SrgbBlock:
return Format::eAstc6x5UnormBlock;
case Format::eAstc6x6SrgbBlock:
return Format::eAstc6x6UnormBlock;
case Format::eAstc8x5SrgbBlock:
return Format::eAstc8x5UnormBlock;
case Format::eAstc8x6SrgbBlock:
return Format::eAstc8x6UnormBlock;
case Format::eAstc8x8SrgbBlock:
return Format::eAstc8x8UnormBlock;
case Format::eAstc10x5SrgbBlock:
return Format::eAstc10x5UnormBlock;
case Format::eAstc10x6SrgbBlock:
return Format::eAstc10x6UnormBlock;
case Format::eAstc10x8SrgbBlock:
return Format::eAstc10x8UnormBlock;
case Format::eAstc10x10SrgbBlock:
return Format::eAstc10x10UnormBlock;
case Format::eAstc12x10SrgbBlock:
return Format::eAstc12x10UnormBlock;
case Format::eAstc12x12SrgbBlock:
return Format::eAstc12x12UnormBlock;
case Format::ePvrtc12BppSrgbBlockIMG:
return Format::ePvrtc12BppUnormBlockIMG;
case Format::ePvrtc14BppSrgbBlockIMG:
return Format::ePvrtc14BppUnormBlockIMG;
case Format::ePvrtc22BppSrgbBlockIMG:
return Format::ePvrtc22BppUnormBlockIMG;
case Format::ePvrtc24BppSrgbBlockIMG:
return Format::ePvrtc24BppUnormBlockIMG;
default:
return Format::eUndefined;
}
}
} // namespace vuk<file_sep>#pragma once
#include "vuk/RelSpan.hpp"
#include "vuk/RenderGraph.hpp"
#include "vuk/ShortAlloc.hpp"
#include <optional>
namespace std {
template<>
struct hash<vuk::Resource> {
std::size_t operator()(vuk::Resource const& s) const noexcept {
return (size_t)((uintptr_t)s.name.name.c_str());
}
};
} // namespace std
namespace vuk {
inline bool is_write_access(Access ia) {
constexpr uint64_t write_mask = eColorResolveWrite | eColorWrite | eDepthStencilWrite | eFragmentWrite | eTransferWrite | eComputeWrite | eHostWrite |
eMemoryWrite | eRayTracingWrite | eAccelerationStructureBuildWrite | eClear;
return ia & write_mask;
}
inline bool is_read_access(Access ia) {
constexpr uint64_t read_mask = eColorResolveRead | eColorRead | eDepthStencilRead | eFragmentRead | eFragmentSampled | eTransferRead | eComputeRead |
eComputeSampled | eHostRead | eMemoryRead | eRayTracingRead | eRayTracingSampled | eAccelerationStructureBuildRead;
return ia & read_mask;
}
inline ImageLayout combine_layout(ImageLayout a, ImageLayout b) {
if (a == ImageLayout::eUndefined) {
return b;
}
if (b == ImageLayout::eUndefined) {
return a;
}
if (a == b) {
return a;
}
if ((a == ImageLayout::eDepthStencilReadOnlyOptimal && b == ImageLayout::eDepthStencilAttachmentOptimal) ||
(b == ImageLayout::eDepthStencilReadOnlyOptimal && a == ImageLayout::eDepthStencilAttachmentOptimal)) {
return ImageLayout::eDepthStencilAttachmentOptimal;
}
if ((a == ImageLayout::eReadOnlyOptimalKHR && b == ImageLayout::eAttachmentOptimalKHR) ||
(b == ImageLayout::eReadOnlyOptimalKHR && a == ImageLayout::eAttachmentOptimalKHR)) {
return ImageLayout::eAttachmentOptimalKHR;
}
assert(a != ImageLayout::ePresentSrcKHR && b != ImageLayout::ePresentSrcKHR);
return ImageLayout::eGeneral;
}
inline QueueResourceUse to_use(Access ia, DomainFlags domain) {
constexpr uint64_t color_read = eColorResolveRead | eColorRead;
constexpr uint64_t color_write = eColorResolveWrite | eColorWrite;
constexpr uint64_t color_rw = color_read | color_write;
QueueResourceUse qr{};
if (ia & color_read) {
qr.access |= AccessFlagBits::eColorAttachmentRead;
}
if (ia & color_write) {
qr.access |= AccessFlagBits::eColorAttachmentWrite;
}
if (ia & color_rw) {
qr.stages |= PipelineStageFlagBits::eColorAttachmentOutput;
qr.layout = combine_layout(qr.layout, ImageLayout::eAttachmentOptimalKHR);
}
if (ia & eDepthStencilRead) {
qr.access |= AccessFlagBits::eDepthStencilAttachmentRead;
qr.layout = combine_layout(qr.layout, ImageLayout::eReadOnlyOptimalKHR);
}
if (ia & eDepthStencilWrite) {
qr.access |= AccessFlagBits::eDepthStencilAttachmentWrite;
qr.layout = combine_layout(qr.layout, ImageLayout::eAttachmentOptimalKHR);
}
if (ia & eDepthStencilRW) {
qr.stages |= PipelineStageFlagBits::eEarlyFragmentTests | PipelineStageFlagBits::eLateFragmentTests;
}
if (ia & (eFragmentRead | eComputeRead | eVertexRead | eRayTracingRead)) {
qr.access |= AccessFlagBits::eShaderRead;
qr.layout = combine_layout(qr.layout, ImageLayout::eGeneral);
}
if (ia & eRayTracingRead) {
qr.access |= AccessFlagBits::eAccelerationStructureReadKHR;
qr.layout = combine_layout(qr.layout, ImageLayout::eGeneral);
}
if (ia & (eFragmentWrite | eComputeWrite | eRayTracingWrite)) {
qr.access |= AccessFlagBits::eShaderWrite;
qr.layout = combine_layout(qr.layout, ImageLayout::eGeneral);
}
if (ia & (eFragmentSampled | eComputeSampled | eRayTracingSampled)) {
qr.access |= AccessFlagBits::eShaderRead;
qr.layout = combine_layout(qr.layout, ImageLayout::eReadOnlyOptimalKHR);
}
if (ia & (eVertexRead | eVertexSampled)) {
qr.stages |= PipelineStageFlagBits::eVertexShader;
}
if (ia & (eFragmentRW | eFragmentSampled)) {
qr.stages |= PipelineStageFlagBits::eFragmentShader;
}
if (ia & (eComputeRW | eComputeSampled)) {
qr.stages |= PipelineStageFlagBits::eComputeShader;
}
if (ia & (eRayTracingRW | eRayTracingSampled)) {
qr.stages |= PipelineStageFlagBits::eRayTracingShaderKHR;
}
if (ia & eTransferRead) {
qr.access |= AccessFlagBits::eTransferRead;
qr.layout = combine_layout(qr.layout, ImageLayout::eTransferSrcOptimal);
}
if (ia & eTransferWrite) {
qr.access |= AccessFlagBits::eTransferWrite;
qr.layout = combine_layout(qr.layout, ImageLayout::eTransferDstOptimal);
}
if (ia & eTransferRW) {
qr.stages |= PipelineStageFlagBits::eTransfer;
}
if (ia & eAttributeRead) {
qr.access |= AccessFlagBits::eVertexAttributeRead;
qr.stages |= PipelineStageFlagBits::eVertexInput;
}
if (ia & eIndexRead) {
qr.access |= AccessFlagBits::eIndexRead;
qr.stages |= PipelineStageFlagBits::eVertexInput;
}
if (ia & eIndirectRead) {
qr.access |= AccessFlagBits::eIndirectCommandRead;
qr.stages |= PipelineStageFlagBits::eDrawIndirect;
}
if (ia & eAccelerationStructureBuildRead) {
qr.stages |= PipelineStageFlagBits::eAccelerationStructureBuildKHR;
qr.access |= AccessFlagBits::eAccelerationStructureReadKHR;
}
if (ia & eAccelerationStructureBuildWrite) {
qr.stages |= PipelineStageFlagBits::eAccelerationStructureBuildKHR;
qr.access |= AccessFlagBits::eAccelerationStructureWriteKHR;
}
if (ia & eHostRead) {
qr.access |= AccessFlagBits::eHostRead;
qr.layout = combine_layout(qr.layout, ImageLayout::eGeneral);
}
if (ia & eHostWrite) {
qr.access |= AccessFlagBits::eHostWrite;
qr.layout = combine_layout(qr.layout, ImageLayout::eGeneral);
}
if (ia & eHostRW) {
qr.stages |= PipelineStageFlagBits::eHost;
}
if (ia & eMemoryRead) {
qr.access |= AccessFlagBits::eMemoryRead;
qr.layout = combine_layout(qr.layout, ImageLayout::eGeneral);
}
if (ia & eMemoryWrite) {
qr.access |= AccessFlagBits::eMemoryWrite;
qr.layout = combine_layout(qr.layout, ImageLayout::eGeneral);
}
if (ia & eMemoryRW) {
qr.stages |= PipelineStageFlagBits::eAllCommands;
}
if (ia & eClear) {
qr.stages |= PipelineStageFlagBits::eTransfer;
qr.access |= AccessFlagBits::eTransferWrite;
qr.layout = combine_layout(qr.layout, ImageLayout::eTransferDstOptimal);
}
qr.domain = domain;
return qr;
}
// not all domains can support all stages, this function corrects stage flags
inline void scope_to_domain(VkPipelineStageFlags2KHR& src, DomainFlags flags) {
DomainFlags remove;
// if no graphics in domain, remove all graphics
if ((flags & DomainFlagBits::eGraphicsQueue) == DomainFlags{}) {
remove |= DomainFlagBits::eGraphicsQueue;
// if no graphics & compute in domain, remove all compute
if ((flags & DomainFlagBits::eComputeQueue) == DomainFlags{}) {
remove |= DomainFlagBits::eComputeQueue;
}
}
if (remove & DomainFlagBits::eGraphicsQueue) {
src &= (VkPipelineStageFlags2KHR)~0b11111111110;
}
if (remove & DomainFlagBits::eComputeQueue) {
src &= (VkPipelineStageFlags2KHR)~0b100000000000;
}
}
inline bool is_framebuffer_attachment(const Resource& r) {
if (r.type == Resource::Type::eBuffer)
return false;
switch (r.ia) {
case eColorWrite:
case eColorRW:
case eDepthStencilRW:
case eColorRead:
case eDepthStencilRead:
case eColorResolveRead:
case eColorResolveWrite:
return true;
default:
return false;
}
}
inline bool is_framebuffer_attachment(QueueResourceUse u) {
switch (u.layout) {
case vuk::ImageLayout::eColorAttachmentOptimal:
case vuk::ImageLayout::eDepthStencilAttachmentOptimal:
return true;
default:
return false;
}
}
inline bool is_write_access(QueueResourceUse u) {
if (u.access == vuk::AccessFlagBits{})
return false;
if (u.access & vuk::AccessFlagBits::eColorAttachmentWrite)
return true;
if (u.access & vuk::AccessFlagBits::eDepthStencilAttachmentWrite)
return true;
if (u.access & vuk::AccessFlagBits::eShaderWrite)
return true;
if (u.access & vuk::AccessFlagBits::eTransferWrite)
return true;
if (u.access & vuk::AccessFlagBits::eHostWrite)
return true;
if (u.access & vuk::AccessFlagBits::eMemoryWrite)
return true;
if (u.access & vuk::AccessFlagBits::eAccelerationStructureWriteKHR)
return true;
return false;
}
inline bool is_read_access(QueueResourceUse u) {
if (u.access == vuk::AccessFlagBits{})
return false;
return !is_write_access(u);
}
inline bool is_transfer_access(Access a) {
return (a & eTransferRW);
}
inline bool is_storage_access(Access a) {
return (a & (eComputeRW | eVertexRead | eFragmentRW | eRayTracingRW));
}
inline bool is_readonly_access(Access a) {
return a & ~(eTransferRW | eComputeRW | eVertexRead | eFragmentRW | eRayTracingRW);
}
struct Acquire {
QueueResourceUse src_use;
DomainFlagBits initial_domain = DomainFlagBits::eAny;
uint64_t initial_visibility;
bool unsynchronized = false;
};
struct BufferInfo {
QualifiedName name;
Buffer buffer;
FutureBase* attached_future = nullptr;
Acquire acquire;
RelSpan<ChainLink*> use_chains;
std::optional<Allocator> allocator = {};
};
struct AttachmentInfo {
QualifiedName name;
ImageAttachment attachment = {};
enum class Type { eInternal, eExternal, eSwapchain } type;
// swapchain for swapchain
Swapchain* swapchain = nullptr;
RelSpan<struct RenderPassInfo*> rp_uses;
FutureBase* attached_future = nullptr;
Acquire acquire;
Subrange::Image image_subrange;
int32_t parent_attachment = 0;
RelSpan<ChainLink*> use_chains = {};
std::optional<Allocator> allocator = {};
};
struct AttachmentRPInfo {
AttachmentInfo* attachment_info;
VkAttachmentDescription description = {};
QueueResourceUse initial, final;
std::optional<Clear> clear_value;
bool is_resolve_dst = false;
AttachmentInfo* resolve_src = nullptr;
};
} // namespace vuk
<file_sep>#include "TestContext.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/Partials.hpp"
#include <doctest/doctest.h>
using namespace vuk;
TEST_CASE("error: unattached resource") {
REQUIRE(test_context.prepare());
std::shared_ptr<RenderGraph> rg = std::make_shared<RenderGraph>("uatt");
rg->add_pass({
.resources = { "nonexistent_image"_image >> vuk::eColorWrite },
});
Compiler compiler;
REQUIRE_THROWS(compiler.compile(std::span{ &rg, 1 }, {}));
}
TEST_CASE("error: cbuf references unknown resource") {
REQUIRE(test_context.prepare());
std::shared_ptr<RenderGraph> rg = std::make_shared<RenderGraph>("uatt");
rg->add_pass({ .execute = [](vuk::CommandBuffer& cbuf) {
cbuf.bind_buffer(0, 0, "foo");
} });
Compiler compiler;
auto ex = compiler.link(std::span{ &rg, 1 }, {});
REQUIRE((bool)ex);
REQUIRE_THROWS(ex->execute(*test_context.allocator, {}));
}<file_sep>#if VUK_USE_SHADERC
#include "../src/ShadercIncluder.hpp"
#include <shaderc/shaderc.hpp>
#endif
#if VUK_USE_DXC
#ifdef _WIN32
// dxcapi.h expects the COM API to be present on Windows.
// On other platforms, the Vulkan SDK will have WinAdapter.h alongside dxcapi.h that is automatically included to stand in for the COM API.
#include <atlbase.h>
#endif
#include <dxc/dxcapi.h>
#define DXC_HR(hr, msg) \
if (FAILED(hr)) { \
throw ShaderCompilationException{ msg }; \
}
#endif
#include <algorithm>
#include <atomic>
#include "../src/ContextImpl.hpp"
#include "vuk/Allocator.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/Context.hpp"
#include "vuk/Exception.hpp"
#include "vuk/Program.hpp"
#include "vuk/Query.hpp"
#include "vuk/RenderGraph.hpp"
namespace {
/* TODO: I am currently unaware of any use case that would make supporting static loading worthwhile
void load_pfns_static(vuk::ContextCreateParameters::FunctionPointers& pfns) {
#define VUK_X(name) \
if (pfns.name == nullptr) { \
pfns.name = (PFN_##name)name; \
}
#define VUK_Y(name) \
if (pfns.name == nullptr) { \
pfns.name = (PFN_##name)name; \
}
#include "vuk/VulkanPFNOptional.hpp"
#include "vuk/VulkanPFNRequired.hpp"
#undef VUK_X
#undef VUK_Y
}*/
void load_pfns_dynamic(VkInstance instance, VkDevice device, vuk::ContextCreateParameters::FunctionPointers& pfns) {
#define VUK_X(name) \
if (pfns.name == nullptr) { \
pfns.name = (PFN_##name)pfns.vkGetDeviceProcAddr(device, #name); \
}
#define VUK_Y(name) \
if (pfns.name == nullptr) { \
pfns.name = (PFN_##name)pfns.vkGetInstanceProcAddr(instance, #name); \
}
#include "vuk/VulkanPFNOptional.hpp"
#include "vuk/VulkanPFNRequired.hpp"
#undef VUK_X
#undef VUK_Y
}
bool check_pfns(vuk::ContextCreateParameters::FunctionPointers& pfns) {
bool valid = true;
#define VUK_X(name) valid = valid && pfns.name;
#define VUK_Y(name) valid = valid && pfns.name;
#include "vuk/VulkanPFNRequired.hpp"
#undef VUK_X
#undef VUK_Y
return valid;
}
bool load_pfns(vuk::ContextCreateParameters params, vuk::ContextCreateParameters::FunctionPointers& pfns) {
// PFN loading
// if the user passes in PFNs, those will be used, always
if (check_pfns(pfns)) {
return true;
}
// we don't have all the PFNs, so we will load them if this is allowed
if (pfns.vkGetInstanceProcAddr && pfns.vkGetDeviceProcAddr && params.allow_dynamic_loading_of_vk_function_pointers) {
load_pfns_dynamic(params.instance, params.device, pfns);
return check_pfns(pfns);
} else {
return false;
}
}
} // namespace
namespace vuk {
Context::Context(ContextCreateParameters params) :
ContextCreateParameters::FunctionPointers(params.pointers),
instance(params.instance),
device(params.device),
physical_device(params.physical_device),
graphics_queue_family_index(params.graphics_queue_family_index),
compute_queue_family_index(params.compute_queue_family_index),
transfer_queue_family_index(params.transfer_queue_family_index) {
// TODO: conversion to static factory fn
bool pfn_load_success = load_pfns(params, *this);
assert(pfn_load_success);
[[maybe_unused]] bool dedicated_graphics_queue_ = false;
bool dedicated_compute_queue_ = false;
bool dedicated_transfer_queue_ = false;
if (params.graphics_queue != VK_NULL_HANDLE && params.graphics_queue_family_index != VK_QUEUE_FAMILY_IGNORED) {
dedicated_graphics_queue_ = true;
}
if (params.compute_queue != VK_NULL_HANDLE && params.compute_queue_family_index != VK_QUEUE_FAMILY_IGNORED) {
dedicated_compute_queue_ = true;
} else {
compute_queue_family_index = params.graphics_queue_family_index;
}
if (params.transfer_queue != VK_NULL_HANDLE && params.transfer_queue_family_index != VK_QUEUE_FAMILY_IGNORED) {
dedicated_transfer_queue_ = true;
} else {
transfer_queue_family_index = compute_queue ? params.compute_queue_family_index : params.graphics_queue_family_index;
}
impl = new ContextImpl(*this);
{
TimelineSemaphore ts;
impl->device_vk_resource->allocate_timeline_semaphores(std::span{ &ts, 1 }, {});
dedicated_graphics_queue.emplace(this->vkQueueSubmit, this->vkQueueSubmit2KHR, params.graphics_queue, params.graphics_queue_family_index, ts);
graphics_queue = &dedicated_graphics_queue.value();
}
if (dedicated_compute_queue_) {
TimelineSemaphore ts;
impl->device_vk_resource->allocate_timeline_semaphores(std::span{ &ts, 1 }, {});
dedicated_compute_queue.emplace(this->vkQueueSubmit, this->vkQueueSubmit2KHR, params.compute_queue, params.compute_queue_family_index, ts);
compute_queue = &dedicated_compute_queue.value();
} else {
compute_queue = graphics_queue;
}
if (dedicated_transfer_queue_) {
TimelineSemaphore ts;
impl->device_vk_resource->allocate_timeline_semaphores(std::span{ &ts, 1 }, {});
dedicated_transfer_queue.emplace(this->vkQueueSubmit, this->vkQueueSubmit2KHR, params.transfer_queue, params.transfer_queue_family_index, ts);
transfer_queue = &dedicated_transfer_queue.value();
} else {
transfer_queue = compute_queue ? compute_queue : graphics_queue;
}
this->vkGetPhysicalDeviceProperties(physical_device, &physical_device_properties);
min_buffer_alignment =
std::max(physical_device_properties.limits.minUniformBufferOffsetAlignment, physical_device_properties.limits.minStorageBufferOffsetAlignment);
VkPhysicalDeviceProperties2 prop2{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 };
if (this->vkCmdBuildAccelerationStructuresKHR) {
prop2.pNext = &rt_properties;
rt_properties.pNext = &as_properties;
}
this->vkGetPhysicalDeviceProperties2(physical_device, &prop2);
}
Context::Context(Context&& o) noexcept : impl(std::exchange(o.impl, nullptr)) {
instance = o.instance;
device = o.device;
physical_device = o.physical_device;
graphics_queue_family_index = o.graphics_queue_family_index;
compute_queue_family_index = o.compute_queue_family_index;
transfer_queue_family_index = o.transfer_queue_family_index;
dedicated_graphics_queue = std::move(o.dedicated_graphics_queue);
graphics_queue = &dedicated_graphics_queue.value();
dedicated_compute_queue = std::move(o.dedicated_compute_queue);
if (dedicated_compute_queue) {
compute_queue = &o.dedicated_compute_queue.value();
} else {
compute_queue = graphics_queue;
}
dedicated_transfer_queue = std::move(o.dedicated_transfer_queue);
if (dedicated_transfer_queue) {
transfer_queue = &dedicated_transfer_queue.value();
} else {
transfer_queue = compute_queue ? compute_queue : graphics_queue;
}
rt_properties = o.rt_properties;
impl->pipelinebase_cache.allocator = this;
impl->pool_cache.allocator = this;
impl->sampler_cache.allocator = this;
impl->shader_modules.allocator = this;
impl->descriptor_set_layouts.allocator = this;
impl->pipeline_layouts.allocator = this;
impl->device_vk_resource->ctx = this;
}
Context& Context::operator=(Context&& o) noexcept {
impl = std::exchange(o.impl, nullptr);
instance = o.instance;
device = o.device;
physical_device = o.physical_device;
graphics_queue_family_index = o.graphics_queue_family_index;
compute_queue_family_index = o.compute_queue_family_index;
transfer_queue_family_index = o.transfer_queue_family_index;
dedicated_graphics_queue = std::move(o.dedicated_graphics_queue);
graphics_queue = &dedicated_graphics_queue.value();
dedicated_compute_queue = std::move(o.dedicated_compute_queue);
if (dedicated_compute_queue) {
compute_queue = &o.dedicated_compute_queue.value();
} else {
compute_queue = graphics_queue;
}
dedicated_transfer_queue = std::move(o.dedicated_transfer_queue);
if (dedicated_transfer_queue) {
transfer_queue = &dedicated_transfer_queue.value();
} else {
transfer_queue = compute_queue ? compute_queue : graphics_queue;
}
impl->pipelinebase_cache.allocator = this;
impl->pool_cache.allocator = this;
impl->sampler_cache.allocator = this;
impl->shader_modules.allocator = this;
impl->descriptor_set_layouts.allocator = this;
impl->pipeline_layouts.allocator = this;
impl->device_vk_resource->ctx = this;
return *this;
}
bool Context::debug_enabled() const {
return this->vkSetDebugUtilsObjectNameEXT != nullptr;
}
void Context::set_name(const Texture& tex, Name name) {
if (!debug_enabled())
return;
set_name(tex.image->image, name);
set_name(tex.view->payload, name);
}
void Context::begin_region(const VkCommandBuffer& cb, Name name, std::array<float, 4> color) {
if (!debug_enabled())
return;
VkDebugUtilsLabelEXT label = { .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT };
label.pLabelName = name.c_str();
::memcpy(label.color, color.data(), sizeof(float) * 4);
this->vkCmdBeginDebugUtilsLabelEXT(cb, &label);
}
void Context::end_region(const VkCommandBuffer& cb) {
if (!debug_enabled())
return;
this->vkCmdEndDebugUtilsLabelEXT(cb);
}
Result<void> Context::submit_graphics(std::span<VkSubmitInfo> sis, VkFence fence) {
return graphics_queue->submit(sis, fence);
}
Result<void> Context::submit_graphics(std::span<VkSubmitInfo2KHR> sis) {
return graphics_queue->submit(sis, VK_NULL_HANDLE);
}
Result<void> Context::submit_transfer(std::span<VkSubmitInfo> sis, VkFence fence) {
return transfer_queue->submit(sis, fence);
}
Result<void> Context::submit_transfer(std::span<VkSubmitInfo2KHR> sis) {
return transfer_queue->submit(sis, VK_NULL_HANDLE);
}
void PersistentDescriptorSet::update_combined_image_sampler(unsigned binding, unsigned array_index, ImageView iv, Sampler sampler, ImageLayout layout) {
assert(binding < descriptor_bindings.size());
assert(array_index < descriptor_bindings[binding].size());
descriptor_bindings[binding][array_index].image = DescriptorImageInfo(sampler, iv, layout);
descriptor_bindings[binding][array_index].type = (DescriptorType)((uint8_t)DescriptorType::eCombinedImageSampler | (uint8_t)DescriptorType::ePendingWrite);
}
void PersistentDescriptorSet::update_storage_image(unsigned binding, unsigned array_index, ImageView iv) {
assert(binding < descriptor_bindings.size());
assert(array_index < descriptor_bindings[binding].size());
descriptor_bindings[binding][array_index].image = DescriptorImageInfo({}, iv, ImageLayout::eGeneral);
descriptor_bindings[binding][array_index].type = (DescriptorType)((uint8_t)DescriptorType::eStorageImage | (uint8_t)DescriptorType::ePendingWrite);
}
void PersistentDescriptorSet::update_uniform_buffer(unsigned binding, unsigned array_index, Buffer buffer) {
assert(binding < descriptor_bindings.size());
assert(array_index < descriptor_bindings[binding].size());
descriptor_bindings[binding][array_index].buffer = VkDescriptorBufferInfo{ buffer.buffer, buffer.offset, buffer.size };
descriptor_bindings[binding][array_index].type = (DescriptorType)((uint8_t)DescriptorType::eUniformBuffer | (uint8_t)DescriptorType::ePendingWrite);
}
void PersistentDescriptorSet::update_storage_buffer(unsigned binding, unsigned array_index, Buffer buffer) {
assert(binding < descriptor_bindings.size());
assert(array_index < descriptor_bindings[binding].size());
descriptor_bindings[binding][array_index].buffer = VkDescriptorBufferInfo{ buffer.buffer, buffer.offset, buffer.size };
descriptor_bindings[binding][array_index].type = (DescriptorType)((uint8_t)DescriptorType::eStorageBuffer | (uint8_t)DescriptorType::ePendingWrite);
}
void PersistentDescriptorSet::update_sampler(unsigned binding, unsigned array_index, Sampler sampler) {
assert(binding < descriptor_bindings.size());
assert(array_index < descriptor_bindings[binding].size());
descriptor_bindings[binding][array_index].image = DescriptorImageInfo(sampler, {}, {});
descriptor_bindings[binding][array_index].type = (DescriptorType)((uint8_t)DescriptorType::eSampler | (uint8_t)DescriptorType::ePendingWrite);
}
void PersistentDescriptorSet::update_sampled_image(unsigned binding, unsigned array_index, ImageView iv, ImageLayout layout) {
assert(binding < descriptor_bindings.size());
assert(array_index < descriptor_bindings[binding].size());
descriptor_bindings[binding][array_index].image = DescriptorImageInfo({}, iv, layout);
descriptor_bindings[binding][array_index].type = (DescriptorType)((uint8_t)DescriptorType::eSampledImage | (uint8_t)DescriptorType::ePendingWrite);
}
void PersistentDescriptorSet::update_acceleration_structure(unsigned binding, unsigned array_index, VkAccelerationStructureKHR as) {
assert(binding < descriptor_bindings.size());
assert(array_index < descriptor_bindings[binding].size());
descriptor_bindings[binding][array_index].as.as = as;
descriptor_bindings[binding][array_index].type =
(DescriptorType)((uint8_t)DescriptorType::eAccelerationStructureKHR | (uint8_t)DescriptorType::ePendingWrite);
}
void PersistentDescriptorSet::commit(Context& ctx) {
wdss.clear();
for (unsigned i = 0; i < descriptor_bindings.size(); i++) {
auto& db = descriptor_bindings[i];
for (unsigned j = 0; j < db.size(); j++) {
if ((uint8_t)db[j].type & (uint8_t)DescriptorType::ePendingWrite) { // clear pending write
db[j].type = (DescriptorType)((uint8_t)db[j].type & ~(uint8_t)DescriptorType::ePendingWrite);
if (db[j].type == DescriptorType::eAccelerationStructureKHR) {
db[j].as.wds = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR };
db[j].as.wds.accelerationStructureCount = 1;
db[j].as.wds.pAccelerationStructures = &db[j].as.as;
}
wdss.push_back(VkWriteDescriptorSet{ .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.pNext = db[j].type == DescriptorType::eAccelerationStructureKHR ? &db[j].as.wds : nullptr,
.dstSet = backing_set,
.dstBinding = i,
.dstArrayElement = j,
.descriptorCount = 1,
.descriptorType = DescriptorBinding::vk_descriptor_type(db[j].type),
.pImageInfo = &db[j].image.dii,
.pBufferInfo = &db[j].buffer });
}
}
}
ctx.vkUpdateDescriptorSets(ctx.device, (uint32_t)wdss.size(), wdss.data(), 0, nullptr);
}
ShaderModule Context::create(const create_info_t<ShaderModule>& cinfo) {
std::vector<uint32_t> spirv;
const uint32_t* spirv_ptr = nullptr;
size_t size = 0;
switch (cinfo.source.language) {
#if VUK_USE_SHADERC
case ShaderSourceLanguage::eGlsl: {
shaderc::Compiler compiler;
shaderc::CompileOptions options;
options.SetTargetEnvironment(shaderc_target_env_vulkan, shaderc_env_version_vulkan_1_2);
options.SetIncluder(std::make_unique<ShadercDefaultIncluder>());
for (auto& [k, v] : cinfo.defines) {
options.AddMacroDefinition(k, v);
}
const auto result = compiler.CompileGlslToSpv(cinfo.source.as_c_str(), shaderc_glsl_infer_from_source, cinfo.filename.c_str(), options);
if (result.GetCompilationStatus() != shaderc_compilation_status_success) {
std::string message = result.GetErrorMessage().c_str();
throw ShaderCompilationException{ message };
}
spirv = std::vector<uint32_t>{ result.cbegin(), result.cend() };
spirv_ptr = spirv.data();
size = spirv.size();
break;
}
#endif
#if VUK_USE_DXC
case ShaderSourceLanguage::eHlsl: {
std::vector<LPCWSTR> arguments;
arguments.push_back(L"-E");
arguments.push_back(L"main");
arguments.push_back(L"-spirv");
arguments.push_back(L"-fspv-target-env=vulkan1.1");
arguments.push_back(L"-fvk-use-gl-layout");
arguments.push_back(L"-no-warnings");
static const std::pair<const char*, HlslShaderStage> inferred[] = {
{ ".vert.", HlslShaderStage::eVertex }, { ".frag.", HlslShaderStage::ePixel }, { ".comp.", HlslShaderStage::eCompute },
{ ".geom.", HlslShaderStage::eGeometry }, { ".mesh.", HlslShaderStage::eMesh }, { ".hull.", HlslShaderStage::eHull },
{ ".dom.", HlslShaderStage::eDomain }, { ".amp.", HlslShaderStage::eAmplification }
};
static const std::unordered_map<HlslShaderStage, LPCWSTR> stage_mappings{
{ HlslShaderStage::eVertex, L"vs_6_7" }, { HlslShaderStage::ePixel, L"ps_6_7" }, { HlslShaderStage::eCompute, L"cs_6_7" },
{ HlslShaderStage::eGeometry, L"gs_6_7" }, { HlslShaderStage::eMesh, L"ms_6_7" }, { HlslShaderStage::eHull, L"hs_6_7" },
{ HlslShaderStage::eDomain, L"ds_6_7" }, { HlslShaderStage::eAmplification, L"as_6_7" }
};
HlslShaderStage shader_stage = cinfo.source.hlsl_stage;
if (shader_stage == HlslShaderStage::eInferred) {
for (const auto& [ext, stage] : inferred) {
if (cinfo.filename.find(ext) != std::string::npos) {
shader_stage = stage;
break;
}
}
}
assert((shader_stage != HlslShaderStage::eInferred) && "Failed to infer HLSL shader stage");
arguments.push_back(L"-T");
arguments.push_back(stage_mappings.at(shader_stage));
DxcBuffer source_buf;
source_buf.Ptr = cinfo.source.as_c_str();
source_buf.Size = cinfo.source.data.size() * 4;
source_buf.Encoding = 0;
CComPtr<IDxcCompiler3> compiler = nullptr;
DXC_HR(DxcCreateInstance(CLSID_DxcCompiler, __uuidof(IDxcCompiler3), (void**)&compiler), "Failed to create DXC compiler");
CComPtr<IDxcUtils> utils = nullptr;
DXC_HR(DxcCreateInstance(CLSID_DxcUtils, __uuidof(IDxcUtils), (void**)&utils), "Failed to create DXC utils");
CComPtr<IDxcIncludeHandler> include_handler = nullptr;
DXC_HR(utils->CreateDefaultIncludeHandler(&include_handler), "Failed to create include handler");
CComPtr<IDxcResult> result = nullptr;
DXC_HR(compiler->Compile(&source_buf, arguments.data(), arguments.size(), &*include_handler, __uuidof(IDxcResult), (void**)&result),
"Failed to compile with DXC");
CComPtr<IDxcBlobUtf8> errors = nullptr;
DXC_HR(result->GetOutput(DXC_OUT_ERRORS, IID_PPV_ARGS(&errors), nullptr), "Failed to get DXC compile errors");
if (errors && errors->GetStringLength() > 0) {
std::string message = errors->GetStringPointer();
throw ShaderCompilationException{ message };
}
CComPtr<IDxcBlob> output = nullptr;
DXC_HR(result->GetOutput(DXC_OUT_OBJECT, IID_PPV_ARGS(&output), nullptr), "Failed to get DXC output");
assert(output != nullptr);
const uint32_t* begin = (const uint32_t*)output->GetBufferPointer();
const uint32_t* end = begin + (output->GetBufferSize() / 4);
spirv = std::vector<uint32_t>{ begin, end };
spirv_ptr = spirv.data();
size = spirv.size();
break;
}
#endif
case ShaderSourceLanguage::eSpirv: {
spirv_ptr = cinfo.source.data_ptr;
size = cinfo.source.size;
break;
}
default:
assert(0);
}
Program p;
auto stage = p.introspect(spirv_ptr, size);
VkShaderModuleCreateInfo moduleCreateInfo{ .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
moduleCreateInfo.codeSize = size * sizeof(uint32_t);
moduleCreateInfo.pCode = spirv_ptr;
VkShaderModule sm;
this->vkCreateShaderModule(device, &moduleCreateInfo, nullptr, &sm);
std::string name = "ShaderModule: " + cinfo.filename;
set_name(sm, Name(name));
return { sm, p, stage };
}
PipelineBaseInfo Context::create(const create_info_t<PipelineBaseInfo>& cinfo) {
std::vector<VkPipelineShaderStageCreateInfo> psscis;
// accumulate descriptors from all stages
Program accumulated_reflection;
std::string pipe_name = "Pipeline:";
for (auto i = 0; i < cinfo.shaders.size(); i++) {
auto& contents = cinfo.shaders[i];
if (contents.data_ptr == nullptr) {
continue;
}
auto& sm = impl->shader_modules.acquire({ contents, cinfo.shader_paths[i], cinfo.defines });
VkPipelineShaderStageCreateInfo shader_stage{ .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
shader_stage.pSpecializationInfo = nullptr;
shader_stage.stage = sm.stage;
shader_stage.module = sm.shader_module;
shader_stage.pName = "main"; // TODO: make param
psscis.push_back(shader_stage);
accumulated_reflection.append(sm.reflection_info);
pipe_name += cinfo.shader_paths[i] + "+";
}
pipe_name = pipe_name.substr(0, pipe_name.size() - 1); // trim off last "+"
// acquire descriptor set layouts (1 per set)
// acquire pipeline layout
PipelineLayoutCreateInfo plci;
plci.dslcis = PipelineBaseCreateInfo::build_descriptor_layouts(accumulated_reflection, cinfo);
// use explicit descriptor layouts if there are any
for (auto& l : cinfo.explicit_set_layouts) {
plci.dslcis[l.index] = l;
}
plci.pcrs.insert(plci.pcrs.begin(), accumulated_reflection.push_constant_ranges.begin(), accumulated_reflection.push_constant_ranges.end());
plci.plci.pushConstantRangeCount = (uint32_t)accumulated_reflection.push_constant_ranges.size();
plci.plci.pPushConstantRanges = accumulated_reflection.push_constant_ranges.data();
std::array<DescriptorSetLayoutAllocInfo, VUK_MAX_SETS> dslai = {};
std::vector<VkDescriptorSetLayout> dsls;
for (auto& dsl : plci.dslcis) {
dsl.dslci.bindingCount = (uint32_t)dsl.bindings.size();
dsl.dslci.pBindings = dsl.bindings.data();
VkDescriptorSetLayoutBindingFlagsCreateInfo dslbfci{ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO };
if (dsl.flags.size() > 0) {
dslbfci.bindingCount = (uint32_t)dsl.bindings.size();
dslbfci.pBindingFlags = dsl.flags.data();
dsl.dslci.pNext = &dslbfci;
}
auto descset_layout_alloc_info = impl->descriptor_set_layouts.acquire(dsl);
dslai[dsl.index] = descset_layout_alloc_info;
dsls.push_back(dslai[dsl.index].layout);
}
plci.plci.pSetLayouts = dsls.data();
plci.plci.setLayoutCount = (uint32_t)dsls.size();
PipelineBaseInfo pbi;
pbi.psscis = std::move(psscis);
pbi.layout_info = dslai;
pbi.pipeline_layout = impl->pipeline_layouts.acquire(plci);
pbi.dslcis = std::move(plci.dslcis);
for (auto& dslci : pbi.dslcis) {
std::sort(dslci.bindings.begin(), dslci.bindings.end(), [](auto& a, auto& b) { return a.binding < b.binding; });
}
pbi.pipeline_name = Name(pipe_name);
pbi.reflection_info = accumulated_reflection;
pbi.binding_flags = cinfo.binding_flags;
pbi.variable_count_max = cinfo.variable_count_max;
pbi.hit_groups = cinfo.hit_groups;
pbi.max_ray_recursion_depth = cinfo.max_ray_recursion_depth;
return pbi;
}
bool Context::load_pipeline_cache(std::span<std::byte> data) {
VkPipelineCacheCreateInfo pcci{ .sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, .initialDataSize = data.size_bytes(), .pInitialData = data.data() };
this->vkDestroyPipelineCache(device, vk_pipeline_cache, nullptr);
this->vkCreatePipelineCache(device, &pcci, nullptr, &vk_pipeline_cache);
return true;
}
std::vector<std::byte> Context::save_pipeline_cache() {
size_t size;
std::vector<std::byte> data;
this->vkGetPipelineCacheData(device, vk_pipeline_cache, &size, nullptr);
data.resize(size);
this->vkGetPipelineCacheData(device, vk_pipeline_cache, &size, data.data());
return data;
}
Queue& Context::domain_to_queue(DomainFlags domain) const {
auto queue_only = (DomainFlagBits)(domain & DomainFlagBits::eQueueMask).m_mask;
switch (queue_only) {
case DomainFlagBits::eGraphicsQueue:
return *graphics_queue;
case DomainFlagBits::eComputeQueue:
return *compute_queue;
case DomainFlagBits::eTransferQueue:
return *transfer_queue;
default:
assert(0);
return *transfer_queue;
}
};
uint32_t Context::domain_to_queue_index(DomainFlags domain) const {
auto queue_only = (DomainFlagBits)(domain & DomainFlagBits::eQueueMask).m_mask;
switch (queue_only) {
case DomainFlagBits::eGraphicsQueue:
return graphics_queue_family_index;
case DomainFlagBits::eComputeQueue:
return compute_queue_family_index;
case DomainFlagBits::eTransferQueue:
return transfer_queue_family_index;
default:
assert(0);
return 0;
}
};
uint32_t Context::domain_to_queue_family_index(DomainFlags domain) const {
return domain_to_queue_index(domain);
}
Query Context::create_timestamp_query() {
return { impl->query_id_counter++ };
}
DeviceVkResource& Context::get_vk_resource() {
return *impl->device_vk_resource;
}
DescriptorSetLayoutAllocInfo Context::create(const create_info_t<DescriptorSetLayoutAllocInfo>& cinfo) {
DescriptorSetLayoutAllocInfo ret;
auto cinfo_mod = cinfo;
for (auto& b : cinfo_mod.bindings) {
b.descriptorType = DescriptorBinding::vk_descriptor_type((vuk::DescriptorType)b.descriptorType);
}
cinfo_mod.dslci.pBindings = cinfo_mod.bindings.data();
this->vkCreateDescriptorSetLayout(device, &cinfo_mod.dslci, nullptr, &ret.layout);
for (size_t i = 0; i < cinfo_mod.bindings.size(); i++) {
auto& b = cinfo_mod.bindings[i];
// if this is not a variable count binding, add it to the descriptor count
if (cinfo_mod.flags.size() <= i || !(cinfo_mod.flags[i] & to_integral(DescriptorBindingFlagBits::eVariableDescriptorCount))) {
auto index = b.descriptorType == VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR ? 11 : to_integral(b.descriptorType);
ret.descriptor_counts[index] += b.descriptorCount;
} else { // a variable count binding
ret.variable_count_binding = (uint32_t)i;
ret.variable_count_binding_type = DescriptorType(b.descriptorType);
ret.variable_count_binding_max_size = b.descriptorCount;
}
}
return ret;
}
VkPipelineLayout Context::create(const create_info_t<VkPipelineLayout>& cinfo) {
VkPipelineLayout pl;
this->vkCreatePipelineLayout(device, &cinfo.plci, nullptr, &pl);
return pl;
}
SwapchainRef Context::add_swapchain(Swapchain sw) {
std::lock_guard _(impl->swapchains_lock);
return &*impl->swapchains.emplace(sw);
}
void Context::remove_swapchain(SwapchainRef sw) {
std::lock_guard _(impl->swapchains_lock);
for (auto it = impl->swapchains.begin(); it != impl->swapchains.end(); it++) {
if (&*it == sw) {
impl->swapchains.erase(it);
return;
}
}
}
uint64_t Context::get_frame_count() const {
return impl->frame_counter;
}
void Context::create_named_pipeline(Name name, PipelineBaseCreateInfo ci) {
std::lock_guard _(impl->named_pipelines_lock);
impl->named_pipelines.insert_or_assign(name, &impl->pipelinebase_cache.acquire(std::move(ci)));
}
PipelineBaseInfo* Context::get_named_pipeline(Name name) {
std::lock_guard _(impl->named_pipelines_lock);
return impl->named_pipelines.at(name);
}
PipelineBaseInfo* Context::get_pipeline(const PipelineBaseCreateInfo& pbci) {
return &impl->pipelinebase_cache.acquire(pbci);
}
Program Context::get_pipeline_reflection_info(const PipelineBaseCreateInfo& pci) {
auto& res = impl->pipelinebase_cache.acquire(pci);
return res.reflection_info;
}
ShaderModule Context::compile_shader(ShaderSource source, std::string path) {
ShaderModuleCreateInfo sci;
sci.filename = std::move(path);
sci.source = std::move(source);
auto sm = impl->shader_modules.remove(sci);
if (sm) {
this->vkDestroyShaderModule(device, sm->shader_module, nullptr);
}
return impl->shader_modules.acquire(sci);
}
Texture Context::allocate_texture(Allocator& allocator, ImageCreateInfo ici, SourceLocationAtFrame loc) {
ici.imageType = ici.extent.depth > 1 ? ImageType::e3D : ici.extent.height > 1 ? ImageType::e2D : ImageType::e1D;
VkImageFormatListCreateInfo listci = { VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO };
auto unorm_fmt = srgb_to_unorm(ici.format);
auto srgb_fmt = unorm_to_srgb(ici.format);
VkFormat formats[2] = { (VkFormat)ici.format, unorm_fmt == vuk::Format::eUndefined ? (VkFormat)srgb_fmt : (VkFormat)unorm_fmt };
listci.pViewFormats = formats;
listci.viewFormatCount = formats[1] == VK_FORMAT_UNDEFINED ? 1 : 2;
if (listci.viewFormatCount > 1) {
ici.flags = vuk::ImageCreateFlagBits::eMutableFormat;
ici.pNext = &listci;
}
Unique<Image> dst = allocate_image(allocator, ici).value(); // TODO: dropping error
ImageViewCreateInfo ivci;
ivci.format = ici.format;
ivci.image = dst->image;
ivci.subresourceRange.aspectMask = format_to_aspect(ici.format);
ivci.subresourceRange.baseArrayLayer = 0;
ivci.subresourceRange.baseMipLevel = 0;
ivci.subresourceRange.layerCount = 1;
ivci.subresourceRange.levelCount = ici.mipLevels;
ivci.viewType = ici.imageType == ImageType::e3D ? ImageViewType::e3D : ici.imageType == ImageType::e2D ? ImageViewType::e2D : ImageViewType::e1D;
Texture tex{ std::move(dst), allocate_image_view(allocator, ivci, loc).value() }; // TODO: dropping error
tex.extent = ici.extent;
tex.format = ici.format;
tex.sample_count = ici.samples;
tex.layer_count = 1;
tex.level_count = ici.mipLevels;
return tex;
}
void Context::destroy(const DescriptorPool& dp) {
dp.destroy(*this, device);
}
void Context::destroy(const ShaderModule& sm) {
this->vkDestroyShaderModule(device, sm.shader_module, nullptr);
}
void Context::destroy(const DescriptorSetLayoutAllocInfo& ds) {
this->vkDestroyDescriptorSetLayout(device, ds.layout, nullptr);
}
void Context::destroy(const VkPipelineLayout& pl) {
this->vkDestroyPipelineLayout(device, pl, nullptr);
}
void Context::destroy(const DescriptorSet&) {
// no-op, we destroy the pools
}
void Context::destroy(const Sampler& sa) {
this->vkDestroySampler(device, sa.payload, nullptr);
}
void Context::destroy(const PipelineBaseInfo& pbi) {
// no-op, we don't own device objects
}
Context::~Context() {
if (impl) {
this->vkDeviceWaitIdle(device);
for (auto& s : impl->swapchains) {
for (auto& swiv : s.image_views) {
this->vkDestroyImageView(device, swiv.payload, nullptr);
}
this->vkDestroySwapchainKHR(device, s.swapchain, nullptr);
}
this->vkDestroyPipelineCache(device, vk_pipeline_cache, nullptr);
if (dedicated_graphics_queue) {
impl->device_vk_resource->deallocate_timeline_semaphores(std::span{ &dedicated_graphics_queue->get_submit_sync(), 1 });
}
if (dedicated_compute_queue) {
impl->device_vk_resource->deallocate_timeline_semaphores(std::span{ &dedicated_compute_queue->get_submit_sync(), 1 });
}
if (dedicated_transfer_queue) {
impl->device_vk_resource->deallocate_timeline_semaphores(std::span{ &dedicated_transfer_queue->get_submit_sync(), 1 });
}
delete impl;
}
}
uint64_t Context::get_unique_handle_id() {
return impl->unique_handle_id_counter++;
}
void Context::next_frame() {
impl->frame_counter++;
collect(impl->frame_counter);
}
Result<void> Context::wait_idle() {
std::unique_lock<std::recursive_mutex> graphics_lock;
if (dedicated_graphics_queue) {
graphics_lock = std::unique_lock{ graphics_queue->get_queue_lock() };
}
std::unique_lock<std::recursive_mutex> compute_lock;
if (dedicated_compute_queue) {
compute_lock = std::unique_lock{ compute_queue->get_queue_lock() };
}
std::unique_lock<std::recursive_mutex> transfer_lock;
if (dedicated_transfer_queue) {
transfer_lock = std::unique_lock{ transfer_queue->get_queue_lock() };
}
VkResult result = this->vkDeviceWaitIdle(device);
if (result < 0) {
return { expected_error, VkException{ result } };
}
return { expected_value };
}
void Context::collect(uint64_t frame) {
impl->collect(frame);
}
Unique<PersistentDescriptorSet>
Context::create_persistent_descriptorset(Allocator& allocator, DescriptorSetLayoutCreateInfo dslci, unsigned num_descriptors) {
dslci.dslci.bindingCount = (uint32_t)dslci.bindings.size();
dslci.dslci.pBindings = dslci.bindings.data();
VkDescriptorSetLayoutBindingFlagsCreateInfo dslbfci{ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO };
if (dslci.flags.size() > 0) {
dslbfci.bindingCount = (uint32_t)dslci.bindings.size();
dslbfci.pBindingFlags = dslci.flags.data();
dslci.dslci.pNext = &dslbfci;
}
auto& dslai = impl->descriptor_set_layouts.acquire(dslci, impl->frame_counter);
return create_persistent_descriptorset(allocator, { dslai, dslci, num_descriptors });
}
Unique<PersistentDescriptorSet> Context::create_persistent_descriptorset(Allocator& allocator, const PersistentDescriptorSetCreateInfo& ci) {
Unique<PersistentDescriptorSet> pds(allocator);
allocator.allocate_persistent_descriptor_sets(std::span{ &*pds, 1 }, std::span{ &ci, 1 });
return pds;
}
Unique<PersistentDescriptorSet>
Context::create_persistent_descriptorset(Allocator& allocator, const PipelineBaseInfo& base, unsigned set, unsigned num_descriptors) {
return create_persistent_descriptorset(allocator, { base.layout_info[set], base.dslcis[set], num_descriptors });
}
Sampler Context::create(const create_info_t<Sampler>& cinfo) {
VkSampler s;
this->vkCreateSampler(device, (VkSamplerCreateInfo*)&cinfo, nullptr, &s);
return wrap(s);
}
DescriptorPool Context::create(const create_info_t<DescriptorPool>& cinfo) {
return DescriptorPool{};
}
Sampler Context::acquire_sampler(const SamplerCreateInfo& sci, uint64_t absolute_frame) {
return impl->sampler_cache.acquire(sci, absolute_frame);
}
DescriptorPool& Context::acquire_descriptor_pool(const DescriptorSetLayoutAllocInfo& dslai, uint64_t absolute_frame) {
return impl->pool_cache.acquire(dslai, absolute_frame);
}
bool Context::is_timestamp_available(Query q) {
std::scoped_lock _(impl->query_lock);
auto it = impl->timestamp_result_map.find(q);
return (it != impl->timestamp_result_map.end());
}
std::optional<uint64_t> Context::retrieve_timestamp(Query q) {
std::scoped_lock _(impl->query_lock);
auto it = impl->timestamp_result_map.find(q);
if (it != impl->timestamp_result_map.end()) {
uint64_t res = it->second;
impl->timestamp_result_map.erase(it);
return res;
}
return {};
}
std::optional<double> Context::retrieve_duration(Query q1, Query q2) {
if (!is_timestamp_available(q1)) {
return {};
}
auto r1 = retrieve_timestamp(q1);
auto r2 = retrieve_timestamp(q2);
if (!r2) {
return {};
}
auto ns = impl->physical_device_properties.limits.timestampPeriod * (r2.value() - r1.value());
return ns * 1e-9;
}
Result<void> Context::make_timestamp_results_available(std::span<const TimestampQueryPool> pools) {
std::scoped_lock _(impl->query_lock);
std::array<uint64_t, TimestampQueryPool::num_queries> host_values;
for (auto& pool : pools) {
if (pool.count == 0) {
continue;
}
auto result = this->vkGetQueryPoolResults(device,
pool.pool,
0,
pool.count,
sizeof(uint64_t) * pool.count,
host_values.data(),
sizeof(uint64_t),
VkQueryResultFlagBits::VK_QUERY_RESULT_64_BIT | VkQueryResultFlagBits::VK_QUERY_RESULT_WAIT_BIT);
if (result != VK_SUCCESS) {
return { expected_error, AllocateException{ result } };
}
for (uint64_t i = 0; i < pool.count; i++) {
impl->timestamp_result_map.emplace(pool.queries[i], host_values[i]);
}
}
return { expected_value };
}
} // namespace vuk<file_sep>#pragma once
#include "glfw.hpp"
#include "utils.hpp"
#include "vuk/Allocator.hpp"
#include "vuk/AllocatorHelpers.hpp"
#include "vuk/CommandBuffer.hpp"
#include "vuk/Context.hpp"
#include "vuk/Partials.hpp"
#include "vuk/RenderGraph.hpp"
#include "vuk/SampledImage.hpp"
#include "vuk/resources/DeviceFrameResource.hpp"
#include <VkBootstrap.h>
#include <filesystem>
#include <functional>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <stdio.h>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
#include "backends/imgui_impl_glfw.h"
inline std::filesystem::path root;
namespace vuk {
struct ExampleRunner;
struct Example {
std::string_view name;
std::function<void(ExampleRunner&, vuk::Allocator&)> setup;
std::function<vuk::Future(ExampleRunner&, vuk::Allocator&, vuk::Future)> render;
std::function<void(ExampleRunner&, vuk::Allocator&)> cleanup;
};
struct ExampleRunner {
VkDevice device;
VkPhysicalDevice physical_device;
VkQueue graphics_queue;
VkQueue transfer_queue;
std::optional<Context> context;
std::optional<DeviceSuperFrameResource> superframe_resource;
std::optional<Allocator> superframe_allocator;
bool suspend = false;
vuk::SwapchainRef swapchain;
GLFWwindow* window;
VkSurfaceKHR surface;
vkb::Instance vkbinstance;
vkb::Device vkbdevice;
util::ImGuiData imgui_data;
std::vector<Future> futures;
std::mutex setup_lock;
double old_time = 0;
uint32_t num_frames = 0;
bool has_rt;
vuk::Unique<std::array<VkSemaphore, 3>> present_ready;
vuk::Unique<std::array<VkSemaphore, 3>> render_complete;
// when called during setup, enqueues a device-side operation to be completed before rendering begins
void enqueue_setup(Future&& fut) {
std::scoped_lock _(setup_lock);
futures.emplace_back(std::move(fut));
}
plf::colony<vuk::SampledImage> sampled_images;
std::vector<Example*> examples;
ExampleRunner();
void setup() {
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForVulkan(window, true);
imgui_data = util::ImGui_ImplVuk_Init(*superframe_allocator);
{
std::vector<std::jthread> threads;
for (auto& ex : examples) {
threads.emplace_back(std::jthread([&] { ex->setup(*this, *superframe_allocator); }));
}
}
glfwSetWindowSizeCallback(window, [](GLFWwindow* window, int width, int height) {
ExampleRunner& runner = *reinterpret_cast<ExampleRunner*>(glfwGetWindowUserPointer(window));
if (width == 0 && height == 0) {
runner.suspend = true;
} else {
runner.superframe_allocator->deallocate(std::span{ &runner.swapchain->swapchain, 1 });
runner.superframe_allocator->deallocate(runner.swapchain->image_views);
runner.context->remove_swapchain(runner.swapchain);
runner.swapchain = runner.context->add_swapchain(util::make_swapchain(runner.vkbdevice, runner.swapchain->swapchain));
for (auto& iv : runner.swapchain->image_views) {
runner.context->set_name(iv.payload, "Swapchain ImageView");
}
runner.suspend = false;
}
});
}
void render();
void cleanup() {
context->wait_idle();
for (auto& ex : examples) {
if (ex->cleanup) {
ex->cleanup(*this, *superframe_allocator);
}
}
}
void set_window_title(std::string title) {
glfwSetWindowTitle(window, title.c_str());
}
double get_time() {
return glfwGetTime();
}
~ExampleRunner() {
present_ready.reset();
render_complete.reset();
imgui_data.font_texture.view.reset();
imgui_data.font_texture.image.reset();
superframe_resource.reset();
context.reset();
auto vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR)vkbinstance.fp_vkGetInstanceProcAddr(vkbinstance.instance, "vkDestroySurfaceKHR");
vkDestroySurfaceKHR(vkbinstance.instance, surface, nullptr);
destroy_window_glfw(window);
vkb::destroy_device(vkbdevice);
vkb::destroy_instance(vkbinstance);
}
static ExampleRunner& get_runner() {
static ExampleRunner runner;
return runner;
}
};
inline vuk::ExampleRunner::ExampleRunner() {
vkb::InstanceBuilder builder;
builder.request_validation_layers()
.set_debug_callback([](VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) -> VkBool32 {
auto ms = vkb::to_string_message_severity(messageSeverity);
auto mt = vkb::to_string_message_type(messageType);
printf("[%s: %s](user defined)\n%s\n", ms, mt, pCallbackData->pMessage);
return VK_FALSE;
})
.set_app_name("vuk_example")
.set_engine_name("vuk")
.require_api_version(1, 2, 0)
.set_app_version(0, 1, 0);
auto inst_ret = builder.build();
if (!inst_ret) {
throw std::runtime_error("Couldn't initialise instance");
}
has_rt = true;
vkbinstance = inst_ret.value();
auto instance = vkbinstance.instance;
vkb::PhysicalDeviceSelector selector{ vkbinstance };
window = create_window_glfw("Vuk example", true);
glfwSetWindowUserPointer(window, this);
surface = create_surface_glfw(vkbinstance.instance, window);
selector.set_surface(surface)
.set_minimum_version(1, 0)
.add_required_extension(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME)
.add_required_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME)
.add_required_extension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME)
.add_required_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
auto phys_ret = selector.select();
vkb::PhysicalDevice vkbphysical_device;
if (!phys_ret) {
has_rt = false;
vkb::PhysicalDeviceSelector selector2{ vkbinstance };
selector2.set_surface(surface).set_minimum_version(1, 0).add_required_extension(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME);
auto phys_ret2 = selector2.select();
if (!phys_ret2) {
throw std::runtime_error("Couldn't create physical device");
} else {
vkbphysical_device = phys_ret2.value();
}
} else {
vkbphysical_device = phys_ret.value();
}
physical_device = vkbphysical_device.physical_device;
vkb::DeviceBuilder device_builder{ vkbphysical_device };
VkPhysicalDeviceVulkan12Features vk12features{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES };
vk12features.timelineSemaphore = true;
vk12features.descriptorBindingPartiallyBound = true;
vk12features.descriptorBindingUpdateUnusedWhilePending = true;
vk12features.shaderSampledImageArrayNonUniformIndexing = true;
vk12features.runtimeDescriptorArray = true;
vk12features.descriptorBindingVariableDescriptorCount = true;
vk12features.hostQueryReset = true;
vk12features.bufferDeviceAddress = true;
vk12features.shaderOutputLayer = true;
VkPhysicalDeviceVulkan11Features vk11features{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES };
vk11features.shaderDrawParameters = true;
VkPhysicalDeviceFeatures2 vk10features{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR };
vk10features.features.shaderInt64 = true;
VkPhysicalDeviceSynchronization2FeaturesKHR sync_feat{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR,
.synchronization2 = true };
VkPhysicalDeviceAccelerationStructureFeaturesKHR accelFeature{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR,
.accelerationStructure = true };
VkPhysicalDeviceRayTracingPipelineFeaturesKHR rtPipelineFeature{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR,
.rayTracingPipeline = true };
device_builder = device_builder.add_pNext(&vk12features).add_pNext(&vk11features).add_pNext(&sync_feat).add_pNext(&accelFeature).add_pNext(&vk10features);
if (has_rt) {
device_builder = device_builder.add_pNext(&rtPipelineFeature);
}
auto dev_ret = device_builder.build();
if (!dev_ret) {
throw std::runtime_error("Couldn't create device");
}
vkbdevice = dev_ret.value();
graphics_queue = vkbdevice.get_queue(vkb::QueueType::graphics).value();
auto graphics_queue_family_index = vkbdevice.get_queue_index(vkb::QueueType::graphics).value();
transfer_queue = vkbdevice.get_queue(vkb::QueueType::transfer).value();
auto transfer_queue_family_index = vkbdevice.get_queue_index(vkb::QueueType::transfer).value();
device = vkbdevice.device;
ContextCreateParameters::FunctionPointers fps;
fps.vkGetInstanceProcAddr = vkbinstance.fp_vkGetInstanceProcAddr;
fps.vkGetDeviceProcAddr = vkbinstance.fp_vkGetDeviceProcAddr;
context.emplace(ContextCreateParameters{ instance,
device,
physical_device,
graphics_queue,
graphics_queue_family_index,
VK_NULL_HANDLE,
VK_QUEUE_FAMILY_IGNORED,
transfer_queue,
transfer_queue_family_index,
fps });
const unsigned num_inflight_frames = 3;
superframe_resource.emplace(*context, num_inflight_frames);
superframe_allocator.emplace(*superframe_resource);
swapchain = context->add_swapchain(util::make_swapchain(vkbdevice, {}));
present_ready = vuk::Unique<std::array<VkSemaphore, 3>>(*superframe_allocator);
render_complete = vuk::Unique<std::array<VkSemaphore, 3>>(*superframe_allocator);
superframe_allocator->allocate_semaphores(*present_ready);
superframe_allocator->allocate_semaphores(*render_complete);
}
} // namespace vuk
namespace util {
struct Register {
Register(vuk::Example& x) {
vuk::ExampleRunner::get_runner().examples.push_back(&x);
}
};
} // namespace util
#define CONCAT_IMPL(x, y) x##y
#define MACRO_CONCAT(x, y) CONCAT_IMPL(x, y)
#define REGISTER_EXAMPLE(x) util::Register MACRO_CONCAT(_reg_, __LINE__)(x)
<file_sep>#pragma once
#include "vuk/RelSpan.hpp"
#include "vuk/RenderGraph.hpp"
#include <optional>
// struct describing use chains
namespace vuk {
struct ChainAccess {
int32_t pass;
int32_t resource = -1;
};
struct ChainLink {
ChainLink* source = nullptr; // in subchains, this denotes the end of the undiverged chain
ChainLink* prev = nullptr; // if this came from a previous undef, we link them together
std::optional<ChainAccess> def;
RelSpan<ChainAccess> reads;
Resource::Type type;
std::optional<ChainAccess> undef;
ChainLink* next = nullptr; // if this links to a def, we link them together
ChainLink* destination = nullptr; // in subchains, this denotes the start of the converged chain
RelSpan<ChainLink*> child_chains;
};
} // namespace vuk<file_sep>#pragma once
#include <span>
#include <vector>
namespace vuk {
template<class T>
struct RelSpan {
size_t offset0 = 0;
size_t offset1 = 0;
constexpr size_t size() const noexcept {
return offset1 - offset0;
}
constexpr std::span<T> to_span(T* base) const noexcept {
return std::span{ base + offset0, base + offset1 };
}
constexpr std::span<T> to_span(std::vector<T>& base) const noexcept {
return std::span{ base.data() + offset0, base.data() + offset1 };
}
constexpr std::span<const T> to_span(const std::vector<T>& base) const noexcept {
return std::span{ base.data() + offset0, base.data() + offset1 };
}
void append(std::vector<T>& base, T value) {
// easy case: we have space at the end of the vector
if (offset1 == base.size()) {
base.push_back(std::move(value));
offset1++;
return;
}
// non-easy case: copy the span to the end and extend
auto new_offset0 = base.size();
base.insert(base.begin() + new_offset0, base.begin() + offset0, base.begin() + offset1);
base.push_back(std::move(value));
offset0 = new_offset0;
offset1 = base.size();
}
};
} // namespace vuk<file_sep>Rendergraph
===========
.. doxygenstruct:: vuk::Resource
:members:
.. doxygenstruct:: vuk::RenderGraph
:members:
.. doxygenstruct:: vuk::ExecutableRenderGraph
:members:
Futures
=======
vuk Futures allow you to reason about computation of resources that happened in the past, or will happen in the future. In general the limitation of RenderGraphs are that they don't know the state of the resources produces by previous computation, or the state the resources should be left in for future computation, so these states must be provided manually (this is error-prone). Instead you can encapsulate the computation and its result into a Future, which can then serve as an input to other RenderGraphs.
Futures can be constructed from a RenderGraph and a named Resource that is considered to be the output. A Future can optionally own the RenderGraph - but in all cases a Future must outlive the RenderGraph it references.
You can submit Futures manually, which will compile, execute and submit the RenderGraph it references. In this case when you use this Future as input to another RenderGraph it will wait for the result on the device. If a Future has not yet been submitted, the contained RenderGraph is simply appended as a subgraph (i.e. inlined).
It is also possible to wait for the result to be produced to be available on the host - but this forces a CPU-GPU sync and should be used sparingly.
.. doxygenclass:: vuk::Future
:members:
Composing render graphs
=======================
Futures make easy to compose complex operations and effects out of RenderGraph building blocks, linked by Futures. These building blocks are termed partials, and vuk provides some built-in. Such partials are functions that take a number of Futures as input, and produce a Future as output.
The built-in partials can be found below. Built on these, there are some convenience functions that couple resource allocation with initial data (`create_XXX()`).
.. doxygenfile:: include/vuk/Partials.hpp<file_sep>#ifdef VUK_BUILD_TESTS
#define DOCTEST_CONFIG_IMPLEMENT
#endif
#include <doctest/doctest.h>
#ifdef VUK_TEST_RUNNER
#include "TestContext.hpp"
namespace vuk {
TestContext test_context;
}
int main(int argc, char** argv) {
return doctest::Context(argc, argv).run();
}
#endif<file_sep>#include "../src/RenderGraphUtil.hpp"
#include "example_runner.hpp"
#include "vuk/RenderGraphReflection.hpp"
std::vector<vuk::QualifiedName> chosen_resource;
bool render_all = true;
vuk::SingleSwapchainRenderBundle bundle;
void vuk::ExampleRunner::render() {
Compiler compiler;
chosen_resource.resize(examples.size());
vuk::wait_for_futures_explicit(*superframe_allocator, compiler, futures);
futures.clear();
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
while (suspend) {
glfwWaitEvents();
}
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(ImGui::GetIO().DisplaySize.x - 352.f, 2));
ImGui::SetNextWindowSize(ImVec2(350, 0));
ImGui::Begin("Example selector", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoResize);
ImGui::Checkbox("All", &render_all);
ImGui::SameLine();
static vuk::Example* item_current = examples[7]; // Here our selection is a single pointer stored outside the object.
if (!render_all) {
if (ImGui::BeginCombo("Examples", item_current->name.data(), ImGuiComboFlags_None)) {
for (int n = 0; n < examples.size(); n++) {
bool is_selected = (item_current == examples[n]);
if (ImGui::Selectable(examples[n]->name.data(), is_selected))
item_current = examples[n];
if (is_selected)
ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming
// navigation branch)
}
ImGui::EndCombo();
}
}
ImGui::End();
auto& frame_resource = superframe_resource->get_next_frame();
context->next_frame();
Allocator frame_allocator(frame_resource);
if (!render_all) { // render a single full window example
RenderGraph rg("runner");
vuk::Name attachment_name = item_current->name;
rg.attach_swapchain("_swp", swapchain);
rg.clear_image("_swp", attachment_name, vuk::ClearColor{ 0.3f, 0.5f, 0.3f, 1.0f });
auto fut = item_current->render(*this, frame_allocator, Future{ std::make_shared<RenderGraph>(std::move(rg)), attachment_name });
ImGui::Render();
fut = util::ImGui_ImplVuk_Render(frame_allocator, std::move(fut), imgui_data, ImGui::GetDrawData(), sampled_images);
// make a new RG that will take care of putting the swapchain image into present and releasing it from the rg
std::shared_ptr<RenderGraph> rg_p(std::make_shared<RenderGraph>("presenter"));
rg_p->attach_in("_src", std::move(fut));
// we tell the rendergraph that _src will be used for presenting after the rendergraph
rg_p->release_for_present("_src");
auto erg = *compiler.link(std::span{ &rg_p, 1 }, {});
bundle = *acquire_one(*context, swapchain, (*present_ready)[context->get_frame_count() % 3], (*render_complete)[context->get_frame_count() % 3]);
auto result = *execute_submit(frame_allocator, std::move(erg), std::move(bundle));
present_to_one(*context, std::move(result));
sampled_images.clear();
} else { // render all examples as imgui windows
std::shared_ptr<RenderGraph> rg = std::make_shared<RenderGraph>("runner");
size_t i = 0;
for (auto& ex : examples) {
std::shared_ptr<RenderGraph> rgx = std::make_shared<RenderGraph>(ex->name);
ImGui::SetNextWindowSize(ImVec2(250, 250), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowPos(ImVec2((float)(i % 4) * 250, ((float)i / 4) * 250), ImGuiCond_FirstUseEver);
ImGui::Begin(ex->name.data());
auto size = ImGui::GetContentRegionAvail();
size.x = size.x <= 0 ? 1 : size.x;
size.y = size.y <= 0 ? 1 : size.y;
rgx->attach_and_clear_image("_img",
{ .extent = vuk::Dimension3D::absolute((uint32_t)size.x, (uint32_t)size.y),
.format = swapchain->format,
.sample_count = vuk::Samples::e1,
.level_count = 1,
.layer_count = 1 },
vuk::ClearColor(0.1f, 0.2f, 0.3f, 1.f));
auto rg_frag_fut = ex->render(*this, frame_allocator, Future{ rgx, "_img" });
Name attachment_name_out = Name(std::string(ex->name) + "_final");
auto rg_frag = rg_frag_fut.get_render_graph();
compiler.compile({ &rg_frag, 1 }, {});
if (auto use_chains = compiler.get_use_chains(); use_chains.size() > 1) {
const auto& bound_attachments = compiler.get_bound_attachments();
for (const auto head : use_chains) {
if (head->type != Resource::Type::eImage) {
continue;
}
auto& att_info = compiler.get_chain_attachment(head);
auto samples = att_info.attachment.sample_count.count;
bool disable = (samples != vuk::SampleCountFlagBits::eInfer && samples != vuk::SampleCountFlagBits::e1);
auto maybe_name = compiler.get_last_use_name(head);
std::string btn_id = "";
if (maybe_name->name.to_sv() == attachment_name_out) {
btn_id = "F";
} else {
auto usage = compiler.compute_usage(head);
if (usage & vuk::ImageUsageFlagBits::eColorAttachment) {
btn_id += "C";
} else if (usage & vuk::ImageUsageFlagBits::eDepthStencilAttachment) {
btn_id += "D";
} else if (usage & (vuk::ImageUsageFlagBits::eTransferSrc | vuk::ImageUsageFlagBits::eTransferDst)) {
btn_id += "X";
}
}
if (disable) {
btn_id += " (MS)";
} else {
btn_id += "##" + std::string(att_info.name.prefix.to_sv()) + std::string(att_info.name.name.to_sv());
}
if (disable) {
ImGui::TextDisabled("%s", btn_id.c_str());
} else {
if (maybe_name) {
if (ImGui::Button(btn_id.c_str())) {
if (maybe_name->name.to_sv() == ex->name) {
chosen_resource[i] = QualifiedName{ {}, attachment_name_out };
} else {
if (maybe_name) {
chosen_resource[i] = *maybe_name;
}
}
}
}
}
if (ImGui::IsItemHovered())
ImGui::SetTooltip("%s", att_info.name.name.c_str());
ImGui::SameLine();
}
ImGui::NewLine();
}
if (chosen_resource[i].is_invalid())
chosen_resource[i].name = attachment_name_out;
if (chosen_resource[i].name != attachment_name_out) {
auto othfut = Future(rg_frag, chosen_resource[i]);
rg->attach_in(attachment_name_out, std::move(othfut));
} else {
rg->attach_in(attachment_name_out, std::move(rg_frag_fut));
}
auto si = vuk::make_sampled_image(NameReference{ rg.get(), QualifiedName({}, attachment_name_out) }, imgui_data.font_sci);
ImGui::Image(&*sampled_images.emplace(si), ImGui::GetContentRegionAvail());
ImGui::End();
i++;
}
ImGui::Render();
rg->clear_image("SWAPCHAIN", "SWAPCHAIN+", vuk::ClearColor{ 0.3f, 0.5f, 0.3f, 1.0f });
rg->attach_swapchain("SWAPCHAIN", swapchain);
auto fut = util::ImGui_ImplVuk_Render(frame_allocator, Future{ rg, "SWAPCHAIN+" }, imgui_data, ImGui::GetDrawData(), sampled_images);
std::shared_ptr<RenderGraph> rg_p(std::make_shared<RenderGraph>("presenter"));
rg_p->attach_in("_src", std::move(fut));
// we tell the rendergraph that _src will be used for presenting after the rendergraph
rg_p->release_for_present("_src");
auto erg = *compiler.link(std::span{ &rg_p, 1 }, {});
bundle = *acquire_one(*context, swapchain, (*present_ready)[context->get_frame_count() % 3], (*render_complete)[context->get_frame_count() % 3]);
auto result = *execute_submit(frame_allocator, std::move(erg), std::move(bundle));
present_to_one(*context, std::move(result));
sampled_images.clear();
}
if (++num_frames == 16) {
auto new_time = get_time();
auto delta = new_time - old_time;
auto per_frame_time = delta / 16 * 1000;
old_time = new_time;
num_frames = 0;
set_window_title(std::string("Vuk example browser [") + std::to_string(per_frame_time) + " ms / " + std::to_string(1000 / per_frame_time) + " FPS]");
}
}
}
int main(int argc, char** argv) {
auto path_to_root = std::filesystem::relative(VUK_EX_PATH_ROOT, VUK_EX_PATH_TGT);
root = std::filesystem::canonical(std::filesystem::path(argv[0]).parent_path() / path_to_root);
// very simple error handling in the example framework: we don't check for errors and just let them be converted into exceptions that are caught at top level
try {
vuk::ExampleRunner::get_runner().setup();
vuk::ExampleRunner::get_runner().render();
vuk::ExampleRunner::get_runner().cleanup();
} catch (vuk::Exception& e) {
fprintf(stderr, "%s", e.what());
}
}
<file_sep>#pragma once
#include "Types.hpp"
#include <assert.h>
namespace vuk {
enum class BufferUsageFlagBits : VkBufferUsageFlags {
eTransferRead = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
eTransferWrite = VK_BUFFER_USAGE_TRANSFER_DST_BIT,
eUniformTexelBuffer = VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT,
eStorageTexelBuffer = VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT,
eUniformBuffer = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
eStorageBuffer = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
eIndexBuffer = VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
eVertexBuffer = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
eIndirectBuffer = VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT,
eShaderDeviceAddress = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT,
eTransformFeedbackBufferEXT = VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT,
eTransformFeedbackCounterBufferEXT = VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT,
eConditionalRenderingEXT = VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT,
eShaderDeviceAddressEXT = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT,
eShaderDeviceAddressKHR = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR,
eAccelerationStructureBuildInputReadOnlyKHR = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR,
eAccelerationStructureStorageKHR = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR,
eShaderBindingTable = VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR
};
using BufferUsageFlags = Flags<BufferUsageFlagBits>;
inline constexpr BufferUsageFlags operator|(BufferUsageFlagBits bit0, BufferUsageFlagBits bit1) noexcept {
return BufferUsageFlags(bit0) | bit1;
}
inline constexpr BufferUsageFlags operator&(BufferUsageFlagBits bit0, BufferUsageFlagBits bit1) noexcept {
return BufferUsageFlags(bit0) & bit1;
}
inline constexpr BufferUsageFlags operator^(BufferUsageFlagBits bit0, BufferUsageFlagBits bit1) noexcept {
return BufferUsageFlags(bit0) ^ bit1;
}
static constexpr vuk::BufferUsageFlags all_buffer_usage_flags =
BufferUsageFlagBits::eTransferRead | BufferUsageFlagBits::eTransferWrite | BufferUsageFlagBits::eUniformTexelBuffer |
BufferUsageFlagBits::eStorageTexelBuffer | BufferUsageFlagBits::eUniformBuffer | BufferUsageFlagBits::eStorageBuffer | BufferUsageFlagBits::eIndexBuffer |
BufferUsageFlagBits::eVertexBuffer | BufferUsageFlagBits::eIndirectBuffer | BufferUsageFlagBits::eShaderDeviceAddress |
BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR | BufferUsageFlagBits::eAccelerationStructureStorageKHR |
BufferUsageFlagBits::eShaderBindingTable;
/// @brief A contiguous portion of GPU-visible memory that can be used for storing buffer-type data
struct Buffer {
void* allocation = nullptr;
VkBuffer buffer = VK_NULL_HANDLE;
size_t offset = 0;
size_t size = ~(0u);
uint64_t device_address = 0;
std::byte* mapped_ptr = nullptr;
MemoryUsage memory_usage;
constexpr bool operator==(const Buffer& o) const noexcept {
return buffer == o.buffer && offset == o.offset && size == o.size;
}
constexpr explicit operator bool() const noexcept {
return buffer != VK_NULL_HANDLE;
}
/// @brief Create a new Buffer by offsetting
[[nodiscard]] Buffer add_offset(VkDeviceSize offset_to_add) {
assert(offset_to_add <= size);
return { allocation,
buffer,
offset + offset_to_add,
size - offset_to_add,
device_address != 0 ? device_address + offset_to_add : 0,
mapped_ptr != nullptr ? mapped_ptr + offset_to_add : nullptr,
memory_usage };
}
/// @brief Create a new Buffer that is a subset of the original
[[nodiscard]] Buffer subrange(VkDeviceSize new_offset, VkDeviceSize new_size) {
assert(new_offset + new_size <= size);
return { allocation,
buffer,
offset + new_offset,
new_size,
device_address != 0 ? device_address + new_offset : 0,
mapped_ptr != nullptr ? mapped_ptr + new_offset : nullptr,
memory_usage };
}
};
/// @brief Buffer creation parameters
struct BufferCreateInfo {
/// @brief Memory usage to determine which heap to allocate the memory from
MemoryUsage mem_usage;
/// @brief Size of the Buffer in bytes
VkDeviceSize size;
/// @brief Alignment of the allocated Buffer in bytes
VkDeviceSize alignment = 1;
};
} // namespace vuk
<file_sep>#include "vuk/Descriptor.hpp"
#include "vuk/Context.hpp"
#include <concurrentqueue.h>
#include <mutex>
#include <robin_hood.h>
namespace vuk {
struct DescriptorPoolImpl {
std::mutex grow_mutex;
std::vector<VkDescriptorPool> pools;
uint32_t sets_allocated = 0;
moodycamel::ConcurrentQueue<VkDescriptorSet> free_sets{ 1024 };
};
DescriptorPool::DescriptorPool() : impl(new DescriptorPoolImpl) {}
DescriptorPool::~DescriptorPool() {
delete impl;
}
DescriptorPool::DescriptorPool(DescriptorPool&& o) noexcept {
if (impl) {
delete impl;
}
impl = o.impl;
o.impl = nullptr;
}
void DescriptorPool::grow(Context& ctx, vuk::DescriptorSetLayoutAllocInfo layout_alloc_info) {
if (!impl->grow_mutex.try_lock())
return;
VkDescriptorPoolCreateInfo dpci{ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
dpci.maxSets = impl->sets_allocated == 0 ? 1 : impl->sets_allocated * 2;
std::array<VkDescriptorPoolSize, 12> descriptor_counts = {};
size_t count = ctx.vkCmdBuildAccelerationStructuresKHR ? descriptor_counts.size() : descriptor_counts.size() - 1;
uint32_t used_idx = 0;
for (size_t i = 0; i < count; i++) {
if (layout_alloc_info.descriptor_counts[i] > 0) {
auto& d = descriptor_counts[used_idx];
d.type = i == 11 ? VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR : VkDescriptorType(i);
d.descriptorCount = layout_alloc_info.descriptor_counts[i] * dpci.maxSets;
used_idx++;
}
}
dpci.pPoolSizes = descriptor_counts.data();
dpci.poolSizeCount = used_idx;
VkDescriptorPool pool;
ctx.vkCreateDescriptorPool(ctx.device, &dpci, nullptr, &pool);
impl->pools.emplace_back(pool);
VkDescriptorSetAllocateInfo dsai{ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
dsai.descriptorPool = impl->pools.back();
dsai.descriptorSetCount = dpci.maxSets;
std::vector<VkDescriptorSetLayout> layouts(dpci.maxSets, layout_alloc_info.layout);
dsai.pSetLayouts = layouts.data();
// allocate all the descriptorsets
std::vector<VkDescriptorSet> sets(dsai.descriptorSetCount);
ctx.vkAllocateDescriptorSets(ctx.device, &dsai, sets.data());
impl->free_sets.enqueue_bulk(sets.data(), sets.size());
impl->sets_allocated = dpci.maxSets;
impl->grow_mutex.unlock();
}
VkDescriptorSet DescriptorPool::acquire(Context& ctx, vuk::DescriptorSetLayoutAllocInfo layout_alloc_info) {
VkDescriptorSet ds;
while (!impl->free_sets.try_dequeue(ds)) {
grow(ctx, layout_alloc_info);
}
return ds;
}
void DescriptorPool::release(VkDescriptorSet ds) {
impl->free_sets.enqueue(ds);
}
void DescriptorPool::destroy(Context& ctx, VkDevice device) const {
for (auto& p : impl->pools) {
ctx.vkDestroyDescriptorPool(device, p, nullptr);
}
}
SetBinding SetBinding::finalize(Bitset<VUK_MAX_BINDINGS> used_mask) {
SetBinding final;
final.used = used_mask;
final.layout_info = layout_info;
uint32_t mask = (uint32_t)used_mask.to_ulong();
for (size_t i = 0; i < VUK_MAX_BINDINGS; i++) {
if ((mask & (1 << i)) == 0) {
continue;
} else {
final.bindings[i] = bindings[i];
}
}
return final;
}
} // namespace vuk<file_sep>#include "vuk/resources/DeviceVkResource.hpp"
#include "../src/RenderPass.hpp"
#include "vuk/Buffer.hpp"
#include "vuk/Context.hpp"
#include "vuk/Exception.hpp"
#include "vuk/PipelineInstance.hpp"
#include "vuk/Query.hpp"
#include "vuk/resources/DeviceNestedResource.hpp"
#define VMA_IMPLEMENTATION
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0
#if VUK_DEBUG_ALLOCATIONS
#define VMA_DEBUG_LOG_FORMAT(format, ...) \
do { \
printf((format), __VA_ARGS__); \
printf("\n"); \
} while (false)
#endif
#include <mutex>
#include <numeric>
#include <sstream>
#include <vk_mem_alloc.h>
namespace vuk {
std::string to_string(SourceLocationAtFrame loc) {
std::stringstream sstream;
sstream << loc.location.file_name() << '(' << loc.location.line() << ':' << loc.location.column() << "): " << loc.location.function_name();
if (loc.absolute_frame != -1) {
sstream << "@" << loc.absolute_frame;
}
return sstream.str();
}
std::string to_human_readable(uint64_t in) {
/* k M G */
if (in >= 1024 * 1024 * 1024) {
return std::to_string(in / (1024 * 1024 * 1024)) + " GiB";
} else if (in >= 1024 * 1024) {
return std::to_string(in / (1024 * 1024)) + " MiB";
} else if (in >= 1024) {
return std::to_string(in / (1024)) + " kiB";
} else {
return std::to_string(in) + " B";
}
}
struct DeviceVkResourceImpl {
std::mutex mutex;
VmaAllocator allocator;
VkPhysicalDeviceProperties properties;
std::vector<uint32_t> all_queue_families;
uint32_t queue_family_count;
};
DeviceVkResource::DeviceVkResource(Context& ctx) : ctx(&ctx), impl(new DeviceVkResourceImpl), device(ctx.device) {
VmaAllocatorCreateInfo allocatorInfo = {};
allocatorInfo.instance = ctx.instance;
allocatorInfo.physicalDevice = ctx.physical_device;
allocatorInfo.device = device;
allocatorInfo.flags = VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT | VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT;
VmaVulkanFunctions vulkanFunctions = {};
vulkanFunctions.vkGetPhysicalDeviceProperties = ctx.vkGetPhysicalDeviceProperties;
vulkanFunctions.vkGetPhysicalDeviceMemoryProperties = ctx.vkGetPhysicalDeviceMemoryProperties;
vulkanFunctions.vkAllocateMemory = ctx.vkAllocateMemory;
vulkanFunctions.vkFreeMemory = ctx.vkFreeMemory;
vulkanFunctions.vkMapMemory = ctx.vkMapMemory;
vulkanFunctions.vkUnmapMemory = ctx.vkUnmapMemory;
vulkanFunctions.vkFlushMappedMemoryRanges = ctx.vkFlushMappedMemoryRanges;
vulkanFunctions.vkInvalidateMappedMemoryRanges = ctx.vkInvalidateMappedMemoryRanges;
vulkanFunctions.vkBindBufferMemory = ctx.vkBindBufferMemory;
vulkanFunctions.vkBindImageMemory = ctx.vkBindImageMemory;
vulkanFunctions.vkGetBufferMemoryRequirements = ctx.vkGetBufferMemoryRequirements;
vulkanFunctions.vkGetImageMemoryRequirements = ctx.vkGetImageMemoryRequirements;
vulkanFunctions.vkCreateBuffer = ctx.vkCreateBuffer;
vulkanFunctions.vkDestroyBuffer = ctx.vkDestroyBuffer;
vulkanFunctions.vkCreateImage = ctx.vkCreateImage;
vulkanFunctions.vkDestroyImage = ctx.vkDestroyImage;
vulkanFunctions.vkCmdCopyBuffer = ctx.vkCmdCopyBuffer;
allocatorInfo.pVulkanFunctions = &vulkanFunctions;
vmaCreateAllocator(&allocatorInfo, &impl->allocator);
ctx.vkGetPhysicalDeviceProperties(ctx.physical_device, &impl->properties);
if (ctx.transfer_queue_family_index != ctx.graphics_queue_family_index && ctx.compute_queue_family_index != ctx.graphics_queue_family_index) {
impl->all_queue_families = { ctx.graphics_queue_family_index, ctx.compute_queue_family_index, ctx.transfer_queue_family_index };
} else if (ctx.transfer_queue_family_index != ctx.graphics_queue_family_index) {
impl->all_queue_families = { ctx.graphics_queue_family_index, ctx.transfer_queue_family_index };
} else if (ctx.compute_queue_family_index != ctx.graphics_queue_family_index) {
impl->all_queue_families = { ctx.graphics_queue_family_index, ctx.compute_queue_family_index };
} else {
impl->all_queue_families = { ctx.graphics_queue_family_index };
}
impl->queue_family_count = (uint32_t)impl->all_queue_families.size();
}
DeviceVkResource::~DeviceVkResource() {
vmaDestroyAllocator(impl->allocator);
delete impl;
}
Result<void, AllocateException> DeviceVkResource::allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) {
VkSemaphoreCreateInfo sci{ .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkResult res = ctx->vkCreateSemaphore(device, &sci, nullptr, &dst[i]);
if (res != VK_SUCCESS) {
deallocate_semaphores({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
}
return { expected_value };
}
void DeviceVkResource::deallocate_semaphores(std::span<const VkSemaphore> src) {
for (auto& v : src) {
if (v != VK_NULL_HANDLE) {
ctx->vkDestroySemaphore(device, v, nullptr);
}
}
}
Result<void, AllocateException> DeviceVkResource::allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) {
VkFenceCreateInfo sci{ .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkResult res = ctx->vkCreateFence(device, &sci, nullptr, &dst[i]);
if (res != VK_SUCCESS) {
deallocate_fences({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
}
return { expected_value };
}
void DeviceVkResource::deallocate_fences(std::span<const VkFence> src) {
for (auto& v : src) {
if (v != VK_NULL_HANDLE) {
ctx->vkDestroyFence(device, v, nullptr);
}
}
}
Result<void, AllocateException> DeviceVkResource::allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
VkCommandBufferAllocateInfo cbai{ .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
cbai.commandBufferCount = 1;
cbai.commandPool = ci.command_pool.command_pool;
cbai.level = ci.level;
VkResult res = ctx->vkAllocateCommandBuffers(device, &cbai, &dst[i].command_buffer);
if (res != VK_SUCCESS) {
return { expected_error, AllocateException{ res } };
}
dst[i].command_pool = ci.command_pool;
}
return { expected_value };
}
void DeviceVkResource::deallocate_command_buffers(std::span<const CommandBufferAllocation> dst) {
for (auto& c : dst) {
ctx->vkFreeCommandBuffers(device, c.command_pool.command_pool, 1, &c.command_buffer);
}
}
Result<void, AllocateException>
DeviceVkResource::allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkResult res = ctx->vkCreateCommandPool(device, &cis[i], nullptr, &dst[i].command_pool);
dst[i].queue_family_index = cis[i].queueFamilyIndex;
if (res != VK_SUCCESS) {
deallocate_command_pools({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
}
return { expected_value };
}
void DeviceVkResource::deallocate_command_pools(std::span<const CommandPool> src) {
for (auto& v : src) {
if (v.command_pool != VK_NULL_HANDLE) {
ctx->vkDestroyCommandPool(device, v.command_pool, nullptr);
}
}
}
Result<void, AllocateException>
DeviceVkResource::allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkResult res = ctx->vkCreateFramebuffer(device, &cis[i], nullptr, &dst[i]);
if (res != VK_SUCCESS) {
deallocate_framebuffers({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
}
return { expected_value };
}
void DeviceVkResource::deallocate_framebuffers(std::span<const VkFramebuffer> src) {
for (auto& v : src) {
if (v != VK_NULL_HANDLE) {
ctx->vkDestroyFramebuffer(device, v, nullptr);
}
}
}
Result<void, AllocateException> DeviceVkResource::allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
std::lock_guard _(impl->mutex);
auto& ci = cis[i];
VkBufferCreateInfo bci{ .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bci.size = ci.size;
bci.usage = (VkBufferUsageFlags)all_buffer_usage_flags;
bci.queueFamilyIndexCount = impl->queue_family_count;
bci.sharingMode = bci.queueFamilyIndexCount > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE;
bci.pQueueFamilyIndices = impl->all_queue_families.data();
VmaAllocationCreateInfo aci = {};
aci.usage = VmaMemoryUsage(to_integral(ci.mem_usage));
aci.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer buffer;
VmaAllocation allocation;
VmaAllocationInfo allocation_info;
// ignore alignment: we get a fresh VkBuffer which satisfies all alignments inside the VkBfufer
auto res = vmaCreateBuffer(impl->allocator, &bci, &aci, &buffer, &allocation, &allocation_info);
if (res != VK_SUCCESS) {
deallocate_buffers({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
#if VUK_DEBUG_ALLOCATIONS
vmaSetAllocationName(impl->allocator, allocation, to_string(loc).c_str());
#endif
VkBufferDeviceAddressInfo bdai{ VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, nullptr, buffer };
uint64_t device_address = ctx->vkGetBufferDeviceAddress(device, &bdai);
dst[i] = Buffer{ allocation, buffer, 0, ci.size, device_address, static_cast<std::byte*>(allocation_info.pMappedData), ci.mem_usage };
}
return { expected_value };
}
void DeviceVkResource::deallocate_buffers(std::span<const Buffer> src) {
for (auto& v : src) {
if (v) {
vmaDestroyBuffer(impl->allocator, v.buffer, static_cast<VmaAllocation>(v.allocation));
}
}
}
Result<void, AllocateException> DeviceVkResource::allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
std::lock_guard _(impl->mutex);
VmaAllocationCreateInfo aci{};
aci.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkImage vkimg;
VmaAllocation allocation;
VkImageCreateInfo vkici = cis[i];
if (cis[i].usage & (vuk::ImageUsageFlagBits::eColorAttachment | vuk::ImageUsageFlagBits::eDepthStencilAttachment)) {
// this is a rendertarget, put it into the dedicated memory
aci.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
}
auto res = vmaCreateImage(impl->allocator, &vkici, &aci, &vkimg, &allocation, nullptr);
if (res != VK_SUCCESS) {
deallocate_images({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
#if VUK_DEBUG_ALLOCATIONS
vmaSetAllocationName(impl->allocator, allocation, to_string(loc).c_str());
#endif
dst[i] = Image{ vkimg, allocation };
}
return { expected_value };
}
void DeviceVkResource::deallocate_images(std::span<const Image> src) {
for (auto& v : src) {
if (v) {
vmaDestroyImage(impl->allocator, v.image, static_cast<VmaAllocation>(v.allocation));
}
}
}
Result<void, AllocateException>
DeviceVkResource::allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkImageViewCreateInfo ci = cis[i];
VkImageViewUsageCreateInfo uvci{ VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO };
uvci.usage = (VkImageUsageFlags)cis[i].view_usage;
if (uvci.usage != 0) {
ci.pNext = &uvci;
}
VkImageView iv;
VkResult res = ctx->vkCreateImageView(device, &ci, nullptr, &iv);
if (res != VK_SUCCESS) {
deallocate_image_views({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
dst[i] = ctx->wrap(iv);
}
return { expected_value };
}
Result<void, AllocateException> DeviceVkResource::allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
auto& ci = cis[i];
auto& dslai = ci.dslai;
PersistentDescriptorSet& tda = dst[i];
auto dsl = dslai.layout;
VkDescriptorPoolCreateInfo dpci = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
dpci.maxSets = 1;
std::array<VkDescriptorPoolSize, 12> descriptor_counts = {};
size_t count = get_context().vkCmdBuildAccelerationStructuresKHR ? descriptor_counts.size() : descriptor_counts.size() - 1;
uint32_t used_idx = 0;
for (size_t i = 0; i < count; i++) {
bool used = false;
// create non-variable count descriptors
if (dslai.descriptor_counts[i] > 0) {
auto& d = descriptor_counts[used_idx];
d.type = i == 11 ? VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR : VkDescriptorType(i);
d.descriptorCount = dslai.descriptor_counts[i];
used = true;
}
// create variable count descriptors
if (dslai.variable_count_binding != (unsigned)-1 && dslai.variable_count_binding_type == DescriptorType(i)) {
auto& d = descriptor_counts[used_idx];
d.type = i == 11 ? VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR : VkDescriptorType(i);
d.descriptorCount += ci.num_descriptors;
used = true;
}
if (used) {
used_idx++;
}
}
dpci.pPoolSizes = descriptor_counts.data();
dpci.poolSizeCount = used_idx;
VkResult result = ctx->vkCreateDescriptorPool(device, &dpci, nullptr, &tda.backing_pool);
if (result != VK_SUCCESS) {
deallocate_persistent_descriptor_sets({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ result } };
}
VkDescriptorSetAllocateInfo dsai = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
dsai.descriptorPool = tda.backing_pool;
dsai.descriptorSetCount = 1;
dsai.pSetLayouts = &dsl;
VkDescriptorSetVariableDescriptorCountAllocateInfo dsvdcai = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO };
dsvdcai.descriptorSetCount = 1;
dsvdcai.pDescriptorCounts = &ci.num_descriptors;
if (dslai.variable_count_binding != (unsigned)-1) {
dsai.pNext = &dsvdcai;
}
ctx->vkAllocateDescriptorSets(device, &dsai, &tda.backing_set);
if (result != VK_SUCCESS) {
deallocate_persistent_descriptor_sets({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ result } };
}
for (unsigned i = 0; i < ci.dslci.bindings.size(); i++) {
tda.descriptor_bindings[i].resize(ci.dslci.bindings[i].descriptorCount);
}
if (dslai.variable_count_binding != (unsigned)-1) {
tda.descriptor_bindings[dslai.variable_count_binding].resize(ci.num_descriptors);
}
tda.set_layout_create_info = ci.dslci;
tda.set_layout = dsl;
}
return { expected_value };
}
void DeviceVkResource::deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) {
for (auto& v : src) {
ctx->vkDestroyDescriptorPool(ctx->device, v.backing_pool, nullptr);
}
}
Result<void, AllocateException>
DeviceVkResource::allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
auto& cinfo = cis[i];
auto& pool = ctx->acquire_descriptor_pool(*cinfo.layout_info, ctx->get_frame_count());
auto ds = pool.acquire(*ctx, *cinfo.layout_info);
auto mask = cinfo.used.to_ulong();
uint32_t leading_ones = num_leading_ones((uint32_t)mask);
std::array<VkWriteDescriptorSet, VUK_MAX_BINDINGS> writes = {};
std::array<VkWriteDescriptorSetAccelerationStructureKHR, VUK_MAX_BINDINGS> as_writes = {};
int j = 0;
for (uint32_t i = 0; i < leading_ones; i++, j++) {
if (!cinfo.used.test(i)) {
j--;
continue;
}
auto& write = writes[j];
auto& as_write = as_writes[j];
write = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
auto& binding = cinfo.bindings[i];
write.descriptorType = (VkDescriptorType)binding.type;
write.dstArrayElement = 0;
write.descriptorCount = 1;
write.dstBinding = i;
write.dstSet = ds;
switch (binding.type) {
case DescriptorType::eUniformBuffer:
case DescriptorType::eStorageBuffer:
write.pBufferInfo = &binding.buffer;
break;
case DescriptorType::eSampledImage:
case DescriptorType::eSampler:
case DescriptorType::eCombinedImageSampler:
case DescriptorType::eStorageImage:
write.pImageInfo = &binding.image.dii;
break;
case DescriptorType::eAccelerationStructureKHR:
as_write = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR };
as_write.pAccelerationStructures = &binding.as.as;
as_write.accelerationStructureCount = 1;
write.pNext = &as_write;
break;
default:
assert(0);
}
}
ctx->vkUpdateDescriptorSets(device, j, writes.data(), 0, nullptr);
dst[i] = { ds, *cinfo.layout_info };
}
return { expected_value };
}
Result<void, AllocateException>
DeviceVkResource::allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
auto& cinfo = cis[i];
auto& pool = ctx->acquire_descriptor_pool(cinfo, ctx->get_frame_count());
dst[i] = { pool.acquire(*ctx, cinfo), cinfo };
}
return { expected_value };
}
void DeviceVkResource::deallocate_descriptor_sets(std::span<const DescriptorSet> src) {
for (int64_t i = 0; i < (int64_t)src.size(); i++) {
DescriptorPool& pool = ctx->acquire_descriptor_pool(src[i].layout_info, ctx->get_frame_count());
pool.release(src[i].descriptor_set);
}
}
Result<void, AllocateException>
DeviceVkResource::allocate_descriptor_pools(std::span<VkDescriptorPool> dst, std::span<const VkDescriptorPoolCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkDescriptorPoolCreateInfo ci = cis[i];
VkResult res = ctx->vkCreateDescriptorPool(device, &ci, nullptr, &dst[i]);
if (res != VK_SUCCESS) {
deallocate_descriptor_pools({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
}
return { expected_value };
}
void DeviceVkResource::deallocate_descriptor_pools(std::span<const VkDescriptorPool> src) {
for (int64_t i = 0; i < (int64_t)src.size(); i++) {
ctx->vkDestroyDescriptorPool(device, src[i], nullptr);
}
}
void DeviceVkResource::deallocate_image_views(std::span<const ImageView> src) {
for (auto& v : src) {
if (v.payload != VK_NULL_HANDLE) {
ctx->vkDestroyImageView(device, v.payload, nullptr);
}
}
}
Result<void, AllocateException>
DeviceVkResource::allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst, std::span<const VkQueryPoolCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkResult res = ctx->vkCreateQueryPool(device, &cis[i], nullptr, &dst[i].pool);
if (res != VK_SUCCESS) {
deallocate_timestamp_query_pools({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
ctx->vkResetQueryPool(device, dst[i].pool, 0, cis[i].queryCount);
}
return { expected_value };
}
void DeviceVkResource::deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) {
for (auto& v : src) {
if (v.pool != VK_NULL_HANDLE) {
ctx->vkDestroyQueryPool(device, v.pool, nullptr);
}
}
}
Result<void, AllocateException>
DeviceVkResource::allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (uint64_t i = 0; i < dst.size(); i++) {
auto& ci = cis[i];
ci.pool->queries[ci.pool->count++] = ci.query;
dst[i].id = ci.pool->count;
dst[i].pool = ci.pool->pool;
}
return { expected_value };
}
void DeviceVkResource::deallocate_timestamp_queries(std::span<const TimestampQuery> src) {}
Result<void, AllocateException> DeviceVkResource::allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) {
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkSemaphoreCreateInfo sci{ .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
VkSemaphoreTypeCreateInfo stci{ .sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO };
stci.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE;
stci.initialValue = 0;
sci.pNext = &stci;
VkResult res = ctx->vkCreateSemaphore(device, &sci, nullptr, &dst[i].semaphore);
if (res != VK_SUCCESS) {
deallocate_timeline_semaphores({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
dst[i].value = new uint64_t{ 0 }; // TODO: more sensibly
}
return { expected_value };
}
void DeviceVkResource::deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) {
for (auto& v : src) {
if (v.semaphore != VK_NULL_HANDLE) {
ctx->vkDestroySemaphore(device, v.semaphore, nullptr);
delete v.value;
}
}
}
Result<void, AllocateException> DeviceVkResource::allocate_acceleration_structures(std::span<VkAccelerationStructureKHR> dst,
std::span<const VkAccelerationStructureCreateInfoKHR> cis,
SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
VkAccelerationStructureCreateInfoKHR ci = cis[i];
VkResult res = ctx->vkCreateAccelerationStructureKHR(device, &ci, nullptr, &dst[i]);
if (res != VK_SUCCESS) {
deallocate_acceleration_structures({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
}
return { expected_value };
}
void DeviceVkResource::deallocate_acceleration_structures(std::span<const VkAccelerationStructureKHR> src) {
for (auto& v : src) {
if (v != VK_NULL_HANDLE) {
ctx->vkDestroyAccelerationStructureKHR(device, v, nullptr);
}
}
}
void DeviceVkResource::deallocate_swapchains(std::span<const VkSwapchainKHR> src) {
for (auto& v : src) {
if (v != VK_NULL_HANDLE) {
ctx->vkDestroySwapchainKHR(device, v, nullptr);
}
}
}
template<class T>
T read(const std::byte*& data_ptr) {
T t;
memcpy(&t, data_ptr, sizeof(T));
data_ptr += sizeof(T);
return t;
};
Result<void, AllocateException> DeviceVkResource::allocate_graphics_pipelines(std::span<GraphicsPipelineInfo> dst,
std::span<const GraphicsPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
GraphicsPipelineInstanceCreateInfo cinfo = cis[i];
// create gfx pipeline
VkGraphicsPipelineCreateInfo gpci{ .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO };
gpci.renderPass = cinfo.render_pass;
gpci.layout = cinfo.base->pipeline_layout;
auto psscis = cinfo.base->psscis;
gpci.pStages = psscis.data();
gpci.stageCount = (uint32_t)psscis.size();
// read variable sized data
const std::byte* data_ptr = cinfo.is_inline() ? cinfo.inline_data : cinfo.extended_data;
// subpass
if (cinfo.records.nonzero_subpass) {
gpci.subpass = read<uint8_t>(data_ptr);
}
// INPUT ASSEMBLY
VkPipelineInputAssemblyStateCreateInfo input_assembly_state{ .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.topology = static_cast<VkPrimitiveTopology>(cinfo.topology),
.primitiveRestartEnable = cinfo.primitive_restart_enable };
gpci.pInputAssemblyState = &input_assembly_state;
// VERTEX INPUT
fixed_vector<VkVertexInputBindingDescription, VUK_MAX_ATTRIBUTES> vibds;
fixed_vector<VkVertexInputAttributeDescription, VUK_MAX_ATTRIBUTES> viads;
VkPipelineVertexInputStateCreateInfo vertex_input_state{ .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
if (cinfo.records.vertex_input) {
viads.resize(cinfo.base->reflection_info.attributes.size());
for (auto& viad : viads) {
auto compressed = read<GraphicsPipelineInstanceCreateInfo::VertexInputAttributeDescription>(data_ptr);
viad.binding = compressed.binding;
viad.location = compressed.location;
viad.format = (VkFormat)compressed.format;
viad.offset = compressed.offset;
}
vertex_input_state.pVertexAttributeDescriptions = viads.data();
vertex_input_state.vertexAttributeDescriptionCount = (uint32_t)viads.size();
vibds.resize(read<uint8_t>(data_ptr));
for (auto& vibd : vibds) {
auto compressed = read<GraphicsPipelineInstanceCreateInfo::VertexInputBindingDescription>(data_ptr);
vibd.binding = compressed.binding;
vibd.inputRate = (VkVertexInputRate)compressed.inputRate;
vibd.stride = compressed.stride;
}
vertex_input_state.pVertexBindingDescriptions = vibds.data();
vertex_input_state.vertexBindingDescriptionCount = (uint32_t)vibds.size();
}
gpci.pVertexInputState = &vertex_input_state;
// PIPELINE COLOR BLEND ATTACHMENTS
VkPipelineColorBlendStateCreateInfo color_blend_state{ .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
.attachmentCount = cinfo.attachmentCount };
auto default_writemask = ColorComponentFlagBits::eR | ColorComponentFlagBits::eG | ColorComponentFlagBits::eB | ColorComponentFlagBits::eA;
std::vector<VkPipelineColorBlendAttachmentState> pcbas(
cinfo.attachmentCount, VkPipelineColorBlendAttachmentState{ .blendEnable = false, .colorWriteMask = (VkColorComponentFlags)default_writemask });
if (cinfo.records.color_blend_attachments) {
if (!cinfo.records.broadcast_color_blend_attachment_0) {
for (auto& pcba : pcbas) {
auto compressed = read<GraphicsPipelineInstanceCreateInfo::PipelineColorBlendAttachmentState>(data_ptr);
pcba = { compressed.blendEnable,
(VkBlendFactor)compressed.srcColorBlendFactor,
(VkBlendFactor)compressed.dstColorBlendFactor,
(VkBlendOp)compressed.colorBlendOp,
(VkBlendFactor)compressed.srcAlphaBlendFactor,
(VkBlendFactor)compressed.dstAlphaBlendFactor,
(VkBlendOp)compressed.alphaBlendOp,
compressed.colorWriteMask };
}
} else { // handle broadcast
auto compressed = read<GraphicsPipelineInstanceCreateInfo::PipelineColorBlendAttachmentState>(data_ptr);
for (auto& pcba : pcbas) {
pcba = { compressed.blendEnable,
(VkBlendFactor)compressed.srcColorBlendFactor,
(VkBlendFactor)compressed.dstColorBlendFactor,
(VkBlendOp)compressed.colorBlendOp,
(VkBlendFactor)compressed.srcAlphaBlendFactor,
(VkBlendFactor)compressed.dstAlphaBlendFactor,
(VkBlendOp)compressed.alphaBlendOp,
compressed.colorWriteMask };
}
}
}
if (cinfo.records.logic_op) {
auto compressed = read<GraphicsPipelineInstanceCreateInfo::BlendStateLogicOp>(data_ptr);
color_blend_state.logicOpEnable = true;
color_blend_state.logicOp = static_cast<VkLogicOp>(compressed.logic_op);
}
if (cinfo.records.blend_constants) {
memcpy(&color_blend_state.blendConstants, data_ptr, sizeof(float) * 4);
data_ptr += sizeof(float) * 4;
}
color_blend_state.pAttachments = pcbas.data();
color_blend_state.attachmentCount = (uint32_t)pcbas.size();
gpci.pColorBlendState = &color_blend_state;
// SPECIALIZATION CONSTANTS
fixed_vector<VkSpecializationInfo, graphics_stage_count> specialization_infos;
fixed_vector<VkSpecializationMapEntry, VUK_MAX_SPECIALIZATIONCONSTANT_RANGES> specialization_map_entries;
uint16_t specialization_constant_data_size = 0;
const std::byte* specialization_constant_data = nullptr;
if (cinfo.records.specialization_constants) {
Bitset<VUK_MAX_SPECIALIZATIONCONSTANT_RANGES> set_constants = {};
set_constants = read<Bitset<VUK_MAX_SPECIALIZATIONCONSTANT_RANGES>>(data_ptr);
specialization_constant_data = data_ptr;
for (unsigned i = 0; i < cinfo.base->reflection_info.spec_constants.size(); i++) {
auto& sc = cinfo.base->reflection_info.spec_constants[i];
uint16_t size = sc.type == Program::Type::edouble ? (uint16_t)sizeof(double) : 4;
if (set_constants.test(i)) {
specialization_constant_data_size += size;
}
}
data_ptr += specialization_constant_data_size;
uint16_t entry_offset = 0;
for (uint32_t i = 0; i < psscis.size(); i++) {
auto& pssci = psscis[i];
uint16_t data_offset = 0;
uint16_t current_entry_offset = entry_offset;
for (unsigned i = 0; i < cinfo.base->reflection_info.spec_constants.size(); i++) {
auto& sc = cinfo.base->reflection_info.spec_constants[i];
auto size = sc.type == Program::Type::edouble ? sizeof(double) : 4;
if (sc.stage & pssci.stage) {
specialization_map_entries.emplace_back(VkSpecializationMapEntry{ sc.binding, data_offset, size });
data_offset += (uint16_t)size;
entry_offset++;
}
}
VkSpecializationInfo si;
si.pMapEntries = specialization_map_entries.data() + current_entry_offset;
si.mapEntryCount = (uint32_t)specialization_map_entries.size() - current_entry_offset;
si.pData = specialization_constant_data;
si.dataSize = specialization_constant_data_size;
if (si.mapEntryCount > 0) {
specialization_infos.push_back(si);
pssci.pSpecializationInfo = &specialization_infos.back();
}
}
}
// RASTER STATE
VkPipelineRasterizationStateCreateInfo rasterization_state{ .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
.polygonMode = VK_POLYGON_MODE_FILL,
.cullMode = cinfo.cullMode,
.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE,
.lineWidth = 1.f };
if (cinfo.records.non_trivial_raster_state) {
auto rs = read<GraphicsPipelineInstanceCreateInfo::RasterizationState>(data_ptr);
rasterization_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
.depthClampEnable = rs.depthClampEnable,
.rasterizerDiscardEnable = rs.rasterizerDiscardEnable,
.polygonMode = (VkPolygonMode)rs.polygonMode,
.cullMode = cinfo.cullMode,
.frontFace = (VkFrontFace)rs.frontFace,
.lineWidth = 1.f };
}
rasterization_state.depthBiasEnable = cinfo.records.depth_bias_enable;
if (cinfo.records.depth_bias) {
auto db = read<GraphicsPipelineInstanceCreateInfo::DepthBias>(data_ptr);
rasterization_state.depthBiasClamp = db.depthBiasClamp;
rasterization_state.depthBiasConstantFactor = db.depthBiasConstantFactor;
rasterization_state.depthBiasSlopeFactor = db.depthBiasSlopeFactor;
}
if (cinfo.records.line_width_not_1) {
rasterization_state.lineWidth = read<float>(data_ptr);
}
VkPipelineRasterizationConservativeStateCreateInfoEXT conservative_state{
.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT
};
if (cinfo.records.conservative_rasterization_enabled) {
auto cs = read<GraphicsPipelineInstanceCreateInfo::ConservativeState>(data_ptr);
conservative_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT,
.conservativeRasterizationMode = (VkConservativeRasterizationModeEXT)cs.conservativeMode,
.extraPrimitiveOverestimationSize = cs.overestimationAmount };
rasterization_state.pNext = &conservative_state;
}
gpci.pRasterizationState = &rasterization_state;
// DEPTH - STENCIL STATE
VkPipelineDepthStencilStateCreateInfo depth_stencil_state{ VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
if (cinfo.records.depth_stencil) {
auto d = read<GraphicsPipelineInstanceCreateInfo::Depth>(data_ptr);
depth_stencil_state.depthTestEnable = d.depthTestEnable;
depth_stencil_state.depthWriteEnable = d.depthWriteEnable;
depth_stencil_state.depthCompareOp = (VkCompareOp)d.depthCompareOp;
if (cinfo.records.depth_bounds) {
auto db = read<GraphicsPipelineInstanceCreateInfo::DepthBounds>(data_ptr);
depth_stencil_state.depthBoundsTestEnable = true;
depth_stencil_state.minDepthBounds = db.minDepthBounds;
depth_stencil_state.maxDepthBounds = db.maxDepthBounds;
}
if (cinfo.records.stencil_state) {
auto s = read<GraphicsPipelineInstanceCreateInfo::Stencil>(data_ptr);
depth_stencil_state.stencilTestEnable = true;
depth_stencil_state.front = s.front;
depth_stencil_state.back = s.back;
}
gpci.pDepthStencilState = &depth_stencil_state;
}
// MULTISAMPLE STATE
VkPipelineMultisampleStateCreateInfo multisample_state{ .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT };
if (cinfo.records.more_than_one_sample) {
auto ms = read<GraphicsPipelineInstanceCreateInfo::Multisample>(data_ptr);
multisample_state.rasterizationSamples = static_cast<VkSampleCountFlagBits>(ms.rasterization_samples);
multisample_state.alphaToCoverageEnable = ms.alpha_to_coverage_enable;
multisample_state.alphaToOneEnable = ms.alpha_to_one_enable;
multisample_state.minSampleShading = ms.min_sample_shading;
multisample_state.sampleShadingEnable = ms.sample_shading_enable;
multisample_state.pSampleMask = nullptr; // not yet supported
}
gpci.pMultisampleState = &multisample_state;
// VIEWPORTS
const VkViewport* viewports = nullptr;
uint8_t num_viewports = 1;
if (cinfo.records.viewports) {
num_viewports = read<uint8_t>(data_ptr);
if (!(static_cast<vuk::DynamicStateFlags>(cinfo.dynamic_state_flags) & vuk::DynamicStateFlagBits::eViewport)) {
viewports = reinterpret_cast<const VkViewport*>(data_ptr);
data_ptr += num_viewports * sizeof(VkViewport);
}
}
// SCISSORS
const VkRect2D* scissors = nullptr;
uint8_t num_scissors = 1;
if (cinfo.records.scissors) {
num_scissors = read<uint8_t>(data_ptr);
if (!(static_cast<vuk::DynamicStateFlags>(cinfo.dynamic_state_flags) & vuk::DynamicStateFlagBits::eScissor)) {
scissors = reinterpret_cast<const VkRect2D*>(data_ptr);
data_ptr += num_scissors * sizeof(VkRect2D);
}
}
VkPipelineViewportStateCreateInfo viewport_state{ VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO };
viewport_state.pViewports = viewports;
viewport_state.viewportCount = num_viewports;
viewport_state.pScissors = scissors;
viewport_state.scissorCount = num_scissors;
gpci.pViewportState = &viewport_state;
VkPipelineDynamicStateCreateInfo dynamic_state{ .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO };
dynamic_state.dynamicStateCount = std::popcount(cinfo.dynamic_state_flags);
fixed_vector<VkDynamicState, VkDynamicState::VK_DYNAMIC_STATE_DEPTH_BOUNDS> dyn_states;
uint64_t dyn_state_cnt = 0;
uint16_t mask = cinfo.dynamic_state_flags;
while (mask > 0) {
bool set = mask & 0x1;
if (set) {
dyn_states.push_back((VkDynamicState)dyn_state_cnt); // TODO: we will need a switch here instead of a cast when handling EXT
}
mask >>= 1;
dyn_state_cnt++;
}
dynamic_state.pDynamicStates = dyn_states.data();
gpci.pDynamicState = &dynamic_state;
VkPipeline pipeline;
VkResult res = ctx->vkCreateGraphicsPipelines(device, ctx->vk_pipeline_cache, 1, &gpci, nullptr, &pipeline);
if (res != VK_SUCCESS) {
deallocate_graphics_pipelines({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
ctx->set_name(pipeline, cinfo.base->pipeline_name);
dst[i] = { cinfo.base, pipeline, gpci.layout, cinfo.base->layout_info };
}
return { expected_value };
}
void DeviceVkResource::deallocate_graphics_pipelines(std::span<const GraphicsPipelineInfo> src) {
for (auto& v : src) {
ctx->vkDestroyPipeline(device, v.pipeline, nullptr);
}
}
Result<void, AllocateException> DeviceVkResource::allocate_compute_pipelines(std::span<ComputePipelineInfo> dst,
std::span<const ComputePipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
ComputePipelineInstanceCreateInfo cinfo = cis[i];
// create compute pipeline
VkComputePipelineCreateInfo cpci{ .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO };
cpci.layout = cinfo.base->pipeline_layout;
cpci.stage = cinfo.base->psscis[0];
VkPipeline pipeline;
VkResult res = ctx->vkCreateComputePipelines(device, ctx->vk_pipeline_cache, 1, &cpci, nullptr, &pipeline);
if (res != VK_SUCCESS) {
deallocate_compute_pipelines({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
ctx->set_name(pipeline, cinfo.base->pipeline_name);
dst[i] = { { cinfo.base, pipeline, cpci.layout, cinfo.base->layout_info }, cinfo.base->reflection_info.local_size };
}
return { expected_value };
}
void DeviceVkResource::deallocate_compute_pipelines(std::span<const ComputePipelineInfo> src) {
for (auto& v : src) {
ctx->vkDestroyPipeline(device, v.pipeline, nullptr);
}
}
Result<void, AllocateException> DeviceVkResource::allocate_ray_tracing_pipelines(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
RayTracingPipelineInstanceCreateInfo cinfo = cis[i];
// create ray tracing pipeline
VkRayTracingPipelineCreateInfoKHR cpci{ .sType = VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR };
cpci.layout = cinfo.base->pipeline_layout;
std::vector<VkRayTracingShaderGroupCreateInfoKHR> groups;
VkRayTracingShaderGroupCreateInfoKHR group{ VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR };
group.anyHitShader = VK_SHADER_UNUSED_KHR;
group.closestHitShader = VK_SHADER_UNUSED_KHR;
group.generalShader = VK_SHADER_UNUSED_KHR;
group.intersectionShader = VK_SHADER_UNUSED_KHR;
uint32_t miss_count = 0;
uint32_t hit_count = 0;
uint32_t callable_count = 0;
for (size_t i = 0; i < cinfo.base->psscis.size(); i++) {
auto& stage = cinfo.base->psscis[i];
if (stage.stage == VK_SHADER_STAGE_RAYGEN_BIT_KHR) {
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR;
group.generalShader = (uint32_t)i;
groups.push_back(group);
} else if (stage.stage == VK_SHADER_STAGE_MISS_BIT_KHR) {
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR;
group.generalShader = (uint32_t)i;
groups.push_back(group);
miss_count++;
} else if (stage.stage == VK_SHADER_STAGE_CALLABLE_BIT_KHR) {
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR;
group.generalShader = (uint32_t)i;
groups.push_back(group);
callable_count++;
}
}
for (auto& hg : cinfo.base->hit_groups) {
group.type = (VkRayTracingShaderGroupTypeKHR)hg.type;
group.generalShader = VK_SHADER_UNUSED_KHR;
group.anyHitShader = hg.any_hit;
group.intersectionShader = hg.intersection;
group.closestHitShader = hg.closest_hit;
groups.push_back(group);
hit_count++;
}
cpci.groupCount = (uint32_t)groups.size();
cpci.pGroups = groups.data();
cpci.maxPipelineRayRecursionDepth = cinfo.base->max_ray_recursion_depth;
cpci.pStages = cinfo.base->psscis.data();
cpci.stageCount = (uint32_t)cinfo.base->psscis.size();
VkPipeline pipeline;
VkResult res = ctx->vkCreateRayTracingPipelinesKHR(device, {}, ctx->vk_pipeline_cache, 1, &cpci, nullptr, &pipeline);
if (res != VK_SUCCESS) {
deallocate_ray_tracing_pipelines({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
auto handleCount = 1 + miss_count + hit_count + callable_count;
uint32_t handleSize = ctx->rt_properties.shaderGroupHandleSize;
// The SBT (buffer) need to have starting groups to be aligned and handles in the group to be aligned.
uint32_t handleSizeAligned = vuk::align_up(handleSize, ctx->rt_properties.shaderGroupHandleAlignment);
VkStridedDeviceAddressRegionKHR rgen_region{};
VkStridedDeviceAddressRegionKHR miss_region{};
VkStridedDeviceAddressRegionKHR hit_region{};
VkStridedDeviceAddressRegionKHR call_region{};
rgen_region.stride = vuk::align_up(handleSizeAligned, ctx->rt_properties.shaderGroupBaseAlignment);
rgen_region.size = rgen_region.stride; // The size member of pRayGenShaderBindingTable must be equal to its stride member
miss_region.stride = handleSizeAligned;
miss_region.size = vuk::align_up(miss_count * handleSizeAligned, ctx->rt_properties.shaderGroupBaseAlignment);
hit_region.stride = handleSizeAligned;
hit_region.size = vuk::align_up(hit_count * handleSizeAligned, ctx->rt_properties.shaderGroupBaseAlignment);
call_region.stride = handleSizeAligned;
call_region.size = vuk::align_up(callable_count * handleSizeAligned, ctx->rt_properties.shaderGroupBaseAlignment);
// Get the shader group handles
uint32_t dataSize = handleCount * handleSize;
std::vector<uint8_t> handles(dataSize);
auto result = ctx->vkGetRayTracingShaderGroupHandlesKHR(device, pipeline, 0, handleCount, dataSize, handles.data());
assert(result == VK_SUCCESS);
VkDeviceSize sbt_size = rgen_region.size + miss_region.size + hit_region.size + call_region.size;
Buffer SBT;
BufferCreateInfo bci{ .mem_usage = vuk::MemoryUsage::eCPUtoGPU, .size = sbt_size, .alignment = ctx->rt_properties.shaderGroupBaseAlignment };
auto buff_cr_result = allocate_buffers(std::span{ &SBT, 1 }, std::span{ &bci, 1 }, {});
assert(buff_cr_result);
// Helper to retrieve the handle data
auto get_handle = [&](int i) {
return handles.data() + i * handleSize;
};
std::byte* pData{ nullptr };
uint32_t handleIdx{ 0 };
// Raygen
pData = SBT.mapped_ptr;
memcpy(pData, get_handle(handleIdx++), handleSize);
// Miss
pData = SBT.mapped_ptr + rgen_region.size;
for (uint32_t c = 0; c < miss_count; c++) {
memcpy(pData, get_handle(handleIdx++), handleSize);
pData += miss_region.stride;
}
// Hit
pData = SBT.mapped_ptr + rgen_region.size + miss_region.size;
for (uint32_t c = 0; c < hit_count; c++) {
memcpy(pData, get_handle(handleIdx++), handleSize);
pData += hit_region.stride;
}
// Call
pData = SBT.mapped_ptr + rgen_region.size + miss_region.size + hit_region.size;
for (uint32_t c = 0; c < callable_count; c++) {
memcpy(pData, get_handle(handleIdx++), handleSize);
pData += call_region.stride;
}
auto sbtAddress = SBT.device_address;
rgen_region.deviceAddress = sbtAddress;
miss_region.deviceAddress = sbtAddress + rgen_region.size;
hit_region.deviceAddress = sbtAddress + rgen_region.size + miss_region.size;
call_region.deviceAddress = sbtAddress + rgen_region.size + miss_region.size + hit_region.size;
ctx->set_name(pipeline, cinfo.base->pipeline_name);
dst[i] = { { cinfo.base, pipeline, cpci.layout, cinfo.base->layout_info }, rgen_region, miss_region, hit_region, call_region, SBT };
}
return { expected_value };
}
void DeviceVkResource::deallocate_ray_tracing_pipelines(std::span<const RayTracingPipelineInfo> src) {
for (auto& v : src) {
deallocate_buffers(std::span{ &v.sbt, 1 });
ctx->vkDestroyPipeline(device, v.pipeline, nullptr);
}
}
Result<void, AllocateException>
DeviceVkResource::allocate_render_passes(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc) {
assert(dst.size() == cis.size());
for (int64_t i = 0; i < (int64_t)dst.size(); i++) {
auto cinfo = cis[i];
VkResult res = ctx->vkCreateRenderPass(device, &cinfo, nullptr, &dst[i]);
if (res != VK_SUCCESS) {
deallocate_render_passes({ dst.data(), (uint64_t)i });
return { expected_error, AllocateException{ res } };
}
}
return { expected_value };
}
void DeviceVkResource::deallocate_render_passes(std::span<const VkRenderPass> src) {
for (auto& v : src) {
ctx->vkDestroyRenderPass(device, v, nullptr);
}
}
Result<void, AllocateException> DeviceNestedResource::allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) {
return upstream->allocate_semaphores(dst, loc);
}
void DeviceNestedResource::deallocate_semaphores(std::span<const VkSemaphore> sema) {
upstream->deallocate_semaphores(sema);
}
Result<void, AllocateException> DeviceNestedResource::allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) {
return upstream->allocate_fences(dst, loc);
}
void DeviceNestedResource::deallocate_fences(std::span<const VkFence> dst) {
upstream->deallocate_fences(dst);
}
Result<void, AllocateException> DeviceNestedResource::allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc) {
return upstream->allocate_command_buffers(dst, cis, loc);
}
void DeviceNestedResource::deallocate_command_buffers(std::span<const CommandBufferAllocation> dst) {
upstream->deallocate_command_buffers(dst);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_command_pools(dst, cis, loc);
}
void DeviceNestedResource::deallocate_command_pools(std::span<const CommandPool> dst) {
upstream->deallocate_command_pools(dst);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_buffers(dst, cis, loc);
}
void DeviceNestedResource::deallocate_buffers(std::span<const Buffer> src) {
upstream->deallocate_buffers(src);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_framebuffers(dst, cis, loc);
}
void DeviceNestedResource::deallocate_framebuffers(std::span<const VkFramebuffer> src) {
upstream->deallocate_framebuffers(src);
}
Result<void, AllocateException> DeviceNestedResource::allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_images(dst, cis, loc);
}
void DeviceNestedResource::deallocate_images(std::span<const Image> src) {
upstream->deallocate_images(src);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_image_views(dst, cis, loc);
}
void DeviceNestedResource::deallocate_image_views(std::span<const ImageView> src) {
upstream->deallocate_image_views(src);
}
Result<void, AllocateException> DeviceNestedResource::allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) {
return upstream->allocate_persistent_descriptor_sets(dst, cis, loc);
}
void DeviceNestedResource::deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) {
upstream->deallocate_persistent_descriptor_sets(src);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) {
return upstream->allocate_descriptor_sets_with_value(dst, cis, loc);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_descriptor_sets(dst, cis, loc);
}
void DeviceNestedResource::deallocate_descriptor_sets(std::span<const DescriptorSet> src) {
upstream->deallocate_descriptor_sets(src);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_descriptor_pools(std::span<VkDescriptorPool> dst, std::span<const VkDescriptorPoolCreateInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_descriptor_pools(dst, cis, loc);
}
void DeviceNestedResource::deallocate_descriptor_pools(std::span<const VkDescriptorPool> src) {
upstream->deallocate_descriptor_pools(src);
}
Result<void, AllocateException> DeviceNestedResource::allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst,
std::span<const VkQueryPoolCreateInfo> cis,
SourceLocationAtFrame loc) {
return upstream->allocate_timestamp_query_pools(dst, cis, loc);
}
void DeviceNestedResource::deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) {
upstream->deallocate_timestamp_query_pools(src);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_timestamp_queries(dst, cis, loc);
}
void DeviceNestedResource::deallocate_timestamp_queries(std::span<const TimestampQuery> src) {
upstream->deallocate_timestamp_queries(src);
}
Result<void, AllocateException> DeviceNestedResource::allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) {
return upstream->allocate_timeline_semaphores(dst, loc);
}
void DeviceNestedResource::deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) {
upstream->deallocate_timeline_semaphores(src);
}
Result<void, AllocateException> DeviceNestedResource::allocate_acceleration_structures(std::span<VkAccelerationStructureKHR> dst,
std::span<const VkAccelerationStructureCreateInfoKHR> cis,
SourceLocationAtFrame loc) {
return upstream->allocate_acceleration_structures(dst, cis, loc);
}
void DeviceNestedResource::deallocate_acceleration_structures(std::span<const VkAccelerationStructureKHR> src) {
upstream->deallocate_acceleration_structures(src);
}
void DeviceNestedResource::deallocate_swapchains(std::span<const VkSwapchainKHR> src) {
upstream->deallocate_swapchains(src);
}
Result<void, AllocateException> DeviceNestedResource::allocate_graphics_pipelines(std::span<GraphicsPipelineInfo> dst,
std::span<const GraphicsPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
return upstream->allocate_graphics_pipelines(dst, cis, loc);
}
void DeviceNestedResource::deallocate_graphics_pipelines(std::span<const GraphicsPipelineInfo> src) {
upstream->deallocate_graphics_pipelines(src);
}
Result<void, AllocateException> DeviceNestedResource::allocate_compute_pipelines(std::span<ComputePipelineInfo> dst,
std::span<const ComputePipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
return upstream->allocate_compute_pipelines(dst, cis, loc);
}
void DeviceNestedResource::deallocate_compute_pipelines(std::span<const ComputePipelineInfo> src) {
upstream->deallocate_compute_pipelines(src);
}
Result<void, AllocateException> DeviceNestedResource::allocate_ray_tracing_pipelines(std::span<RayTracingPipelineInfo> dst,
std::span<const RayTracingPipelineInstanceCreateInfo> cis,
SourceLocationAtFrame loc) {
return upstream->allocate_ray_tracing_pipelines(dst, cis, loc);
}
void DeviceNestedResource::deallocate_ray_tracing_pipelines(std::span<const RayTracingPipelineInfo> src) {
upstream->deallocate_ray_tracing_pipelines(src);
}
Result<void, AllocateException>
DeviceNestedResource::allocate_render_passes(std::span<VkRenderPass> dst, std::span<const RenderPassCreateInfo> cis, SourceLocationAtFrame loc) {
return upstream->allocate_render_passes(dst, cis, loc);
}
void DeviceNestedResource::deallocate_render_passes(std::span<const VkRenderPass> src) {
return upstream->deallocate_render_passes(src);
}
} // namespace vuk<file_sep>// REQUIRED
// 1.0
VUK_X(vkCmdBindDescriptorSets)
VUK_X(vkCmdBindIndexBuffer)
VUK_X(vkCmdBindPipeline)
VUK_X(vkCmdBindVertexBuffers)
VUK_X(vkCmdBlitImage)
VUK_X(vkCmdClearColorImage)
VUK_X(vkCmdClearDepthStencilImage)
VUK_X(vkCmdCopyBuffer)
VUK_X(vkCmdCopyBufferToImage)
VUK_X(vkCmdCopyImageToBuffer)
VUK_X(vkCmdFillBuffer)
VUK_X(vkCmdUpdateBuffer)
VUK_X(vkCmdResolveImage)
VUK_X(vkCmdPipelineBarrier)
VUK_X(vkCmdWriteTimestamp)
VUK_X(vkCmdDraw)
VUK_X(vkCmdDrawIndexed)
VUK_X(vkCmdDrawIndexedIndirect)
VUK_X(vkCmdDispatch)
VUK_X(vkCmdDispatchIndirect)
VUK_X(vkCmdPushConstants)
VUK_X(vkCmdSetViewport)
VUK_X(vkCmdSetScissor)
VUK_X(vkCmdSetLineWidth)
VUK_X(vkCmdSetDepthBias)
VUK_X(vkCmdSetBlendConstants)
VUK_X(vkCmdSetDepthBounds)
VUK_Y(vkGetPhysicalDeviceProperties)
VUK_X(vkCreateFramebuffer)
VUK_X(vkDestroyFramebuffer)
VUK_X(vkCreateCommandPool)
VUK_X(vkResetCommandPool)
VUK_X(vkDestroyCommandPool)
VUK_X(vkAllocateCommandBuffers)
VUK_X(vkBeginCommandBuffer)
VUK_X(vkEndCommandBuffer)
VUK_X(vkFreeCommandBuffers)
VUK_X(vkCreateDescriptorPool)
VUK_X(vkResetDescriptorPool)
VUK_X(vkDestroyDescriptorPool)
VUK_X(vkAllocateDescriptorSets)
VUK_X(vkUpdateDescriptorSets)
VUK_X(vkCreateGraphicsPipelines)
VUK_X(vkCreateComputePipelines)
VUK_X(vkDestroyPipeline)
VUK_X(vkCreateQueryPool)
VUK_X(vkGetQueryPoolResults)
VUK_X(vkDestroyQueryPool)
VUK_X(vkCreatePipelineCache)
VUK_X(vkGetPipelineCacheData)
VUK_X(vkDestroyPipelineCache)
VUK_X(vkCreateRenderPass)
VUK_X(vkCmdBeginRenderPass)
VUK_X(vkCmdNextSubpass)
VUK_X(vkCmdEndRenderPass)
VUK_X(vkDestroyRenderPass)
VUK_X(vkCreateSampler)
VUK_X(vkDestroySampler)
VUK_X(vkCreateShaderModule)
VUK_X(vkDestroyShaderModule)
VUK_X(vkCreateImageView)
VUK_X(vkDestroyImageView)
VUK_X(vkCreateDescriptorSetLayout)
VUK_X(vkDestroyDescriptorSetLayout)
VUK_X(vkCreatePipelineLayout)
VUK_X(vkDestroyPipelineLayout)
VUK_X(vkCreateFence)
VUK_X(vkWaitForFences)
VUK_X(vkDestroyFence)
VUK_X(vkCreateSemaphore)
VUK_X(vkWaitSemaphores)
VUK_X(vkDestroySemaphore)
VUK_X(vkQueueSubmit)
VUK_X(vkDeviceWaitIdle)
VUK_Y(vkGetPhysicalDeviceMemoryProperties)
VUK_X(vkAllocateMemory)
VUK_X(vkFreeMemory)
VUK_X(vkMapMemory)
VUK_X(vkUnmapMemory)
VUK_X(vkFlushMappedMemoryRanges)
VUK_X(vkInvalidateMappedMemoryRanges)
VUK_X(vkBindBufferMemory)
VUK_X(vkBindImageMemory)
VUK_X(vkGetBufferMemoryRequirements)
VUK_X(vkGetImageMemoryRequirements)
VUK_X(vkCreateBuffer)
VUK_X(vkDestroyBuffer)
VUK_X(vkCreateImage)
VUK_X(vkDestroyImage)
// 1.1
VUK_Y(vkGetPhysicalDeviceProperties2)
// 1.2
VUK_X(vkGetBufferDeviceAddress)
VUK_X(vkCmdDrawIndexedIndirectCount)
VUK_X(vkResetQueryPool)
// sync2 or 1.3
VUK_X(vkCmdPipelineBarrier2KHR)
VUK_X(vkQueueSubmit2KHR)<file_sep>#pragma once
#include "vuk_fwd.hpp"
#include <bit>
#include <cstdint>
namespace vuk {
template<uint64_t Count>
struct Bitset {
static constexpr uint64_t bitmask(uint64_t const onecount) {
return static_cast<uint64_t>(-(onecount != 0)) & (static_cast<uint64_t>(-1) >> (8*sizeof(uint64_t) - onecount));
}
static constexpr uint64_t n_bits = sizeof(uint64_t) * 8;
static constexpr uint64_t n_words = idivceil(Count, n_bits);
static constexpr uint64_t remainder = Count - n_bits * (Count / n_bits);
static constexpr uint64_t last_word_mask = remainder > 0 ? bitmask(remainder) : 0;
uint64_t words[n_words];
Bitset& set(uint64_t pos, bool value = true) noexcept {
auto word = pos / n_bits;
if (value) {
words[word] |= 1ULL << (pos - n_bits * word);
} else {
words[word] &= ~(1ULL << (pos - n_bits * word));
}
return *this;
}
uint64_t to_ulong() const noexcept{
static_assert(n_words == 1);
return words[0];
}
uint64_t count() const noexcept {
uint64_t accum = 0;
for (uint64_t i = 0; i < (Count / n_bits); i++) {
accum += std::popcount(words[i]);
}
if constexpr (remainder > 0) {
accum += std::popcount(words[n_words - 1] & last_word_mask);
}
return accum;
}
bool test(uint64_t pos) const noexcept {
auto word = pos / n_bits;
return words[word] & 1ULL << (pos - n_bits * word);
}
void reset() noexcept {
for (uint64_t i = 0; i < n_words; i++) {
words[i] = 0;
}
}
bool operator==(const Bitset& other) const noexcept {
for (uint64_t i = 0; i < (Count / n_bits); i++) {
if (words[i] != other.words[i])
return false;
}
if constexpr (remainder > 0) {
return (words[n_words - 1] & last_word_mask) == (other.words[n_words - 1] & last_word_mask);
}
return true;
}
Bitset operator|(const Bitset& other) const noexcept {
Bitset out;
for (uint64_t i = 0; i < (Count / n_bits); i++) {
out.words[i] = words[i] | other.words[i];
}
if constexpr (remainder > 0) {
out.words[n_words - 1] = (words[n_words - 1] & last_word_mask) | (other.words[n_words - 1] & last_word_mask);
}
return out;
}
};
} // namespace vuk<file_sep>#pragma once
#include "vuk/Config.hpp"
#include "vuk/Types.hpp"
#include <vector>
namespace vuk {
enum class ColorSpaceKHR {
eSrgbNonlinear = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
eDisplayP3NonlinearEXT = VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT,
eExtendedSrgbLinearEXT = VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT,
eDisplayP3LinearEXT = VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT,
eDciP3NonlinearEXT = VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT,
eBt709LinearEXT = VK_COLOR_SPACE_BT709_LINEAR_EXT,
eBt709NonlinearEXT = VK_COLOR_SPACE_BT709_NONLINEAR_EXT,
eBt2020LinearEXT = VK_COLOR_SPACE_BT2020_LINEAR_EXT,
eHdr10St2084EXT = VK_COLOR_SPACE_HDR10_ST2084_EXT,
eDolbyvisionEXT = VK_COLOR_SPACE_DOLBYVISION_EXT,
eHdr10HlgEXT = VK_COLOR_SPACE_HDR10_HLG_EXT,
eAdobergbLinearEXT = VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT,
eAdobergbNonlinearEXT = VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT,
ePassThroughEXT = VK_COLOR_SPACE_PASS_THROUGH_EXT,
eExtendedSrgbNonlinearEXT = VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT,
eDisplayNativeAMD = VK_COLOR_SPACE_DISPLAY_NATIVE_AMD,
eVkColorspaceSrgbNonlinear = VK_COLORSPACE_SRGB_NONLINEAR_KHR,
eDciP3LinearEXT = VK_COLOR_SPACE_DCI_P3_LINEAR_EXT
};
struct SurfaceFormatKHR {
Format format = Format::eUndefined;
ColorSpaceKHR colorSpace = ColorSpaceKHR::eSrgbNonlinear;
operator VkSurfaceFormatKHR const&() const noexcept {
return *reinterpret_cast<const VkSurfaceFormatKHR*>(this);
}
operator VkSurfaceFormatKHR&() noexcept {
return *reinterpret_cast<VkSurfaceFormatKHR*>(this);
}
bool operator==(SurfaceFormatKHR const& rhs) const noexcept {
return (format == rhs.format) && (colorSpace == rhs.colorSpace);
}
bool operator!=(SurfaceFormatKHR const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(sizeof(SurfaceFormatKHR) == sizeof(VkSurfaceFormatKHR), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<SurfaceFormatKHR>::value, "struct wrapper is not a standard layout!");
enum class PresentModeKHR {
eImmediate = VK_PRESENT_MODE_IMMEDIATE_KHR,
eMailbox = VK_PRESENT_MODE_MAILBOX_KHR,
eFifo = VK_PRESENT_MODE_FIFO_KHR,
eFifoRelaxed = VK_PRESENT_MODE_FIFO_RELAXED_KHR,
eSharedDemandRefresh = VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR,
eSharedContinuousRefresh = VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR
};
struct Swapchain {
VkSwapchainKHR swapchain;
VkSurfaceKHR surface;
vuk::Format format;
vuk::Extent2D extent = { 0, 0 };
std::vector<vuk::Image> images;
std::vector<vuk::ImageView> image_views;
};
using SwapchainRef = Swapchain*;
} // namespace vuk<file_sep>
### **vuk** - A rendergraph-based abstraction for Vulkan
[](https://discord.gg/UNkJMHgUmZ)
[](https://vuk.readthedocs.io)
[](https://github.com/martty/vuk/actions/workflows/cmake.yml)
### Quick Start
1. Grab the vuk repository
2. Compile the examples
3. Run the example browser and get a feel for the library
```
git clone http://github.com/martty/vuk
cd vuk
git submodule init
git submodule update --recursive
mkdir build
cd build
mkdir debug
cd debug
cmake ../.. -G Ninja -DVUK_BUILD_EXAMPLES=ON -DVUK_USE_DXC=OFF
cmake --build .
./vuk_all_examples
```
(if building with a multi-config generator, do not make the `debug` folder)
### Overview of using **vuk**
1. Initialize your window(s) and Vulkan device
2. Create a `vuk::Context` object
3. Each frame:
1. Each frame, prepare high level description of your rendering, in the form of `vuk::Pass`
2. Bind concrete resources as inputs and outputs
3. Bind managed resources (temporary resources used by the rendergraph)
4. Record the execution your rendergraph into a command buffer
5. Submit and present
### What does **vuk** do
- [x] Automatically deduces renderpasses, subpasses and framebuffers
- [x] with all the synchronization handled for you
- [x] including buffers
- [x] images
- [x] and rendertargets.
- [x] for multiple queues
- [ ] using fine grained synchronization when possible (events)
- [x] Automatically transitions images into proper layouts
- [x] for renderpasses
- [x] and commands outside of renderpasses (eg. blitting).
- [x] Automates pipeline creation with
- [x] optionally compiling your shaders at runtime using shaderc
- [x] pipeline layouts and
- [x] descriptor set layouts
- [x] by reflecting your shaders
- [x] and deducing parameters based on renderpass and framebuffer.
- [x] Automates resource binding with hashmaps, reducing descriptor set allocations and updates.
- [x] Handles temporary allocations for a frame
- [x] Handles long-term allocations with RAII handles
- [x] Comes with lots of sugar to simplify common operations, but still exposing the full Vulkan interface:
- [x] Matching viewport/scissor dimensions to attachment sizes
- [x] Simplified vertex format specification
- [x] Blend presets
- [x] Directly writable mapped UBOs
- [x] Automatic management of multisampling
- [x] Helps debugging by naming the internal resources
- [x] dear imgui integration code
<file_sep>#pragma once
#include <stdint.h>
namespace vuk {
/// @brief Handle to a query result
struct Query {
uint64_t id;
constexpr bool operator==(const Query& other) const noexcept {
return id == other.id;
}
};
struct TimestampQueryPool {
static constexpr uint32_t num_queries = 32;
VkQueryPool pool;
Query queries[num_queries];
uint8_t count = 0;
};
struct TimestampQuery {
VkQueryPool pool;
uint32_t id;
};
struct TimestampQueryCreateInfo {
TimestampQueryPool* pool = nullptr;
Query query;
};
} // namespace vuk
namespace std {
template<>
struct hash<vuk::Query> {
size_t operator()(vuk::Query const& s) const {
return hash<uint64_t>()(s.id);
}
};
} // namespace std<file_sep>#pragma once
#include <iterator>
namespace vuk {
// generic iterator for both const_iterator and iterator.
template<class Key, class Value>
class ConstMapIterator {
public:
using difference_type = std::ptrdiff_t;
using value_type = std::pair<const Key&, Value>;
using reference = value_type;
using iterator_category = std::forward_iterator_tag;
ConstMapIterator(void* iter) : _iter(iter) {}
ConstMapIterator(ConstMapIterator const&) noexcept;
ConstMapIterator& operator=(ConstMapIterator const& other) noexcept {
ConstMapIterator tmp(other);
swap(tmp);
return *this;
}
~ConstMapIterator();
void swap(ConstMapIterator& other) noexcept {
using std::swap;
swap(_iter, other._iter);
}
ConstMapIterator& operator++() noexcept;
ConstMapIterator operator++(int) const noexcept {
ConstMapIterator tmp = *this;
++(*this);
return tmp;
}
reference operator*() noexcept;
bool operator==(ConstMapIterator<Key, Value> const& o) const noexcept;
bool operator!=(ConstMapIterator<Key, Value> const& o) const noexcept {
return !(*this == o);
}
private:
void* _iter;
};
template<class Key, class Value>
struct MapProxy {
using const_iterator = ConstMapIterator<Key, Value>;
MapProxy(void* map) : _map(map) {}
const_iterator begin() const noexcept {
return cbegin();
}
const_iterator end() const noexcept {
return cend();
}
const_iterator cbegin() const noexcept;
const_iterator cend() const noexcept;
size_t size() const noexcept;
const_iterator find(Key) const noexcept;
private:
void* _map;
};
} // namespace vuk<file_sep>#include "example_runner.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
#include <stb_image.h>
/* 06_msaa
* In this example we will build on the previous example 04_texture, but we will render the cube to a multisampled texture,
* which we will resolve to the final swapchain image.
*
* These examples are powered by the example framework, which hides some of the code required, as that would be repeated for each example.
* Furthermore it allows launching individual examples and all examples with the example same code.
* Check out the framework (example_runner_*) files if interested!
*/
namespace {
float angle = 0.f;
auto box = util::generate_cube();
vuk::Unique<vuk::Buffer> verts, inds;
std::optional<vuk::Texture> texture_of_doge;
vuk::Example x{
.name = "06_msaa",
.setup =
[](vuk::ExampleRunner& runner, vuk::Allocator& allocator) {
// Same setup as for 04_texture, except we use spirv to create the pipeline
// This is a good option is if you don't want to ship shaderc or if you are caching or have your sl -> spirv pipeline
{
vuk::PipelineBaseCreateInfo pci;
pci.add_spirv(util::read_spirv((root / "examples/ubo_test_tex.vert.spv").generic_string()), (root / "examples/ubo_test_tex.vert").generic_string());
pci.add_spirv(util::read_spirv((root / "examples/triangle_depthshaded_tex.frag.spv").generic_string()),
(root / "examples/triangle_depthshaded_text.frag").generic_string());
runner.context->create_named_pipeline("textured_cube", pci);
}
int x, y, chans;
auto doge_image = stbi_load((root / "examples/doge.png").generic_string().c_str(), &x, &y, &chans, 4);
auto [tex, tex_fut] = create_texture(allocator, vuk::Format::eR8G8B8A8Srgb, vuk::Extent3D{ (unsigned)x, (unsigned)y, 1u }, doge_image, false);
texture_of_doge = std::move(tex);
runner.enqueue_setup(std::move(tex_fut));
stbi_image_free(doge_image);
// We set up the cube data, same as in example 02_cube
auto [vert_buf, vert_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.first));
verts = std::move(vert_buf);
auto [ind_buf, ind_fut] = create_buffer(allocator, vuk::MemoryUsage::eGPUonly, vuk::DomainFlagBits::eTransferOnGraphics, std::span(box.second));
inds = std::move(ind_buf);
// For the example, we just ask these that these uploads complete before moving on to rendering
// In an engine, you would integrate these uploads into some explicit system
runner.enqueue_setup(std::move(vert_fut));
runner.enqueue_setup(std::move(ind_fut));
},
.render =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator, vuk::Future target) {
struct VP {
glm::mat4 view;
glm::mat4 proj;
} vp;
vp.view = glm::lookAt(glm::vec3(0, 1.5, 3.5), glm::vec3(0), glm::vec3(0, 1, 0));
vp.proj = glm::perspective(glm::degrees(70.f), 1.f, 1.f, 10.f);
vp.proj[1][1] *= -1;
auto [buboVP, uboVP_fut] = create_buffer(frame_allocator, vuk::MemoryUsage::eCPUtoGPU, vuk::DomainFlagBits::eTransferOnGraphics, std::span(&vp, 1));
auto uboVP = *buboVP;
vuk::RenderGraph rg("06");
rg.attach_in("06_msaa", std::move(target));
// The rendering pass is unchanged by going to multisampled,
// but we will use an offscreen multisampled color attachment
rg.add_pass({ .resources = { "06_msaa_MS"_image >> vuk::eColorWrite, "06_msaa_depth"_image >> vuk::eDepthStencilRW },
.execute = [uboVP](vuk::CommandBuffer& command_buffer) {
command_buffer.set_viewport(0, vuk::Rect2D::framebuffer())
.set_scissor(0, vuk::Rect2D::framebuffer())
.set_rasterization({}) // Set the default rasterization state
// Set the depth/stencil state
.set_depth_stencil(vuk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
.depthWriteEnable = true,
.depthCompareOp = vuk::CompareOp::eLessOrEqual,
})
.broadcast_color_blend({}) // Set the default color blend state
.bind_vertex_buffer(0,
*verts,
0,
vuk::Packed{ vuk::Format::eR32G32B32Sfloat,
vuk::Ignore{ offsetof(util::Vertex, uv_coordinates) - sizeof(util::Vertex::position) },
vuk::Format::eR32G32Sfloat })
.bind_index_buffer(*inds, vuk::IndexType::eUint32)
.bind_image(0, 2, *texture_of_doge->view)
.bind_sampler(0, 2, {})
.bind_graphics_pipeline("textured_cube")
.bind_buffer(0, 0, uboVP);
glm::mat4* model = command_buffer.map_scratch_buffer<glm::mat4>(0, 1);
*model = static_cast<glm::mat4>(glm::angleAxis(glm::radians(angle), glm::vec3(0.f, 1.f, 0.f)));
command_buffer.draw_indexed(box.second.size(), 1, 0, 0, 0);
} });
angle += 180.f * ImGui::GetIO().DeltaTime;
// We mark our MS attachment as multisampled (8 samples)
// Since resolving requires equal sized images, we can actually infer the size of the MS attachment
// from the final image, and we don't need to specify here
// We use the swapchain format, since resolving needs identical formats
rg.attach_and_clear_image(
"06_msaa_MS", { .format = runner.swapchain->format, .sample_count = vuk::Samples::e8 }, vuk::ClearColor{ 0.f, 0.f, 0.f, 0.f });
rg.attach_and_clear_image("06_msaa_depth", { .format = vuk::Format::eD32Sfloat }, vuk::ClearDepthStencil{ 1.0f, 0 });
// We mark our final result "06_msaa_final" attachment to be a result of a resolve from "06_msaa_MS"
rg.resolve_resource_into("06_msaa", "06_msaa_final", "06_msaa_MS+");
return vuk::Future{ std::make_unique<vuk::RenderGraph>(std::move(rg)), "06_msaa_final" };
},
.cleanup =
[](vuk::ExampleRunner& runner, vuk::Allocator& frame_allocator) {
verts.reset();
inds.reset();
texture_of_doge.reset();
}
};
REGISTER_EXAMPLE(x);
} // namespace<file_sep>#pragma once
#include <stdint.h>
#include <string_view>
// https://gist.github.com/filsinger/1255697/21762ea83a2d3c17561c8e6a29f44249a4626f9e
namespace hash {
template<typename S>
struct fnv_internal;
template<typename S>
struct fnv1a_tpl;
template<>
struct fnv_internal<uint32_t> {
constexpr static uint32_t default_offset_basis = 0x811C9DC5;
constexpr static uint32_t prime = 0x01000193;
};
template<>
struct fnv1a_tpl<uint32_t> : public fnv_internal<uint32_t> {
constexpr static inline uint32_t hash(char const* const aString, const uint32_t val = default_offset_basis) {
return (aString[0] == '\0') ? val : hash(&aString[1], (val ^ uint32_t(aString[0])) * prime);
}
constexpr static inline uint32_t hash(char const* const aString, const size_t aStrlen, const uint32_t val) {
return (aStrlen == 0) ? val : hash(aString + 1, aStrlen - 1, (val ^ uint32_t(aString[0])) * prime);
}
};
using fnv1a = fnv1a_tpl<uint32_t>;
} // namespace hash
inline constexpr uint32_t operator"" _fnv1a(const char* aString, const size_t aStrlen) {
typedef hash::fnv1a_tpl<uint32_t> hash_type;
return hash_type::hash(aString, aStrlen, hash_type::default_offset_basis);
}
template<typename T>
inline void hash_combine(size_t& seed, const T& v) noexcept {
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
inline constexpr void hash_combine_direct(uint32_t& seed, uint32_t v) noexcept {
seed ^= v + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
#define FWD(x) (static_cast<decltype(x)&&>(x))
template<typename T, typename... Rest>
inline void hash_combine(size_t& seed, const T& v, Rest&&... rest) noexcept {
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
hash_combine(seed, FWD(rest)...);
}
#undef FWD<file_sep>#include "vuk/Name.hpp"
#include "vuk/Hash.hpp"
#include <array>
#include <robin_hood.h>
#include <shared_mutex>
#include <mutex>
#include <string>
#include <string_view>
#include <vector>
namespace {
struct Intern {
static constexpr size_t arr_siz = 2048;
const char* add(std::string_view s) {
auto hash = hash::fnv1a::hash(s.data(), (uint32_t)s.size(), hash::fnv1a::default_offset_basis);
{
std::shared_lock _(lock);
if (auto it = map.find(hash); it != map.end()) {
return it->second;
}
}
std::unique_lock _(lock);
// second lookup, under a unique lock, so there are no races
if (auto it = map.find(hash); it != map.end()) {
return it->second;
}
for (auto& [size, bf] : buffers) {
auto buffer = std::string_view(bf->data(), bf->size());
auto pos = buffer.find(s);
while (pos != std::string::npos && buffer[pos + s.size()] != '\0') {
pos = buffer.find(s, pos + 1);
}
if (pos == std::string_view::npos) {
if ((size + s.size() + 1) < bf->size()) {
auto osize = size;
s.copy(bf->data() + size, s.size());
*(bf->data() + size + s.size()) = '\0';
size += s.size() + 1;
map.emplace(hash, bf->data() + osize);
return bf->data() + osize;
}
} else { // for returning tail substrings
map.emplace(hash, bf->data() + pos);
return bf->data() + pos;
}
}
buffers.resize(buffers.size() + 1);
auto& [nsize, nbuf] = buffers.back();
nbuf = new std::array<char, arr_siz>{};
s.copy(nbuf->data(), s.size());
*(nbuf->data() + s.size()) = '\0';
nsize += s.size() + 1;
map.emplace(hash, nbuf->data());
return nbuf->data();
}
Intern() {
buffers.resize(1);
buffers[0].first = 1;
buffers[0].second = new std::array<char, arr_siz>;
buffers[0].second->at(0) = '\0';
}
// to store the strings
std::vector<std::pair<size_t, std::array<char, arr_siz>*>> buffers;
robin_hood::unordered_flat_map<uint32_t, const char*> map;
std::shared_mutex lock;
};
static Intern g_intern;
} // namespace
namespace vuk {
Name::Name(const char* str) noexcept {
id = g_intern.add(str);
}
Name::Name(std::string_view str) noexcept {
id = g_intern.add(str);
}
std::string_view Name::to_sv() const noexcept {
return id;
}
bool Name::is_invalid() const noexcept {
return id == &invalid_value[0];
}
Name Name::append(std::string_view other) const noexcept {
auto ourlen = strlen(id);
auto theirlen = other.size();
auto hash = hash::fnv1a::hash(id, (uint32_t)ourlen, hash::fnv1a::default_offset_basis);
hash = hash::fnv1a::hash(other.data(), (uint32_t)theirlen, hash);
// speculative
{
std::shared_lock _(g_intern.lock);
if (auto it = g_intern.map.find(hash); it != g_intern.map.end()) {
Name n;
n.id = it->second;
return n;
}
}
std::string app;
app.reserve(ourlen + theirlen);
app.append(id);
app.append(other);
return Name(app);
}
} // namespace vuk
namespace std {
size_t hash<vuk::Name>::operator()(vuk::Name const& s) const {
return hash<const char*>()(s.id);
}
size_t hash<vuk::QualifiedName>::operator()(vuk::QualifiedName const& s) const {
uint32_t h = (uint32_t)hash<vuk::Name>()(s.prefix);
::hash_combine_direct(h, (uint32_t)hash<vuk::Name>()(s.name));
return h;
}
} // namespace std<file_sep>#pragma once
#include "../src/CreateInfo.hpp"
#include "vuk/Bitset.hpp"
#include "vuk/Config.hpp"
#include "vuk/Descriptor.hpp"
#include "vuk/FixedVector.hpp"
#include "vuk/Hash.hpp"
#include "vuk/Image.hpp"
#include "vuk/PipelineTypes.hpp"
#include "vuk/Program.hpp"
#include "vuk/ShaderSource.hpp"
#include <bit>
#include <vector>
namespace vuk {
static constexpr uint32_t graphics_stage_count = 5;
struct PipelineLayoutCreateInfo {
VkPipelineLayoutCreateInfo plci{ .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
vuk::fixed_vector<VkPushConstantRange, VUK_MAX_PUSHCONSTANT_RANGES> pcrs;
vuk::fixed_vector<vuk::DescriptorSetLayoutCreateInfo, VUK_MAX_SETS> dslcis;
bool operator==(const PipelineLayoutCreateInfo& o) const noexcept {
return plci.flags == o.plci.flags && pcrs == o.pcrs && dslcis == o.dslcis;
}
};
template<>
struct create_info<VkPipelineLayout> {
using type = vuk::PipelineLayoutCreateInfo;
};
enum class HitGroupType {
eTriangles = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR,
eProcedural = VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR
};
struct HitGroup {
HitGroupType type;
uint32_t closest_hit = VK_SHADER_UNUSED_KHR;
uint32_t any_hit = VK_SHADER_UNUSED_KHR;
uint32_t intersection = VK_SHADER_UNUSED_KHR;
};
struct PipelineBaseCreateInfoBase {
// 4 valid flags
Bitset<4 * VUK_MAX_SETS* VUK_MAX_BINDINGS> binding_flags = {};
// set flags on specific descriptor in specific set
void set_binding_flags(unsigned set, unsigned binding, vuk::DescriptorBindingFlags flags) noexcept {
unsigned f = static_cast<unsigned>(flags);
binding_flags.set(set * 4 * VUK_MAX_BINDINGS + binding * 4 + 0, f & 0b1);
binding_flags.set(set * 4 * VUK_MAX_BINDINGS + binding * 4 + 1, f & 0b10);
binding_flags.set(set * 4 * VUK_MAX_BINDINGS + binding * 4 + 2, f & 0b100);
binding_flags.set(set * 4 * VUK_MAX_BINDINGS + binding * 4 + 3, f & 0b1000);
}
// if the set has a variable count binding, the maximum number of bindings possible
std::array<uint32_t, VUK_MAX_SETS> variable_count_max = {};
void set_variable_count_binding(unsigned set, unsigned binding, uint32_t max_descriptors) noexcept {
// clear all variable count bits
for (unsigned i = 0; i < VUK_MAX_BINDINGS; i++) {
binding_flags.set(set * 4 * VUK_MAX_BINDINGS + i * 4 + 3, 0);
}
// set variable count (0x8)
binding_flags.set(set * 4 * VUK_MAX_BINDINGS + binding * 4 + 3, 1);
variable_count_max[set] = max_descriptors;
}
vuk::fixed_vector<DescriptorSetLayoutCreateInfo, VUK_MAX_SETS> explicit_set_layouts = {};
};
/* filled out by the user */
struct PipelineBaseCreateInfo : PipelineBaseCreateInfoBase {
friend class CommandBuffer;
friend class Context;
public:
void add_shader(ShaderSource source, std::string filename) {
shaders.emplace_back(std::move(source));
shader_paths.emplace_back(std::move(filename));
}
#if VUK_USE_SHADERC
void add_glsl(std::string_view source, std::string filename) {
shaders.emplace_back(ShaderSource::glsl(source));
shader_paths.emplace_back(std::move(filename));
}
void define(std::string key, std::string value) {
defines.emplace_back(std::move(key), std::move(value));
}
#endif
#if VUK_USE_DXC
void add_hlsl(std::string_view source, std::string filename, HlslShaderStage stage = HlslShaderStage::eInferred) {
shaders.emplace_back(ShaderSource::hlsl(source, stage));
shader_paths.emplace_back(std::move(filename));
}
#endif
void add_spirv(std::vector<uint32_t> source, std::string filename) {
shaders.emplace_back(ShaderSource::spirv(std::move(source)));
shader_paths.emplace_back(std::move(filename));
}
void add_static_spirv(const uint32_t* source, size_t num_words, std::string identifier) {
shaders.emplace_back(ShaderSource::spirv(source, num_words));
shader_paths.emplace_back(std::move(identifier));
}
void add_hit_group(HitGroup hit_group) {
hit_groups.emplace_back(hit_group);
}
std::vector<ShaderSource> shaders;
std::vector<std::string> shader_paths;
std::vector<HitGroup> hit_groups;
std::vector<std::pair<std::string, std::string>> defines;
/// @brief Recursion depth for RT pipelines, corresponding to maxPipelineRayRecursionDepth
uint32_t max_ray_recursion_depth = 1;
friend struct std::hash<PipelineBaseCreateInfo>;
public:
static vuk::fixed_vector<vuk::DescriptorSetLayoutCreateInfo, VUK_MAX_SETS> build_descriptor_layouts(const Program&, const PipelineBaseCreateInfoBase&);
bool operator==(const PipelineBaseCreateInfo& o) const noexcept {
return shaders == o.shaders && binding_flags == o.binding_flags && variable_count_max == o.variable_count_max && defines == o.defines;
}
};
struct PipelineBaseInfo {
Name pipeline_name;
vuk::Program reflection_info;
std::vector<VkPipelineShaderStageCreateInfo> psscis;
VkPipelineLayout pipeline_layout;
std::array<DescriptorSetLayoutAllocInfo, VUK_MAX_SETS> layout_info = {};
fixed_vector<DescriptorSetLayoutCreateInfo, VUK_MAX_SETS> dslcis = {}; // saved for debug purposes
std::vector<HitGroup> hit_groups;
uint32_t max_ray_recursion_depth;
// 4 valid flags
Bitset<4 * VUK_MAX_SETS* VUK_MAX_BINDINGS> binding_flags = {};
// if the set has a variable count binding, the maximum number of bindings possible
std::array<uint32_t, VUK_MAX_SETS> variable_count_max = {};
};
template<>
struct create_info<PipelineBaseInfo> {
using type = vuk::PipelineBaseCreateInfo;
};
} // namespace vuk
namespace std {
template<class T>
struct hash<std::vector<T>> {
size_t operator()(std::vector<T> const& x) const noexcept {
size_t h = 0;
for (auto& e : x) {
hash_combine(h, e);
}
return h;
}
};
template<class T, size_t N>
struct hash<vuk::fixed_vector<T, N>> {
size_t operator()(vuk::fixed_vector<T, N> const& x) const noexcept {
size_t h = 0;
for (auto& e : x) {
hash_combine(h, e);
}
return h;
}
};
template<class T1, class T2>
struct hash<std::pair<T1, T2>> {
size_t operator()(std::pair<T1, T2> const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.first, x.second);
return h;
}
};
template<>
struct hash<vuk::ShaderSource> {
size_t operator()(vuk::ShaderSource const& x) const noexcept;
};
template<>
struct hash<vuk::PipelineBaseCreateInfo> {
size_t operator()(vuk::PipelineBaseCreateInfo const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.shaders, x.defines);
return h;
}
};
}; // namespace std
<file_sep>#pragma once
#include "vuk/Hash.hpp"
#include <string_view>
namespace vuk {
class Name {
public:
Name() = default;
Name(decltype(nullptr));
Name(const char* str) noexcept;
Name(std::string_view str) noexcept;
std::string_view to_sv() const noexcept;
const char* c_str() const noexcept {
return id;
}
Name append(std::string_view other) const noexcept;
bool is_invalid() const noexcept;
friend bool operator==(Name a, Name b) noexcept {
return a.id == b.id;
}
friend bool operator!=(Name a, Name b) noexcept {
return a.id != b.id;
}
friend bool operator<(Name a, Name b) noexcept {
return (uintptr_t)a.id < (uintptr_t)b.id;
}
private:
static constexpr const char invalid_value[] = "UNNAMED";
const char* id = invalid_value;
friend struct std::hash<vuk::Name>;
};
struct QualifiedName {
Name prefix;
Name name;
constexpr QualifiedName() = default;
constexpr QualifiedName(Name prefix, Name name) : prefix(prefix), name(name) {}
bool operator==(const QualifiedName&) const noexcept = default;
bool is_invalid() const noexcept {
return name.is_invalid();
}
};
// a stable Name that can refer to an arbitrary subgraph Name
struct NameReference {
struct RenderGraph* rg = nullptr;
QualifiedName name;
static constexpr NameReference direct(Name n) {
return NameReference{ nullptr, { Name{}, n } };
}
};
} // namespace vuk
namespace std {
template<>
struct hash<vuk::Name> {
size_t operator()(vuk::Name const& s) const;
};
template<>
struct hash<vuk::QualifiedName> {
size_t operator()(vuk::QualifiedName const& s) const;
};
} // namespace std
<file_sep>#pragma once
#include <string.h>
#include <algorithm>
#include <memory>
#include <utility>
namespace vuk {
// https://gist.github.com/ThePhD/8153067
template<typename T, std::size_t n, std::size_t a = std::alignment_of<T>::value>
class fixed_vector {
public:
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef T* pointer_type;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef pointer_type iterator;
typedef const pointer_type const_iterator;
private:
alignas(a) std::byte items[sizeof(T) * n];
std::size_t len;
constexpr T* ptrat(std::size_t idx) {
return static_cast<T*>(static_cast<void*>(&items)) + idx;
}
constexpr const T* ptrat(std::size_t idx) const {
return static_cast<const T*>(static_cast<const void*>(&items)) + idx;
}
constexpr T& refat(std::size_t idx) {
return *ptrat(idx);
}
constexpr const T& refat(std::size_t idx) const {
return *ptrat(idx);
}
public:
constexpr static std::size_t max_size() {
return n;
}
constexpr fixed_vector() : len(0) {
memset(&items, 0, sizeof(T) * n);
}
constexpr fixed_vector(std::size_t capacity) : len(std::min(n, capacity)) {
memset(&items, 0, sizeof(T) * n);
}
template<std::size_t c>
constexpr fixed_vector(const T (&arr)[c]) : len(c) {
memset(&items, 0, sizeof(T) * n);
static_assert(c < n, "Array too large to initialize fixed_vector");
std::copy(std::addressof(arr[0]), std::addressof(arr[c]), data());
}
constexpr fixed_vector(std::initializer_list<T> initializer) : len(std::min(n, initializer.size())) {
memset(&items, 0, sizeof(T) * n);
std::copy(initializer.begin(), initializer.begin() + len, data());
}
constexpr fixed_vector(const fixed_vector& o) {
memset(&items, 0, sizeof(T) * n);
std::uninitialized_copy(o.begin(), o.end(), begin());
len = o.len;
}
constexpr fixed_vector& operator=(const fixed_vector& o) {
auto existing = std::min(len, o.len);
std::copy_n(o.begin(), existing, begin());
std::uninitialized_copy(o.begin() + existing, o.end(), begin() + existing);
resize(o.len);
return *this;
}
constexpr fixed_vector(fixed_vector&& o) {
memset(&items, 0, sizeof(T) * n);
std::uninitialized_move(o.begin(), o.end(), begin());
len = o.len;
o.resize(0);
}
constexpr fixed_vector& operator=(fixed_vector&& o) {
auto existing = std::min(len, o.len);
std::copy_n(std::make_move_iterator(o.begin()), existing, begin());
std::uninitialized_move(o.begin() + existing, o.end(), begin() + existing);
resize(o.len);
o.resize(0);
return *this;
}
constexpr ~fixed_vector() {
for (std::size_t i = 0; i < len; i++) {
ptrat(i)->~T();
}
}
constexpr bool empty() const {
return len < 1;
}
constexpr bool not_empty() const {
return len > 0;
}
constexpr bool full() const {
return len >= n;
}
constexpr void push_back(const T& item) {
new (ptrat(len++)) T(item);
}
constexpr void push_back(T&& item) {
new (ptrat(len++)) T(std::move(item));
}
template<typename... Tn>
constexpr T& emplace_back(Tn&&... argn) {
return *(new (ptrat(len++)) T(std::forward<Tn>(argn)...));
}
constexpr void pop_back() {
T& addr = refat(--len);
addr.~T();
}
constexpr void clear() {
for (; len > 0;) {
pop_back();
}
}
constexpr std::size_t size() const {
return len;
}
constexpr std::size_t capacity() const {
return n;
}
constexpr void resize(std::size_t sz) {
auto old_len = len;
while (len > sz)
pop_back();
if (old_len > len) {
memset(reinterpret_cast<char*>(&items) + len * sizeof(T), 0, sizeof(T) * (old_len - len));
}
len = std::min(sz, n);
}
constexpr void resize(std::size_t sz, const value_type& value) {
auto old_len = len;
while (len > sz)
pop_back();
if (old_len > len) {
memset(reinterpret_cast<char*>(&items) + len * sizeof(T), 0, sizeof(T) * (old_len - len));
}
len = std::min(sz, n);
if (len > old_len) {
std::uninitialized_fill(begin() + old_len, begin() + len, value);
}
}
constexpr T* data() {
return ptrat(0);
}
constexpr const T* data() const {
return ptrat(0);
}
constexpr T& operator[](std::size_t idx) {
return refat(idx);
}
constexpr const T& operator[](std::size_t idx) const {
return refat(idx);
}
constexpr T& front() {
return refat(0);
}
constexpr T& back() {
return refat(len - 1);
}
constexpr const T& front() const {
return refat(0);
}
constexpr const T& back() const {
return refat(len - 1);
}
constexpr T* begin() {
return data();
}
constexpr const T* cbegin() {
return data();
}
constexpr const T* begin() const {
return data();
}
constexpr const T* cbegin() const {
return data();
}
constexpr T* end() {
return data() + len;
}
constexpr const T* cend() {
return data() + len;
}
constexpr const T* end() const {
return data() + len;
}
constexpr const T* cend() const {
return data() + len;
}
/*
iterator insert(const_iterator pos, const T& value);
iterator insert(const_iterator pos, T&& value);
iterator insert( const_iterator pos, std::initializer_list<T> ilist );
*/
template<class InputIt>
constexpr iterator insert(const_iterator pos, InputIt first, InputIt last) {
auto clen = std::distance(first, last);
if (clen == 0)
return pos;
std::copy(pos, pos + (len - std::distance(begin(), pos)), pos + clen);
std::copy(first, last, pos);
len += clen;
return pos;
}
constexpr bool operator==(const fixed_vector& o) const noexcept {
return std::equal(begin(), end(), o.begin(), o.end());
}
};
} // namespace vuk
<file_sep>#pragma once
#include "vuk/Config.hpp"
#include "vuk/Hash.hpp"
#include "vuk/vuk_fwd.hpp"
#include <compare>
#include <string_view>
#include <type_traits>
#define MOV(x) (static_cast<std::remove_reference_t<decltype(x)>&&>(x))
namespace vuk {
struct HandleBase {
size_t id = UINT64_MAX;
};
template<class T>
struct Handle : public HandleBase {
T payload;
constexpr bool operator==(const Handle& o) const noexcept {
return id == o.id;
}
};
template<typename Type>
class Unique {
Allocator* allocator;
Type payload;
public:
using element_type = Type;
explicit Unique() : allocator(nullptr), payload{} {}
explicit Unique(Allocator& allocator) : allocator(&allocator), payload{} {}
explicit Unique(Allocator& allocator, Type payload) : allocator(&allocator), payload(MOV(payload)) {}
Unique(Unique const&) = delete;
Unique(Unique&& other) noexcept : allocator(other.allocator), payload(other.release()) {}
~Unique() noexcept;
Unique& operator=(Unique const&) = delete;
Unique& operator=(Unique&& other) noexcept {
auto tmp = other.allocator;
reset(other.release());
allocator = tmp;
return *this;
}
explicit operator bool() const noexcept {
return static_cast<bool>(payload);
}
Type const* operator->() const noexcept {
return &payload;
}
Type* operator->() noexcept {
return &payload;
}
Type const& operator*() const noexcept {
return payload;
}
Type& operator*() noexcept {
return payload;
}
const Type& get() const noexcept {
return payload;
}
Type& get() noexcept {
return payload;
}
void reset(Type value = Type()) noexcept;
Type release() noexcept {
allocator = nullptr;
return MOV(payload);
}
void swap(Unique<Type>& rhs) noexcept {
std::swap(payload, rhs.payload);
std::swap(allocator, rhs.allocator);
}
};
template<typename Type>
inline void swap(Unique<Type>& lhs, Unique<Type>& rhs) noexcept {
lhs.swap(rhs);
}
} // namespace vuk
namespace std {
template<class T>
struct hash<vuk::Handle<T>> {
size_t operator()(vuk::Handle<T> const& x) const noexcept {
size_t h = 0;
hash_combine(h, x.id, reinterpret_cast<uint64_t>(x.payload));
return h;
}
};
} // namespace std
namespace vuk {
enum class SampleCountFlagBits : VkSampleCountFlags {
e1 = VK_SAMPLE_COUNT_1_BIT,
e2 = VK_SAMPLE_COUNT_2_BIT,
e4 = VK_SAMPLE_COUNT_4_BIT,
e8 = VK_SAMPLE_COUNT_8_BIT,
e16 = VK_SAMPLE_COUNT_16_BIT,
e32 = VK_SAMPLE_COUNT_32_BIT,
e64 = VK_SAMPLE_COUNT_64_BIT,
eInfer = 1024
};
struct Samples {
SampleCountFlagBits count;
struct Framebuffer {};
Samples() noexcept : count(SampleCountFlagBits::e1) {}
Samples(SampleCountFlagBits samples) noexcept : count(samples) {}
Samples(Framebuffer) noexcept : count(SampleCountFlagBits::eInfer) {}
constexpr static auto e1 = SampleCountFlagBits::e1;
constexpr static auto e2 = SampleCountFlagBits::e2;
constexpr static auto e4 = SampleCountFlagBits::e4;
constexpr static auto e8 = SampleCountFlagBits::e8;
constexpr static auto e16 = SampleCountFlagBits::e16;
constexpr static auto e32 = SampleCountFlagBits::e32;
constexpr static auto e64 = SampleCountFlagBits::e64;
constexpr static auto eInfer = SampleCountFlagBits::eInfer;
};
inline bool operator==(Samples const& a, Samples const& b) noexcept {
return a.count == b.count;
}
struct Offset3D;
struct Offset2D {
int32_t x = {};
int32_t y = {};
bool operator==(Offset2D const& rhs) const noexcept {
return (x == rhs.x) && (y == rhs.y);
}
bool operator!=(Offset2D const& rhs) const noexcept {
return !operator==(rhs);
}
operator VkOffset2D const&() const noexcept {
return *reinterpret_cast<const VkOffset2D*>(this);
}
operator VkOffset2D&() noexcept {
return *reinterpret_cast<VkOffset2D*>(this);
}
explicit operator Offset3D();
};
struct Extent3D;
struct Extent2D {
uint32_t width = {};
uint32_t height = {};
bool operator==(Extent2D const& rhs) const noexcept {
return (width == rhs.width) && (height == rhs.height);
}
bool operator!=(Extent2D const& rhs) const noexcept {
return !operator==(rhs);
}
operator VkExtent2D const&() const noexcept {
return *reinterpret_cast<const VkExtent2D*>(this);
}
operator VkExtent2D&() noexcept {
return *reinterpret_cast<VkExtent2D*>(this);
}
explicit operator Extent3D();
};
struct Offset3D {
int32_t x = {};
int32_t y = {};
int32_t z = {};
bool operator==(Offset3D const& rhs) const noexcept {
return (x == rhs.x) && (y == rhs.y) && (z == rhs.z);
}
bool operator!=(Offset3D const& rhs) const noexcept {
return !operator==(rhs);
}
operator VkOffset3D const&() const noexcept {
return *reinterpret_cast<const VkOffset3D*>(this);
}
operator VkOffset3D&() noexcept {
return *reinterpret_cast<VkOffset3D*>(this);
}
};
inline Offset2D::operator Offset3D() {
return Offset3D{ x, y, 0 };
}
struct Extent3D {
uint32_t width = {};
uint32_t height = {};
uint32_t depth = {};
auto operator<=>(const Extent3D&) const = default;
operator VkExtent3D const&() const noexcept {
return *reinterpret_cast<const VkExtent3D*>(this);
}
operator VkExtent3D&() noexcept {
return *reinterpret_cast<VkExtent3D*>(this);
}
};
inline Extent2D::operator Extent3D() {
return Extent3D{ width, height, 1u };
}
struct Viewport {
float x = {};
float y = {};
float width = {};
float height = {};
float minDepth = 0.f;
float maxDepth = 1.f;
operator VkViewport const&() const noexcept {
return *reinterpret_cast<const VkViewport*>(this);
}
operator VkViewport&() noexcept {
return *reinterpret_cast<VkViewport*>(this);
}
bool operator==(Viewport const& rhs) const noexcept {
return (x == rhs.x) && (y == rhs.y) && (width == rhs.width) && (height == rhs.height) && (minDepth == rhs.minDepth) && (maxDepth == rhs.maxDepth);
}
bool operator!=(Viewport const& rhs) const noexcept {
return !operator==(rhs);
}
};
static_assert(sizeof(Viewport) == sizeof(VkViewport), "struct and wrapper have different size!");
static_assert(std::is_standard_layout<Viewport>::value, "struct wrapper is not a standard layout!");
enum class Sizing { eAbsolute, eRelative };
struct Dimension3D {
Sizing sizing = Sizing::eAbsolute;
Extent3D extent;
struct Relative {
float width = 1.0f;
float height = 1.0f;
float depth = 1.0f;
auto operator<=>(const Relative&) const = default;
} _relative;
static Dimension3D absolute(uint32_t width, uint32_t height) noexcept {
return Dimension3D{ .extent = { width, height, 1 } };
}
static Dimension3D absolute(uint32_t width, uint32_t height, uint32_t depth) noexcept {
return Dimension3D{ .extent = { width, height, depth } };
}
static Dimension3D absolute(Extent2D extent) noexcept {
return Dimension3D{ .extent = static_cast<Extent3D>(extent) };
}
static Dimension3D relative(float width, float height) noexcept {
return Dimension3D{ .sizing = Sizing::eRelative, ._relative = { .width = width, .height = height } };
}
static Dimension3D framebuffer() noexcept {
return Dimension3D{ .sizing = Sizing::eRelative };
}
auto operator<=>(const Dimension3D&) const = default;
};
struct Rect2D {
Sizing sizing = Sizing::eAbsolute;
Offset2D offset = {};
Extent2D extent = {};
struct {
float x = 0.f;
float y = 0.f;
float width = 1.0f;
float height = 1.0f;
} _relative;
static Rect2D absolute(int32_t x, int32_t y, uint32_t width, uint32_t height) noexcept {
return Rect2D{ .offset = { x, y }, .extent = { width, height } };
}
static Rect2D absolute(Offset2D offset, Extent2D extent) noexcept {
return Rect2D{ .offset = offset, .extent = extent };
}
static Rect2D relative(float x, float y, float width, float height) noexcept {
return Rect2D{ .sizing = Sizing::eRelative, ._relative = { .x = x, .y = y, .width = width, .height = height } };
}
static Rect2D framebuffer() noexcept {
return Rect2D{ .sizing = Sizing::eRelative };
}
};
enum class Format {
eUndefined = VK_FORMAT_UNDEFINED,
eR4G4UnormPack8 = VK_FORMAT_R4G4_UNORM_PACK8,
eR4G4B4A4UnormPack16 = VK_FORMAT_R4G4B4A4_UNORM_PACK16,
eB4G4R4A4UnormPack16 = VK_FORMAT_B4G4R4A4_UNORM_PACK16,
eR5G6B5UnormPack16 = VK_FORMAT_R5G6B5_UNORM_PACK16,
eB5G6R5UnormPack16 = VK_FORMAT_B5G6R5_UNORM_PACK16,
eR5G5B5A1UnormPack16 = VK_FORMAT_R5G5B5A1_UNORM_PACK16,
eB5G5R5A1UnormPack16 = VK_FORMAT_B5G5R5A1_UNORM_PACK16,
eA1R5G5B5UnormPack16 = VK_FORMAT_A1R5G5B5_UNORM_PACK16,
eR8Unorm = VK_FORMAT_R8_UNORM,
eR8Snorm = VK_FORMAT_R8_SNORM,
eR8Uscaled = VK_FORMAT_R8_USCALED,
eR8Sscaled = VK_FORMAT_R8_SSCALED,
eR8Uint = VK_FORMAT_R8_UINT,
eR8Sint = VK_FORMAT_R8_SINT,
eR8Srgb = VK_FORMAT_R8_SRGB,
eR8G8Unorm = VK_FORMAT_R8G8_UNORM,
eR8G8Snorm = VK_FORMAT_R8G8_SNORM,
eR8G8Uscaled = VK_FORMAT_R8G8_USCALED,
eR8G8Sscaled = VK_FORMAT_R8G8_SSCALED,
eR8G8Uint = VK_FORMAT_R8G8_UINT,
eR8G8Sint = VK_FORMAT_R8G8_SINT,
eR8G8Srgb = VK_FORMAT_R8G8_SRGB,
eR8G8B8Unorm = VK_FORMAT_R8G8B8_UNORM,
eR8G8B8Snorm = VK_FORMAT_R8G8B8_SNORM,
eR8G8B8Uscaled = VK_FORMAT_R8G8B8_USCALED,
eR8G8B8Sscaled = VK_FORMAT_R8G8B8_SSCALED,
eR8G8B8Uint = VK_FORMAT_R8G8B8_UINT,
eR8G8B8Sint = VK_FORMAT_R8G8B8_SINT,
eR8G8B8Srgb = VK_FORMAT_R8G8B8_SRGB,
eB8G8R8Unorm = VK_FORMAT_B8G8R8_UNORM,
eB8G8R8Snorm = VK_FORMAT_B8G8R8_SNORM,
eB8G8R8Uscaled = VK_FORMAT_B8G8R8_USCALED,
eB8G8R8Sscaled = VK_FORMAT_B8G8R8_SSCALED,
eB8G8R8Uint = VK_FORMAT_B8G8R8_UINT,
eB8G8R8Sint = VK_FORMAT_B8G8R8_SINT,
eB8G8R8Srgb = VK_FORMAT_B8G8R8_SRGB,
eR8G8B8A8Unorm = VK_FORMAT_R8G8B8A8_UNORM,
eR8G8B8A8Snorm = VK_FORMAT_R8G8B8A8_SNORM,
eR8G8B8A8Uscaled = VK_FORMAT_R8G8B8A8_USCALED,
eR8G8B8A8Sscaled = VK_FORMAT_R8G8B8A8_SSCALED,
eR8G8B8A8Uint = VK_FORMAT_R8G8B8A8_UINT,
eR8G8B8A8Sint = VK_FORMAT_R8G8B8A8_SINT,
eR8G8B8A8Srgb = VK_FORMAT_R8G8B8A8_SRGB,
eB8G8R8A8Unorm = VK_FORMAT_B8G8R8A8_UNORM,
eB8G8R8A8Snorm = VK_FORMAT_B8G8R8A8_SNORM,
eB8G8R8A8Uscaled = VK_FORMAT_B8G8R8A8_USCALED,
eB8G8R8A8Sscaled = VK_FORMAT_B8G8R8A8_SSCALED,
eB8G8R8A8Uint = VK_FORMAT_B8G8R8A8_UINT,
eB8G8R8A8Sint = VK_FORMAT_B8G8R8A8_SINT,
eB8G8R8A8Srgb = VK_FORMAT_B8G8R8A8_SRGB,
eA8B8G8R8UnormPack32 = VK_FORMAT_A8B8G8R8_UNORM_PACK32,
eA8B8G8R8SnormPack32 = VK_FORMAT_A8B8G8R8_SNORM_PACK32,
eA8B8G8R8UscaledPack32 = VK_FORMAT_A8B8G8R8_USCALED_PACK32,
eA8B8G8R8SscaledPack32 = VK_FORMAT_A8B8G8R8_SSCALED_PACK32,
eA8B8G8R8UintPack32 = VK_FORMAT_A8B8G8R8_UINT_PACK32,
eA8B8G8R8SintPack32 = VK_FORMAT_A8B8G8R8_SINT_PACK32,
eA8B8G8R8SrgbPack32 = VK_FORMAT_A8B8G8R8_SRGB_PACK32,
eA2R10G10B10UnormPack32 = VK_FORMAT_A2R10G10B10_UNORM_PACK32,
eA2R10G10B10SnormPack32 = VK_FORMAT_A2R10G10B10_SNORM_PACK32,
eA2R10G10B10UscaledPack32 = VK_FORMAT_A2R10G10B10_USCALED_PACK32,
eA2R10G10B10SscaledPack32 = VK_FORMAT_A2R10G10B10_SSCALED_PACK32,
eA2R10G10B10UintPack32 = VK_FORMAT_A2R10G10B10_UINT_PACK32,
eA2R10G10B10SintPack32 = VK_FORMAT_A2R10G10B10_SINT_PACK32,
eA2B10G10R10UnormPack32 = VK_FORMAT_A2B10G10R10_UNORM_PACK32,
eA2B10G10R10SnormPack32 = VK_FORMAT_A2B10G10R10_SNORM_PACK32,
eA2B10G10R10UscaledPack32 = VK_FORMAT_A2B10G10R10_USCALED_PACK32,
eA2B10G10R10SscaledPack32 = VK_FORMAT_A2B10G10R10_SSCALED_PACK32,
eA2B10G10R10UintPack32 = VK_FORMAT_A2B10G10R10_UINT_PACK32,
eA2B10G10R10SintPack32 = VK_FORMAT_A2B10G10R10_SINT_PACK32,
eR16Unorm = VK_FORMAT_R16_UNORM,
eR16Snorm = VK_FORMAT_R16_SNORM,
eR16Uscaled = VK_FORMAT_R16_USCALED,
eR16Sscaled = VK_FORMAT_R16_SSCALED,
eR16Uint = VK_FORMAT_R16_UINT,
eR16Sint = VK_FORMAT_R16_SINT,
eR16Sfloat = VK_FORMAT_R16_SFLOAT,
eR16G16Unorm = VK_FORMAT_R16G16_UNORM,
eR16G16Snorm = VK_FORMAT_R16G16_SNORM,
eR16G16Uscaled = VK_FORMAT_R16G16_USCALED,
eR16G16Sscaled = VK_FORMAT_R16G16_SSCALED,
eR16G16Uint = VK_FORMAT_R16G16_UINT,
eR16G16Sint = VK_FORMAT_R16G16_SINT,
eR16G16Sfloat = VK_FORMAT_R16G16_SFLOAT,
eR16G16B16Unorm = VK_FORMAT_R16G16B16_UNORM,
eR16G16B16Snorm = VK_FORMAT_R16G16B16_SNORM,
eR16G16B16Uscaled = VK_FORMAT_R16G16B16_USCALED,
eR16G16B16Sscaled = VK_FORMAT_R16G16B16_SSCALED,
eR16G16B16Uint = VK_FORMAT_R16G16B16_UINT,
eR16G16B16Sint = VK_FORMAT_R16G16B16_SINT,
eR16G16B16Sfloat = VK_FORMAT_R16G16B16_SFLOAT,
eR16G16B16A16Unorm = VK_FORMAT_R16G16B16A16_UNORM,
eR16G16B16A16Snorm = VK_FORMAT_R16G16B16A16_SNORM,
eR16G16B16A16Uscaled = VK_FORMAT_R16G16B16A16_USCALED,
eR16G16B16A16Sscaled = VK_FORMAT_R16G16B16A16_SSCALED,
eR16G16B16A16Uint = VK_FORMAT_R16G16B16A16_UINT,
eR16G16B16A16Sint = VK_FORMAT_R16G16B16A16_SINT,
eR16G16B16A16Sfloat = VK_FORMAT_R16G16B16A16_SFLOAT,
eR32Uint = VK_FORMAT_R32_UINT,
eR32Sint = VK_FORMAT_R32_SINT,
eR32Sfloat = VK_FORMAT_R32_SFLOAT,
eR32G32Uint = VK_FORMAT_R32G32_UINT,
eR32G32Sint = VK_FORMAT_R32G32_SINT,
eR32G32Sfloat = VK_FORMAT_R32G32_SFLOAT,
eR32G32B32Uint = VK_FORMAT_R32G32B32_UINT,
eR32G32B32Sint = VK_FORMAT_R32G32B32_SINT,
eR32G32B32Sfloat = VK_FORMAT_R32G32B32_SFLOAT,
eR32G32B32A32Uint = VK_FORMAT_R32G32B32A32_UINT,
eR32G32B32A32Sint = VK_FORMAT_R32G32B32A32_SINT,
eR32G32B32A32Sfloat = VK_FORMAT_R32G32B32A32_SFLOAT,
eR64Uint = VK_FORMAT_R64_UINT,
eR64Sint = VK_FORMAT_R64_SINT,
eR64Sfloat = VK_FORMAT_R64_SFLOAT,
eR64G64Uint = VK_FORMAT_R64G64_UINT,
eR64G64Sint = VK_FORMAT_R64G64_SINT,
eR64G64Sfloat = VK_FORMAT_R64G64_SFLOAT,
eR64G64B64Uint = VK_FORMAT_R64G64B64_UINT,
eR64G64B64Sint = VK_FORMAT_R64G64B64_SINT,
eR64G64B64Sfloat = VK_FORMAT_R64G64B64_SFLOAT,
eR64G64B64A64Uint = VK_FORMAT_R64G64B64A64_UINT,
eR64G64B64A64Sint = VK_FORMAT_R64G64B64A64_SINT,
eR64G64B64A64Sfloat = VK_FORMAT_R64G64B64A64_SFLOAT,
eB10G11R11UfloatPack32 = VK_FORMAT_B10G11R11_UFLOAT_PACK32,
eE5B9G9R9UfloatPack32 = VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
eD16Unorm = VK_FORMAT_D16_UNORM,
eX8D24UnormPack32 = VK_FORMAT_X8_D24_UNORM_PACK32,
eD32Sfloat = VK_FORMAT_D32_SFLOAT,
eS8Uint = VK_FORMAT_S8_UINT,
eD16UnormS8Uint = VK_FORMAT_D16_UNORM_S8_UINT,
eD24UnormS8Uint = VK_FORMAT_D24_UNORM_S8_UINT,
eD32SfloatS8Uint = VK_FORMAT_D32_SFLOAT_S8_UINT,
eBc1RgbUnormBlock = VK_FORMAT_BC1_RGB_UNORM_BLOCK,
eBc1RgbSrgbBlock = VK_FORMAT_BC1_RGB_SRGB_BLOCK,
eBc1RgbaUnormBlock = VK_FORMAT_BC1_RGBA_UNORM_BLOCK,
eBc1RgbaSrgbBlock = VK_FORMAT_BC1_RGBA_SRGB_BLOCK,
eBc2UnormBlock = VK_FORMAT_BC2_UNORM_BLOCK,
eBc2SrgbBlock = VK_FORMAT_BC2_SRGB_BLOCK,
eBc3UnormBlock = VK_FORMAT_BC3_UNORM_BLOCK,
eBc3SrgbBlock = VK_FORMAT_BC3_SRGB_BLOCK,
eBc4UnormBlock = VK_FORMAT_BC4_UNORM_BLOCK,
eBc4SnormBlock = VK_FORMAT_BC4_SNORM_BLOCK,
eBc5UnormBlock = VK_FORMAT_BC5_UNORM_BLOCK,
eBc5SnormBlock = VK_FORMAT_BC5_SNORM_BLOCK,
eBc6HUfloatBlock = VK_FORMAT_BC6H_UFLOAT_BLOCK,
eBc6HSfloatBlock = VK_FORMAT_BC6H_SFLOAT_BLOCK,
eBc7UnormBlock = VK_FORMAT_BC7_UNORM_BLOCK,
eBc7SrgbBlock = VK_FORMAT_BC7_SRGB_BLOCK,
eEtc2R8G8B8UnormBlock = VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK,
eEtc2R8G8B8SrgbBlock = VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,
eEtc2R8G8B8A1UnormBlock = VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK,
eEtc2R8G8B8A1SrgbBlock = VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK,
eEtc2R8G8B8A8UnormBlock = VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK,
eEtc2R8G8B8A8SrgbBlock = VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,
eEacR11UnormBlock = VK_FORMAT_EAC_R11_UNORM_BLOCK,
eEacR11SnormBlock = VK_FORMAT_EAC_R11_SNORM_BLOCK,
eEacR11G11UnormBlock = VK_FORMAT_EAC_R11G11_UNORM_BLOCK,
eEacR11G11SnormBlock = VK_FORMAT_EAC_R11G11_SNORM_BLOCK,
eAstc4x4UnormBlock = VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
eAstc4x4SrgbBlock = VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
eAstc5x4UnormBlock = VK_FORMAT_ASTC_5x4_UNORM_BLOCK,
eAstc5x4SrgbBlock = VK_FORMAT_ASTC_5x4_SRGB_BLOCK,
eAstc5x5UnormBlock = VK_FORMAT_ASTC_5x5_UNORM_BLOCK,
eAstc5x5SrgbBlock = VK_FORMAT_ASTC_5x5_SRGB_BLOCK,
eAstc6x5UnormBlock = VK_FORMAT_ASTC_6x5_UNORM_BLOCK,
eAstc6x5SrgbBlock = VK_FORMAT_ASTC_6x5_SRGB_BLOCK,
eAstc6x6UnormBlock = VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
eAstc6x6SrgbBlock = VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
eAstc8x5UnormBlock = VK_FORMAT_ASTC_8x5_UNORM_BLOCK,
eAstc8x5SrgbBlock = VK_FORMAT_ASTC_8x5_SRGB_BLOCK,
eAstc8x6UnormBlock = VK_FORMAT_ASTC_8x6_UNORM_BLOCK,
eAstc8x6SrgbBlock = VK_FORMAT_ASTC_8x6_SRGB_BLOCK,
eAstc8x8UnormBlock = VK_FORMAT_ASTC_8x8_UNORM_BLOCK,
eAstc8x8SrgbBlock = VK_FORMAT_ASTC_8x8_SRGB_BLOCK,
eAstc10x5UnormBlock = VK_FORMAT_ASTC_10x5_UNORM_BLOCK,
eAstc10x5SrgbBlock = VK_FORMAT_ASTC_10x5_SRGB_BLOCK,
eAstc10x6UnormBlock = VK_FORMAT_ASTC_10x6_UNORM_BLOCK,
eAstc10x6SrgbBlock = VK_FORMAT_ASTC_10x6_SRGB_BLOCK,
eAstc10x8UnormBlock = VK_FORMAT_ASTC_10x8_UNORM_BLOCK,
eAstc10x8SrgbBlock = VK_FORMAT_ASTC_10x8_SRGB_BLOCK,
eAstc10x10UnormBlock = VK_FORMAT_ASTC_10x10_UNORM_BLOCK,
eAstc10x10SrgbBlock = VK_FORMAT_ASTC_10x10_SRGB_BLOCK,
eAstc12x10UnormBlock = VK_FORMAT_ASTC_12x10_UNORM_BLOCK,
eAstc12x10SrgbBlock = VK_FORMAT_ASTC_12x10_SRGB_BLOCK,
eAstc12x12UnormBlock = VK_FORMAT_ASTC_12x12_UNORM_BLOCK,
eAstc12x12SrgbBlock = VK_FORMAT_ASTC_12x12_SRGB_BLOCK,
eG8B8G8R8422Unorm = VK_FORMAT_G8B8G8R8_422_UNORM,
eB8G8R8G8422Unorm = VK_FORMAT_B8G8R8G8_422_UNORM,
eG8B8R83Plane420Unorm = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM,
eG8B8R82Plane420Unorm = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM,
eG8B8R83Plane422Unorm = VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM,
eG8B8R82Plane422Unorm = VK_FORMAT_G8_B8R8_2PLANE_422_UNORM,
eG8B8R83Plane444Unorm = VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM,
eR10X6UnormPack16 = VK_FORMAT_R10X6_UNORM_PACK16,
eR10X6G10X6Unorm2Pack16 = VK_FORMAT_R10X6G10X6_UNORM_2PACK16,
eR10X6G10X6B10X6A10X6Unorm4Pack16 = VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
eG10X6B10X6G10X6R10X6422Unorm4Pack16 = VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16,
eB10X6G10X6R10X6G10X6422Unorm4Pack16 = VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16,
eG10X6B10X6R10X63Plane420Unorm3Pack16 = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16,
eG10X6B10X6R10X62Plane420Unorm3Pack16 = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
eG10X6B10X6R10X63Plane422Unorm3Pack16 = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16,
eG10X6B10X6R10X62Plane422Unorm3Pack16 = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16,
eG10X6B10X6R10X63Plane444Unorm3Pack16 = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16,
eR12X4UnormPack16 = VK_FORMAT_R12X4_UNORM_PACK16,
eR12X4G12X4Unorm2Pack16 = VK_FORMAT_R12X4G12X4_UNORM_2PACK16,
eR12X4G12X4B12X4A12X4Unorm4Pack16 = VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16,
eG12X4B12X4G12X4R12X4422Unorm4Pack16 = VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16,
eB12X4G12X4R12X4G12X4422Unorm4Pack16 = VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16,
eG12X4B12X4R12X43Plane420Unorm3Pack16 = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16,
eG12X4B12X4R12X42Plane420Unorm3Pack16 = VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16,
eG12X4B12X4R12X43Plane422Unorm3Pack16 = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16,
eG12X4B12X4R12X42Plane422Unorm3Pack16 = VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16,
eG12X4B12X4R12X43Plane444Unorm3Pack16 = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16,
eG16B16G16R16422Unorm = VK_FORMAT_G16B16G16R16_422_UNORM,
eB16G16R16G16422Unorm = VK_FORMAT_B16G16R16G16_422_UNORM,
eG16B16R163Plane420Unorm = VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM,
eG16B16R162Plane420Unorm = VK_FORMAT_G16_B16R16_2PLANE_420_UNORM,
eG16B16R163Plane422Unorm = VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM,
eG16B16R162Plane422Unorm = VK_FORMAT_G16_B16R16_2PLANE_422_UNORM,
eG16B16R163Plane444Unorm = VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM,
ePvrtc12BppUnormBlockIMG = VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG,
ePvrtc14BppUnormBlockIMG = VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG,
ePvrtc22BppUnormBlockIMG = VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG,
ePvrtc24BppUnormBlockIMG = VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG,
ePvrtc12BppSrgbBlockIMG = VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG,
ePvrtc14BppSrgbBlockIMG = VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG,
ePvrtc22BppSrgbBlockIMG = VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG,
ePvrtc24BppSrgbBlockIMG = VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG,
eAstc4x4SfloatBlockEXT = VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT,
eAstc5x4SfloatBlockEXT = VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT,
eAstc5x5SfloatBlockEXT = VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT,
eAstc6x5SfloatBlockEXT = VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT,
eAstc6x6SfloatBlockEXT = VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT,
eAstc8x5SfloatBlockEXT = VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT,
eAstc8x6SfloatBlockEXT = VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT,
eAstc8x8SfloatBlockEXT = VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT,
eAstc10x5SfloatBlockEXT = VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT,
eAstc10x6SfloatBlockEXT = VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT,
eAstc10x8SfloatBlockEXT = VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT,
eAstc10x10SfloatBlockEXT = VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT,
eAstc12x10SfloatBlockEXT = VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT,
eAstc12x12SfloatBlockEXT = VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT,
eB10X6G10X6R10X6G10X6422Unorm4Pack16KHR = VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16_KHR,
eB12X4G12X4R12X4G12X4422Unorm4Pack16KHR = VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16_KHR,
eB16G16R16G16422UnormKHR = VK_FORMAT_B16G16R16G16_422_UNORM_KHR,
eB8G8R8G8422UnormKHR = VK_FORMAT_B8G8R8G8_422_UNORM_KHR,
eG10X6B10X6G10X6R10X6422Unorm4Pack16KHR = VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16_KHR,
eG10X6B10X6R10X62Plane420Unorm3Pack16KHR = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16_KHR,
eG10X6B10X6R10X62Plane422Unorm3Pack16KHR = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16_KHR,
eG10X6B10X6R10X63Plane420Unorm3Pack16KHR = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16_KHR,
eG10X6B10X6R10X63Plane422Unorm3Pack16KHR = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16_KHR,
eG10X6B10X6R10X63Plane444Unorm3Pack16KHR = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16_KHR,
eG12X4B12X4G12X4R12X4422Unorm4Pack16KHR = VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16_KHR,
eG12X4B12X4R12X42Plane420Unorm3Pack16KHR = VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16_KHR,
eG12X4B12X4R12X42Plane422Unorm3Pack16KHR = VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16_KHR,
eG12X4B12X4R12X43Plane420Unorm3Pack16KHR = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16_KHR,
eG12X4B12X4R12X43Plane422Unorm3Pack16KHR = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16_KHR,
eG12X4B12X4R12X43Plane444Unorm3Pack16KHR = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16_KHR,
eG16B16G16R16422UnormKHR = VK_FORMAT_G16B16G16R16_422_UNORM_KHR,
eG16B16R162Plane420UnormKHR = VK_FORMAT_G16_B16R16_2PLANE_420_UNORM_KHR,
eG16B16R162Plane422UnormKHR = VK_FORMAT_G16_B16R16_2PLANE_422_UNORM_KHR,
eG16B16R163Plane420UnormKHR = VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM_KHR,
eG16B16R163Plane422UnormKHR = VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM_KHR,
eG16B16R163Plane444UnormKHR = VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM_KHR,
eG8B8G8R8422UnormKHR = VK_FORMAT_G8B8G8R8_422_UNORM_KHR,
eG8B8R82Plane420UnormKHR = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR,
eG8B8R82Plane422UnormKHR = VK_FORMAT_G8_B8R8_2PLANE_422_UNORM_KHR,
eG8B8R83Plane420UnormKHR = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM_KHR,
eG8B8R83Plane422UnormKHR = VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM_KHR,
eG8B8R83Plane444UnormKHR = VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM_KHR,
eR10X6G10X6B10X6A10X6Unorm4Pack16KHR = VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16_KHR,
eR10X6G10X6Unorm2Pack16KHR = VK_FORMAT_R10X6G10X6_UNORM_2PACK16_KHR,
eR10X6UnormPack16KHR = VK_FORMAT_R10X6_UNORM_PACK16_KHR,
eR12X4G12X4B12X4A12X4Unorm4Pack16KHR = VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16_KHR,
eR12X4G12X4Unorm2Pack16KHR = VK_FORMAT_R12X4G12X4_UNORM_2PACK16_KHR,
eR12X4UnormPack16KHR = VK_FORMAT_R12X4_UNORM_PACK16_KHR
};
// return the texel block size of a format
uint32_t format_to_texel_block_size(vuk::Format) noexcept;
// return the 3D texel block extent of a format
Extent3D format_to_texel_block_extent(vuk::Format) noexcept;
// compute the byte size of an image with given format and extent
uint32_t compute_image_size(vuk::Format, vuk::Extent3D) noexcept;
// get name of format
std::string_view format_to_sv(Format format) noexcept;
// true if format performs automatic sRGB conversion
bool is_format_srgb(vuk::Format) noexcept;
// get the unorm equivalent of the srgb format (returns vuk::Format::Undefined if the format doesn't exist)
vuk::Format unorm_to_srgb(vuk::Format) noexcept;
// get the srgb equivalent of the unorm format (returns vuk::Format::Undefined if the format doesn't exist)
vuk::Format srgb_to_unorm(vuk::Format) noexcept;
enum class IndexType {
eUint16 = VK_INDEX_TYPE_UINT16,
eUint32 = VK_INDEX_TYPE_UINT32,
eNoneKHR = VK_INDEX_TYPE_NONE_KHR,
eUint8EXT = VK_INDEX_TYPE_UINT8_EXT,
eNoneNV = VK_INDEX_TYPE_NONE_NV
};
template<typename BitType>
class Flags {
public:
using MaskType = typename std::underlying_type_t<BitType>;
// constructors
constexpr Flags() noexcept : m_mask(0) {}
constexpr Flags(BitType bit) noexcept : m_mask(static_cast<MaskType>(bit)) {}
constexpr Flags(Flags<BitType> const& rhs) noexcept : m_mask(rhs.m_mask) {}
constexpr explicit Flags(MaskType flags) noexcept : m_mask(flags) {}
constexpr bool operator<(Flags<BitType> const& rhs) const noexcept {
return m_mask < rhs.m_mask;
}
constexpr bool operator<=(Flags<BitType> const& rhs) const noexcept {
return m_mask <= rhs.m_mask;
}
constexpr bool operator>(Flags<BitType> const& rhs) const noexcept {
return m_mask > rhs.m_mask;
}
constexpr bool operator>=(Flags<BitType> const& rhs) const noexcept {
return m_mask >= rhs.m_mask;
}
constexpr bool operator==(Flags<BitType> const& rhs) const noexcept {
return m_mask == rhs.m_mask;
}
constexpr bool operator!=(Flags<BitType> const& rhs) const noexcept {
return m_mask != rhs.m_mask;
}
// logical operator
constexpr bool operator!() const noexcept {
return !m_mask;
}
// assignment operators
constexpr Flags<BitType>& operator=(Flags<BitType> const& rhs) noexcept {
m_mask = rhs.m_mask;
return *this;
}
constexpr Flags<BitType>& operator|=(Flags<BitType> const& rhs) noexcept {
m_mask |= rhs.m_mask;
return *this;
}
constexpr Flags<BitType>& operator&=(Flags<BitType> const& rhs) noexcept {
m_mask &= rhs.m_mask;
return *this;
}
constexpr Flags<BitType>& operator^=(Flags<BitType> const& rhs) noexcept {
m_mask ^= rhs.m_mask;
return *this;
}
// cast operators
explicit constexpr operator bool() const noexcept {
return !!m_mask;
}
explicit constexpr operator MaskType() const noexcept {
return m_mask;
}
// bitwise operators
friend constexpr Flags<BitType> operator&(Flags<BitType> const& lhs, Flags<BitType> const& rhs) noexcept {
return Flags<BitType>(lhs.m_mask & rhs.m_mask);
}
friend constexpr Flags<BitType> operator|(Flags<BitType> const& lhs, Flags<BitType> const& rhs) noexcept {
return Flags<BitType>(lhs.m_mask | rhs.m_mask);
}
friend constexpr Flags<BitType> operator^(Flags<BitType> const& lhs, Flags<BitType> const& rhs) noexcept {
return Flags<BitType>(lhs.m_mask ^ rhs.m_mask);
}
friend constexpr Flags<BitType> operator&(Flags<BitType> const& lhs, BitType const& rhs) noexcept {
return Flags<BitType>(lhs.m_mask & (std::underlying_type_t<BitType>)rhs);
}
friend constexpr Flags<BitType> operator|(Flags<BitType> const& lhs, BitType const& rhs) noexcept {
return Flags<BitType>(lhs.m_mask | (std::underlying_type_t<BitType>)rhs);
}
friend constexpr Flags<BitType> operator^(Flags<BitType> const& lhs, BitType const& rhs) noexcept {
return Flags<BitType>(lhs.m_mask ^ (std::underlying_type_t<BitType>)rhs);
}
MaskType m_mask;
};
enum class ShaderStageFlagBits : VkShaderStageFlags {
eVertex = VK_SHADER_STAGE_VERTEX_BIT,
eTessellationControl = VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
eTessellationEvaluation = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
eGeometry = VK_SHADER_STAGE_GEOMETRY_BIT,
eFragment = VK_SHADER_STAGE_FRAGMENT_BIT,
eCompute = VK_SHADER_STAGE_COMPUTE_BIT,
eAllGraphics = VK_SHADER_STAGE_ALL_GRAPHICS,
eAll = VK_SHADER_STAGE_ALL,
eRaygenKHR = VK_SHADER_STAGE_RAYGEN_BIT_KHR,
eAnyHitKHR = VK_SHADER_STAGE_ANY_HIT_BIT_KHR,
eClosestHitKHR = VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR,
eMissKHR = VK_SHADER_STAGE_MISS_BIT_KHR,
eIntersectionKHR = VK_SHADER_STAGE_INTERSECTION_BIT_KHR,
eCallableKHR = VK_SHADER_STAGE_CALLABLE_BIT_KHR,
eTaskNV = VK_SHADER_STAGE_TASK_BIT_NV,
eMeshNV = VK_SHADER_STAGE_MESH_BIT_NV,
eAnyHitNV = VK_SHADER_STAGE_ANY_HIT_BIT_NV,
eCallableNV = VK_SHADER_STAGE_CALLABLE_BIT_NV,
eClosestHitNV = VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV,
eIntersectionNV = VK_SHADER_STAGE_INTERSECTION_BIT_NV,
eMissNV = VK_SHADER_STAGE_MISS_BIT_NV,
eRaygenNV = VK_SHADER_STAGE_RAYGEN_BIT_NV
};
using ShaderStageFlags = Flags<ShaderStageFlagBits>;
inline constexpr ShaderStageFlags operator|(ShaderStageFlagBits bit0, ShaderStageFlagBits bit1) noexcept {
return ShaderStageFlags(bit0) | bit1;
}
inline constexpr ShaderStageFlags operator&(ShaderStageFlagBits bit0, ShaderStageFlagBits bit1) noexcept {
return ShaderStageFlags(bit0) & bit1;
}
inline constexpr ShaderStageFlags operator^(ShaderStageFlagBits bit0, ShaderStageFlagBits bit1) noexcept {
return ShaderStageFlags(bit0) ^ bit1;
}
enum class PipelineStageFlagBits : uint32_t {
eNone = VK_PIPELINE_STAGE_NONE,
eTopOfPipe = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
eDrawIndirect = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT,
eVertexInput = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
eVertexShader = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
eTessellationControlShader = VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT,
eTessellationEvaluationShader = VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT,
eGeometryShader = VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT,
eFragmentShader = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
eEarlyFragmentTests = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
eLateFragmentTests = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
eColorAttachmentOutput = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
eComputeShader = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
eTransfer = VK_PIPELINE_STAGE_TRANSFER_BIT,
eBottomOfPipe = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
eHost = VK_PIPELINE_STAGE_HOST_BIT,
eAllGraphics = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
eAllCommands = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
eTransformFeedbackEXT = VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT,
eConditionalRenderingEXT = VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT,
eRayTracingShaderKHR = VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR,
eAccelerationStructureBuildKHR = VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
eShadingRateImageNV = VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV,
eTaskShaderNV = VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV,
eMeshShaderNV = VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV,
eFragmentDensityProcessEXT = VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT,
eCommandPreprocessNV = VK_PIPELINE_STAGE_COMMAND_PREPROCESS_BIT_NV,
eAccelerationStructureBuildNV = VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV,
eRayTracingShaderNV = VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV
};
using PipelineStageFlags = Flags<PipelineStageFlagBits>;
inline constexpr PipelineStageFlags operator|(PipelineStageFlagBits bit0, PipelineStageFlagBits bit1) noexcept {
return PipelineStageFlags(bit0) | bit1;
}
inline constexpr PipelineStageFlags operator&(PipelineStageFlagBits bit0, PipelineStageFlagBits bit1) noexcept {
return PipelineStageFlags(bit0) & bit1;
}
inline constexpr PipelineStageFlags operator^(PipelineStageFlagBits bit0, PipelineStageFlagBits bit1) noexcept {
return PipelineStageFlags(bit0) ^ bit1;
}
enum class AccessFlagBits : VkAccessFlags {
eIndirectCommandRead = VK_ACCESS_INDIRECT_COMMAND_READ_BIT,
eIndexRead = VK_ACCESS_INDEX_READ_BIT,
eVertexAttributeRead = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT,
eUniformRead = VK_ACCESS_UNIFORM_READ_BIT,
eInputAttachmentRead = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT,
eShaderRead = VK_ACCESS_SHADER_READ_BIT,
eShaderWrite = VK_ACCESS_SHADER_WRITE_BIT,
eColorAttachmentRead = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT,
eColorAttachmentWrite = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
eDepthStencilAttachmentRead = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT,
eDepthStencilAttachmentWrite = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
eTransferRead = VK_ACCESS_TRANSFER_READ_BIT,
eTransferWrite = VK_ACCESS_TRANSFER_WRITE_BIT,
eHostRead = VK_ACCESS_HOST_READ_BIT,
eHostWrite = VK_ACCESS_HOST_WRITE_BIT,
eMemoryRead = VK_ACCESS_MEMORY_READ_BIT,
eMemoryWrite = VK_ACCESS_MEMORY_WRITE_BIT,
eTransformFeedbackWriteEXT = VK_ACCESS_TRANSFORM_FEEDBACK_WRITE_BIT_EXT,
eTransformFeedbackCounterReadEXT = VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT,
eTransformFeedbackCounterWriteEXT = VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT,
eConditionalRenderingReadEXT = VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT,
eColorAttachmentReadNoncoherentEXT = VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT,
eAccelerationStructureReadKHR = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR,
eAccelerationStructureWriteKHR = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR,
eShadingRateImageReadNV = VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV,
eFragmentDensityMapReadEXT = VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT,
eCommandPreprocessReadNV = VK_ACCESS_COMMAND_PREPROCESS_READ_BIT_NV,
eCommandPreprocessWriteNV = VK_ACCESS_COMMAND_PREPROCESS_WRITE_BIT_NV,
eAccelerationStructureReadNV = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV,
eAccelerationStructureWriteNV = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV
};
using AccessFlags = Flags<AccessFlagBits>;
inline constexpr AccessFlags operator|(AccessFlagBits bit0, AccessFlagBits bit1) noexcept {
return AccessFlags(bit0) | bit1;
}
inline constexpr AccessFlags operator&(AccessFlagBits bit0, AccessFlagBits bit1) noexcept {
return AccessFlags(bit0) & bit1;
}
inline constexpr AccessFlags operator^(AccessFlagBits bit0, AccessFlagBits bit1) noexcept {
return AccessFlags(bit0) ^ bit1;
}
enum class MemoryUsage {
eGPUonly = 1 /*VMA_MEMORY_USAGE_GPU_ONLY*/,
eCPUtoGPU = 3 /*VMA_MEMORY_USAGE_CPU_TO_GPU*/,
eCPUonly = 2 /*VMA_MEMORY_USAGE_CPU_ONLY*/,
eGPUtoCPU = 4 /*VMA_MEMORY_USAGE_GPU_TO_CPU*/
};
using Bool32 = uint32_t;
struct ClearColor {
constexpr ClearColor(uint32_t r, uint32_t g, uint32_t b, uint32_t a) noexcept {
ccv.uint32[0] = r;
ccv.uint32[1] = g;
ccv.uint32[2] = b;
ccv.uint32[3] = a;
}
constexpr ClearColor(int32_t r, int32_t g, int32_t b, int32_t a) noexcept {
ccv.int32[0] = r;
ccv.int32[1] = g;
ccv.int32[2] = b;
ccv.int32[3] = a;
}
constexpr ClearColor(float r, float g, float b, float a) noexcept {
ccv.float32[0] = r;
ccv.float32[1] = g;
ccv.float32[2] = b;
ccv.float32[3] = a;
}
VkClearColorValue ccv;
};
template<class T>
static constexpr ClearColor White = { 1, 1, 1, 1 };
template<class T>
static constexpr ClearColor Black = { 0, 0, 0, 1 };
template<class T>
static constexpr ClearColor Transparent = { 0, 0, 0, 0 };
template<>
inline constexpr ClearColor White<float> = { 1.f, 1.f, 1.f, 1.f };
template<>
inline constexpr ClearColor White<unsigned> = { 1u, 1u, 1u, 1u };
template<>
inline constexpr ClearColor White<signed> = { 1, 1, 1, 1 };
template<>
inline constexpr ClearColor Black<float> = { 0.f, 0.f, 0.f, 1.f };
template<>
inline constexpr ClearColor Black<unsigned> = { 0u, 0u, 0u, 1u };
template<>
inline constexpr ClearColor Black<signed> = { 0, 0, 0, 1 };
template<>
inline constexpr ClearColor Transparent<float> = { 0.f, 0.f, 0.f, 0.f };
template<>
inline constexpr ClearColor Transparent<unsigned> = { 0u, 0u, 0u, 0u };
template<>
inline constexpr ClearColor Transparent<signed> = { 0, 0, 0, 0 };
struct ClearDepthStencil {
constexpr ClearDepthStencil(float depth, uint32_t stencil) noexcept : cdsv{ depth, stencil } {}
VkClearDepthStencilValue cdsv;
};
struct ClearDepth {
constexpr ClearDepth(float depth) noexcept : depth{ depth } {}
float depth;
operator ClearDepthStencil() {
return ClearDepthStencil(depth, 0);
}
};
struct ClearStencil {
constexpr ClearStencil(uint32_t stencil) noexcept : stencil{ stencil } {}
uint32_t stencil;
};
constexpr inline ClearDepthStencil operator|(ClearDepth d, ClearStencil s) noexcept {
return ClearDepthStencil(d.depth, s.stencil);
}
static constexpr ClearDepth DepthOne = { 1.f };
static constexpr ClearDepth DepthZero = { 0.f };
struct Clear {
constexpr Clear() = default;
constexpr Clear(ClearColor cc) noexcept : is_color(true) {
c.color = cc.ccv;
}
constexpr Clear(ClearDepth cc) noexcept : is_color(false) {
c.depthStencil.depth = cc.depth;
}
constexpr Clear(ClearDepthStencil cc) noexcept : is_color(false) {
c.depthStencil = cc.cdsv;
}
constexpr Clear(const Clear& other) noexcept {
if (other.is_color) {
c.color = other.c.color;
} else {
c.depthStencil = other.c.depthStencil;
}
is_color = other.is_color;
}
bool is_color;
VkClearValue c;
};
enum Access : uint64_t {
eNone = 1ULL << 0, // as initial use: resource available without synchronization, as final use: resource does not need synchronizing
eInfer = 1ULL << 1, // as final use only: this use must be overwritten/inferred before compiling (internal)
eConsume = 1ULL << 2, // must be overwritten before compiling: this access consumes this name (internal)
eConverge = 1ULL << 3, // converge previous uses (internal)
eManual = 1ULL << 4, // provided explictly (internal)
eClear = 1ULL << 5, // general clearing
eTransferClear = 1ULL << 6, // vkCmdClearXXX
eColorWrite = 1ULL << 7,
eColorRead = 1ULL << 8,
eColorRW = eColorWrite | eColorRead,
eColorResolveRead = 1ULL << 10, // special op to mark render pass resolve read
eColorResolveWrite = 1ULL << 11, // special op to mark render pass resolve write
eDepthStencilRead = 1ULL << 12,
eDepthStencilWrite = 1ULL << 13,
eDepthStencilRW = eDepthStencilWrite | eDepthStencilRead,
eInputRead = 1ULL << 14,
eVertexSampled = 1ULL << 15,
eVertexRead = 1ULL << 16,
eAttributeRead = 1ULL << 17,
eIndexRead = 1ULL << 18,
eIndirectRead = 1ULL << 19,
eFragmentSampled = 1ULL << 20,
eFragmentRead = 1ULL << 21,
eFragmentWrite = 1ULL << 22, // written using image store
eFragmentRW = eFragmentRead | eFragmentWrite,
eTransferRead = 1ULL << 23,
eTransferWrite = 1ULL << 24,
eTransferRW = eTransferRead | eTransferWrite,
eComputeRead = 1ULL << 25,
eComputeWrite = 1ULL << 26,
eComputeRW = eComputeRead | eComputeWrite,
eComputeSampled = 1ULL << 27,
eRayTracingRead = 1ULL << 28,
eRayTracingWrite = 1ULL << 29,
eRayTracingRW = eRayTracingRead | eRayTracingWrite,
eRayTracingSampled = 1ULL << 30,
eAccelerationStructureBuildRead = 1ULL << 31,
eAccelerationStructureBuildWrite = 1ULL << 32,
eAccelerationStructureBuildRW = eAccelerationStructureBuildRead | eAccelerationStructureBuildWrite,
eHostRead = 1ULL << 33,
eHostWrite = 1ULL << 34,
eHostRW = eHostRead | eHostWrite,
eMemoryRead = 1ULL << 35,
eMemoryWrite = 1ULL << 36,
eMemoryRW = eMemoryRead | eMemoryWrite,
ePresent = 1ULL << 37
};
inline constexpr Access operator|(Access bit0, Access bit1) noexcept {
return Access((uint64_t)bit0 | (uint64_t)bit1);
}
enum class DomainFlagBits {
eNone = 0,
eHost = 1 << 0,
eGraphicsQueue = 1 << 1,
eComputeQueue = 1 << 2,
eTransferQueue = 1 << 3,
eGraphicsOperation = 1 << 4,
eComputeOperation = 1 << 5,
eTransferOperation = 1 << 6,
eQueueMask = 0b1110,
eOpMask = 0b1110000,
eGraphicsOnGraphics = eGraphicsQueue | eGraphicsOperation,
eComputeOnGraphics = eGraphicsQueue | eComputeOperation,
eTransferOnGraphics = eGraphicsQueue | eTransferOperation,
eComputeOnCompute = eComputeQueue | eComputeOperation,
eTransferOnCompute = eComputeQueue | eComputeOperation,
eTransferOnTransfer = eTransferQueue | eTransferOperation,
eDevice = eGraphicsQueue | eComputeQueue | eTransferQueue,
eAny = eDevice | eHost
};
using DomainFlags = Flags<DomainFlagBits>;
inline constexpr DomainFlags operator|(DomainFlagBits bit0, DomainFlagBits bit1) noexcept {
return DomainFlags(bit0) | bit1;
}
inline constexpr DomainFlags operator&(DomainFlagBits bit0, DomainFlagBits bit1) noexcept {
return DomainFlags(bit0) & bit1;
}
inline constexpr DomainFlags operator^(DomainFlagBits bit0, DomainFlagBits bit1) noexcept {
return DomainFlags(bit0) ^ bit1;
}
// Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16.
// Use types like uint32_t, uint64_t as T.
// Source: VMA
template<typename T>
constexpr inline T align_up(T val, T align) noexcept {
return (val + align - 1) / align * align;
}
struct CommandPool {
VkCommandPool command_pool;
uint32_t queue_family_index;
constexpr bool operator==(const CommandPool& other) const noexcept {
return command_pool == other.command_pool;
}
};
struct CommandBufferAllocationCreateInfo {
VkCommandBufferLevel level;
CommandPool command_pool;
};
struct CommandBufferAllocation {
CommandBufferAllocation() = default;
CommandBufferAllocation(VkCommandBuffer command_buffer, CommandPool command_pool) noexcept : command_buffer(command_buffer), command_pool(command_pool) {}
VkCommandBuffer command_buffer;
CommandPool command_pool;
operator VkCommandBuffer() noexcept {
return command_buffer;
}
};
/// @brief Control compilation options when compiling the rendergraph
struct RenderGraphCompileOptions {
};
enum class DescriptorSetStrategyFlagBits {
eDefault = 0, // implementation choice
/* storage */
ePerLayout = 1 << 1, // one DS pool per layout
eCommon = 1 << 2, // common pool per layout
// eCached = 1 << 3,
/* update - no flag: standard */
// eUpdateAfterBind = 1 << 4,
// ePushDescriptor = 1 << 5,
/* templating - no flag: no template */
// eWithTemplate = 1 << 7
};
using DescriptorSetStrategyFlags = Flags<DescriptorSetStrategyFlagBits>;
inline constexpr DescriptorSetStrategyFlags operator|(DescriptorSetStrategyFlagBits bit0, DescriptorSetStrategyFlagBits bit1) noexcept {
return DescriptorSetStrategyFlags(bit0) | bit1;
}
inline constexpr DescriptorSetStrategyFlags operator&(DescriptorSetStrategyFlagBits bit0, DescriptorSetStrategyFlagBits bit1) noexcept {
return DescriptorSetStrategyFlags(bit0) & bit1;
}
inline constexpr DescriptorSetStrategyFlags operator^(DescriptorSetStrategyFlagBits bit0, DescriptorSetStrategyFlagBits bit1) noexcept {
return DescriptorSetStrategyFlags(bit0) ^ bit1;
}
} // namespace vuk
namespace std {
template<class BitType>
struct hash<vuk::Flags<BitType>> {
size_t operator()(vuk::Flags<BitType> const& x) const noexcept {
return std::hash<typename vuk::Flags<BitType>::MaskType>()((typename vuk::Flags<BitType>::MaskType)x);
}
};
}; // namespace std
#undef MOV
<file_sep>#pragma once
#include "vuk/Allocator.hpp"
#include "vuk/resources/DeviceNestedResource.hpp"
#include "vuk/resources/DeviceVkResource.hpp"
#include <memory>
namespace vuk {
/// @brief Represents resources not tied to a frame, that are deallocated only when the resource is destroyed. Not thread-safe.
///
/// Allocations from this resource are deallocated into the upstream resource when the DeviceLinearResource is destroyed.
/// All resources allocated are automatically deallocated at recycle time - it is not necessary (but not an error) to deallocate them.
struct DeviceLinearResource : DeviceNestedResource {
DeviceLinearResource(DeviceResource& upstream);
~DeviceLinearResource();
DeviceLinearResource(DeviceLinearResource&&);
DeviceLinearResource& operator=(DeviceLinearResource&&);
Result<void, AllocateException> allocate_semaphores(std::span<VkSemaphore> dst, SourceLocationAtFrame loc) override;
void deallocate_semaphores(std::span<const VkSemaphore> src) override; // noop
Result<void, AllocateException> allocate_fences(std::span<VkFence> dst, SourceLocationAtFrame loc) override;
void deallocate_fences(std::span<const VkFence> src) override; // noop
Result<void, AllocateException> allocate_command_buffers(std::span<CommandBufferAllocation> dst,
std::span<const CommandBufferAllocationCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_command_buffers(std::span<const CommandBufferAllocation> src) override; // no-op, deallocated with pools
Result<void, AllocateException>
allocate_command_pools(std::span<CommandPool> dst, std::span<const VkCommandPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_command_pools(std::span<const CommandPool> dst) override; // no-op
// buffers are lockless
Result<void, AllocateException> allocate_buffers(std::span<Buffer> dst, std::span<const BufferCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_buffers(std::span<const Buffer> src) override; // no-op, linear
Result<void, AllocateException>
allocate_framebuffers(std::span<VkFramebuffer> dst, std::span<const FramebufferCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_framebuffers(std::span<const VkFramebuffer> src) override; // noop
Result<void, AllocateException> allocate_images(std::span<Image> dst, std::span<const ImageCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_images(std::span<const Image> src) override; // noop
Result<void, AllocateException>
allocate_image_views(std::span<ImageView> dst, std::span<const ImageViewCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_image_views(std::span<const ImageView> src) override; // noop
Result<void, AllocateException> allocate_persistent_descriptor_sets(std::span<PersistentDescriptorSet> dst,
std::span<const PersistentDescriptorSetCreateInfo> cis,
SourceLocationAtFrame loc) override;
void deallocate_persistent_descriptor_sets(std::span<const PersistentDescriptorSet> src) override; // noop
Result<void, AllocateException>
allocate_descriptor_sets_with_value(std::span<DescriptorSet> dst, std::span<const SetBinding> cis, SourceLocationAtFrame loc) override;
Result<void, AllocateException>
allocate_descriptor_sets(std::span<DescriptorSet> dst, std::span<const DescriptorSetLayoutAllocInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_descriptor_sets(std::span<const DescriptorSet> src) override;
Result<void, AllocateException>
allocate_timestamp_query_pools(std::span<TimestampQueryPool> dst, std::span<const VkQueryPoolCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_timestamp_query_pools(std::span<const TimestampQueryPool> src) override; // noop
Result<void, AllocateException>
allocate_timestamp_queries(std::span<TimestampQuery> dst, std::span<const TimestampQueryCreateInfo> cis, SourceLocationAtFrame loc) override;
void deallocate_timestamp_queries(std::span<const TimestampQuery> src) override; // noop
Result<void, AllocateException> allocate_timeline_semaphores(std::span<TimelineSemaphore> dst, SourceLocationAtFrame loc) override;
void deallocate_timeline_semaphores(std::span<const TimelineSemaphore> src) override; // noop
/// @brief Wait for the fences / timeline semaphores referencing this allocator
void wait();
/// @brief Release the resources of this resource into the upstream
void free();
/// @brief Retrieve the parent Context
/// @return the parent Context
Context& get_context() override {
return upstream->get_context();
}
private:
std::unique_ptr<struct DeviceLinearResourceImpl> impl;
friend struct DeviceLinearResourceImpl;
};
} // namespace vuk<file_sep>cmake_minimum_required(VERSION 3.7)
project(vuk-benchmarks)
FetchContent_Declare(
vk-bootstrap
GIT_REPOSITORY https://github.com/charles-lunarg/vk-bootstrap
GIT_TAG 8e61b2d81c3f5f84339735085ff5651f71bbe1e7
)
FetchContent_MakeAvailable(vk-bootstrap)
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
FetchContent_Declare(
glfw
GIT_REPOSITORY https://github.com/glfw/glfw
GIT_TAG 3.3.2
)
FetchContent_MakeAvailable(glfw)
FetchContent_Declare(
glm
GIT_REPOSITORY https://github.com/g-truc/glm
GIT_TAG 0.9.9.8
)
FetchContent_MakeAvailable(glm)
FetchContent_Declare(
volk
GIT_REPOSITORY https://github.com/zeux/volk
GIT_TAG 1.2.170
)
FetchContent_MakeAvailable(volk)
SET(imgui_sources ../ext/imgui/imgui.cpp ../ext/imgui/imgui_draw.cpp ../ext/imgui/imgui_demo.cpp ../ext/imgui/imgui_widgets.cpp ../ext/imgui/imgui_tables.cpp ../ext/imgui/backends/imgui_impl_glfw.cpp)
file(RELATIVE_PATH binary_to_source ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR})
function(ADD_BENCH name)
set(FULL_NAME "vuk_bench_${name}")
add_executable(${FULL_NAME})
target_sources(${FULL_NAME} PRIVATE "${name}.cpp" bench_runner.cpp ../examples/imgui.cpp ../examples/stbi.cpp ${imgui_sources})
target_include_directories(${FULL_NAME} SYSTEM PRIVATE ../ext/stb ../ext/imgui)
target_compile_definitions(${FULL_NAME} PRIVATE GLM_FORCE_SIZE_FUNC GLM_FORCE_EXPLICIT_CTOR GLM_ENABLE_EXPERIMENTAL GLM_FORCE_RADIANS GLM_FORCE_DEPTH_ZERO_TO_ONE)
target_compile_definitions(${FULL_NAME} PUBLIC VUK_EX_PATH_TO_ROOT="${binary_to_source}")
target_link_libraries(${FULL_NAME} PRIVATE vuk)
target_link_libraries(${FULL_NAME} PRIVATE vk-bootstrap glfw glm)
set_target_properties(${FULL_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
)
if(VUK_COMPILER_CLANGPP OR VUK_COMPILER_GPP)
target_compile_options(${FULL_NAME} PRIVATE -std=c++20 -fno-char8_t)
elseif(MSVC)
target_compile_options(${FULL_NAME} PRIVATE /std:c++20 /permissive- /Zc:char8_t-)
endif()
endfunction(ADD_BENCH)
ADD_BENCH(dependent_texture_fetches)
|
374e1bb26249098955d01687750a6d049f39f6b8
|
[
"Markdown",
"CMake",
"C++",
"reStructuredText"
] | 102 |
C++
|
martty/vuk
|
5b6aacb6be0ce31367768b538f0d0157612541e0
|
b4b31639fc8c06ffbce95d13a27d9eec3e272780
|
refs/heads/master
|
<repo_name>chesles/easy-args<file_sep>/README.md
# easy-args
A stupidly simple command-line argument reader.
# WTF WHY?
There are a lot of great full-featured command-line argument parsers out there:
[minimist][minimist], [yargs][yargs], [nomnom][nomnom], and a gazillion others
in [npm][npm-argv].
`easy_args` is for when you just want something a tiny bit better than
`process.argv.indexOf('--arg')`, but you don't need/want something fancy and
complicated.
# API
Get the value of an argument, provide an optional default.
`easy_args` just looks for something in process.argv that looks like either 'arg' or
'--arg', and returns the value immediately after it.
```js
var easy_args = require('easy-argv')
var port = easy_args('port', { default: 8080 })
// check for a flag - return true if the option is present, false if not
var secure = easy_args('ssl', { flag: true })
```
That's it.
## OK THERE'S (a little) MORE
### Numeric args
Anything that looks like a number is converted to a number:
```js
var port = easy_args('port')
// => 8080 (not "8080")
```
Automatic conversion can be disabled by passing the `numbers: false` option:
```js
var port = easy_args('port', { numbers: false })
// => "8080" (not 8080)
```
### Custom argument array
Provide a custom argv array as the last argument. We use `process.argv` by default.
```js
var port = easy_args('port', { default: 8080 }, ['port', '3117'])
//=> 3117
var port = easy_args('port', { default: 8080 }, [])
//=> 8080
var name = easy_args('name', ['name', 'Steve'])
//=> 'Steve'
```
### Environment Variables
Environment-based configuration is nice, let's support that. Just pass `env: true`:
```js
var port = easy_args('port', { default: 8080, env: true })
// looks in process.env for PORT first, then argv for 'port' or '--port'
```
### Aliases
Allow multiple names for arguments by passing an array of names, or using the
`alias` option (which can also be an array if you want to have lots of names
for the same option. Don't go too crazy with this though.)
```js
var port = easy_args(['port', 'p'], { default: 8080 })
var port = easy_args('port', { default: 8080, alias: 'p' })
```
### Batch mode
Get a batch of args all at once
```js
var args = easy_args({
port: { alias: 'p', default: 8080 },
ssl: { flag: true },
})
```
That's all there is. EASY, RIGHT?
[yargs]: https://github.com/chevex/yargs
[minimist]: https://github.com/substack/minimist
[nomnom]: https://github.com/harthur/nomnom
[npm-argv]: https://www.npmjs.org/search?q=argv
<file_sep>/package.json
{
"name": "easy-args",
"version": "1.0.0",
"description": "Super Simple Command Line Argument Reader",
"main": "easy.js",
"scripts": {
"test": "node test.js"
},
"keywords": [
"argv",
"parsing"
],
"author": "<NAME> <<EMAIL>>",
"license": "MIT"
}
<file_sep>/easy.js
function easy_args(names, options, argv) {
// check for batch mode
if (isObject(names) && arguments.length <= 2) {
return process_batch.apply(this, arguments)
}
var params = normalize_arguments(names, options, argv)
, names = params.names
, options = params.options
, argv = params.argv
, index = argv_index(names, argv)
, value = null
if (options.env) {
value = getenv(names.map(toUpper), process.env)
}
if (!value && index >= 0 && (index + 1) < argv.length) {
value = argv[index + 1]
}
return apply_options(index, value, options)
}
function apply_options(index, value, options) {
if (options.flag) {
value = (index >= 0 ? true : false)
}
if (value === null && 'default' in options)
value = options.default
if (options.array && typeof value == 'string')
value = value.split(options.separator || ',')
if (options.numbers !== false)
value = Array.isArray(value)
? value.map(makenum)
: makenum(value)
return value
}
function normalize_arguments(names, options, argv) {
if (!Array.isArray(names))
names = [names]
else
names = names.slice()
if (Array.isArray(options) && argv === undefined) {
argv = options
options = undefined
}
options = options || {}
argv = argv || process.argv
// add aliases to names
if ('alias' in options) {
if (Array.isArray(options.alias)) {
options.alias.forEach(function(a) { names.push(a) })
}
else {
names.push(options.alias)
}
}
// add dashed aliases unless disabled
if (!('dashes' in options) || options.dashes) {
var dashes = names.map(function(n) {
if (!/^--?/.test(n)) {
// double-dash for longer opts, single dash for short opts
return (n.length > 1 ? '--' : '-') + n
}
return n
})
if (options.dashes == 'require') {
names = dashes
}
else {
names = names.concat(dashes)
}
}
return {
names: names,
options: options,
argv: argv,
}
}
// return the index of the first value in names that is present in argv
// or -1 if no values are present in argv
function argv_index(names, argv) {
var index = -1
for (var i=0; i<names.length; i++) {
if ((index = argv.indexOf(names[i])) >= 0)
break
}
return index
}
function getenv(names, env) {
var value
for (var i=0; i<names.length; i++) {
if (names[i] in env) {
value = env[names[i]]
break
}
}
return value
}
function process_batch(batch, argv) {
var results = {}
Object.keys(batch).forEach(function(arg) {
results[arg] = easy_args(arg, batch[arg], argv)
})
return results
}
function toUpper(s) {
return s.toUpperCase()
}
function makenum(v) {
var n
// booleans, empty string, and null shouldn't get converted to numbers
if (v === true || v === false || v === '' || v === null) return v
if (!isNaN(n = Number(v))) return n
else return v
}
function isObject(o) {
var type = typeof o
return type === 'function' || type === 'object' && !!o && !Array.isArray(o)
}
module.exports = easy_args
|
eb668766928f8a59e6f63c0ca2ab47a0633b2c53
|
[
"Markdown",
"JSON",
"JavaScript"
] | 3 |
Markdown
|
chesles/easy-args
|
648f18c9c99e31612a997fcbf40a75d68a70a01a
|
74f73881fc9d433ec3a50728b545180064dd1b69
|
refs/heads/master
|
<repo_name>jimpetersen/eclipse<file_sep>/git git 2/src/git.java
public class git {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("aswufhhwfhiwhfiueh");
System.out.println("FACEROLL RAGE!!!");
for(int i = 0; i<10; i++){
System.out.println("Nu loopar jag din loop " + i);
}
// Här får du en array och for
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
|
77a156d474d29cafce4f3e57d55c0dce59b9174c
|
[
"Java"
] | 1 |
Java
|
jimpetersen/eclipse
|
546527c4f23a8b9eae1f6924aac4dacc20fc7c91
|
b79fabf46e6806f1e9111cc50d1812a3c5b6cd19
|
refs/heads/master
|
<file_sep>package 최현욱_30126;
public class Book {
static String Name;
static String Author;
static String Publisher;
static String Cost;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAuthor() {
return Author;
}
public void setAuthor(String author) {
Author = author;
}
public String getPublisher() {
return Publisher;
}
public void setPublisher(String publisher) {
Publisher = publisher;
}
public String getCost() {
return Cost;
}
public void setCost(String cost) {
Cost = cost;
}
}
|
0d1e460673f8001b489a72fc99172f30b9386a0c
|
[
"Java"
] | 1 |
Java
|
hwchoi8633/library
|
2674ebbad78092493fc8712ce53c372e5ce2148f
|
e16fd88d555b7650db46a7195c55d943e701ad37
|
refs/heads/master
|
<repo_name>rrcutler/Biostats_Final_Project_Spring_2019<file_sep>/Mouse_Aging_Epigenomics_2018-master/Figure1_General/RNA_Mapping_counting_DE/analyze_all_samples_RNA_nested.R
setwd('/Volumes/MyBook_3/BD_aging_project/RNAseq/All_tissues_analysis/DEseq2_runs/')
library(DESeq2)
# input count matrices are in "Figure1_General/RNA_Mapping_counting_DE/count_matrices"
#################################### Liver ####################################
# read in subread count matrix
my.liver1 <- read.table('count_matrices/Aging_Liver_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.liver <- my.liver1[,c(1,6:15)]
rownames(my.liver) <- my.liver[,1]
#################################### Heart ####################################
# read in subread count matrix
my.heart1 <- read.table('count_matrices/Aging_Heart_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.heart <- my.heart1[,c(1,6:15)]
rownames(my.heart) <- my.heart[,1]
#################################### Cerebellum ####################################
# read in subread count matrix
# there were 2 nextseq runs based on poor clustering on flow cell
# will sum up count matrices
my.cereb1 <- read.table('count_matrices/Aging_cerebellum_counts_genes.txt',skip=1,header=T,sep="\t")
my.cereb2 <- read.table('count_matrices/Aging_cerebellum_v2_counts_genes.txt',skip=1,header=T,sep="\t")
my.cereb <- my.cereb1[,c(1,6:15)]
my.cereb[,3:11] <- my.cereb[,3:11] + my.cereb2[,7:15]
rownames(my.cereb) <- my.cereb[,1]
#################################### Olfactory Bulb #################################
# one of the 12mths samples was not analyzed
# read in subread count matrix
my.ob1 <- read.table('count_matrices/Aging_OlfactoryBulb_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.ob <- my.ob1[,c(1,6:14)]
rownames(my.ob) <- my.ob[,1]
#################################### NPCs pools ###################################
# read in subread count matrix
my.npc1 <- read.table('count_matrices/Aging_NPCs_pool_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.npc <- my.npc1[,c(1,6:12)]
rownames(my.npc) <- my.npc[,1]
################
# create combined matrix
my.all <- cbind(my.liver,my.heart[,-c(1:2)],my.cereb[,-c(1:2)],my.ob[,-c(1:2)],my.npc[,-c(1:2)])
my.null <- which(apply(my.all[,3:length(my.all)], 1, sum) <= 1) # see deseq2 vignetter
# Now pull out the spike in genes
spikes.idx <- grep("ERCC-", rownames(my.all))
my.exclude <- union(my.null,spikes.idx)
my.filtered.matrix <- my.all[-my.exclude,3:length(my.all)]
rownames(my.filtered.matrix) <- my.all[-my.exclude,1]
# get age and cell type vectors
age <- as.numeric(c(rep(3,3),rep(12,3),rep(29,3) ,
rep(3,3),rep(12,3),rep(29,3),
rep(3,3),rep(12,3),rep(29,3),
rep(3,3),rep(12,2),rep(29,3),
rep(3,2),rep(12,2),rep(29,2))) # age in months
tissue <- c(rep("liver",9),rep("heart",9),rep("cereb",9),rep("OB",8),rep("NPCs",6))
# global design matrix
dataDesign = data.frame( row.names = colnames( my.filtered.matrix ),
age = age,
tissue = tissue )
#################################################################################################################
#### Normalize to get global age effect (age and tissues as independent covariates) ###
#################################################################################################################
my.outprefix <- paste(Sys.Date(),"ALL_global_variance estimate","DESeq2_LINEAR_model_with_age",sep="_")
# get matrix using age as a modeling covariate
dds.1 <- DESeqDataSetFromMatrix(countData = my.filtered.matrix,
colData = dataDesign,
design = ~ age + tissue)
# run DESeq normalizations and export results
dds.deseq.1 <- DESeq(dds.1)
res.1 <- results(dds.deseq.1, name= "age") # added the name of the tested variable: doesn't seem to be taken correctly by default for FC
tissue.cts <- log2( counts(dds.deseq.1, normalize = TRUE) + 0.01)
# plot dispersion (variance modeled globally)
my.disp.out <- paste(my.outprefix,"_dispersion_plot.pdf")
pdf(my.disp.out)
plotDispEsts(dds.deseq.1)
dev.off()
# expression range
my.exp.out <- paste(my.outprefix,"_Normalized_counts_boxplot.pdf")
pdf(my.exp.out)
boxplot(tissue.cts,col=c(rep("coral",3),rep("blueviolet",3),rep("dodgerblue",3),
rep("coral",3),rep("blueviolet",3),rep("dodgerblue",3),
rep("coral",3),rep("blueviolet",3),rep("dodgerblue",3),
rep("coral",3),rep("blueviolet",2),rep("dodgerblue",3),
rep("coral",2),rep("blueviolet",2),rep("dodgerblue",2)),
cex=0.5,ylab="Log2 DESeq2 Normalized counts", main = "ALL_GLOBAL",
las=2, cex.axis = 0.5)
dev.off()
### get the heatmap of aging changes at FDR5
## exclude NA
res.1 <- res.1[!is.na(res.1$padj),]
genes.aging <- rownames(res.1)[res.1$padj < 0.05]
my.num.aging <- length(genes.aging)
my.heatmap.out <- paste(my.outprefix,"_Heatmap_significant_genes.pdf")
pdf(my.heatmap.out)
my.heatmap.title <- paste("ALL"," aging singificant (FDR<5%), ",my.num.aging, " genes",sep="")
pheatmap(tissue.cts[genes.aging,],
cluster_cols = F,
cluster_rows = T,
colorRampPalette(rev(c("#CC3333","#FF9999","#FFCCCC","white","#CCCCFF","#9999FF","#333399")))(50),
show_rownames = F, scale="row",
main = my.heatmap.title, cellwidth = 10)
dev.off()
# regress out the non age variance for plotting
full.model <- model.matrix(~ age + tissue, data = dataDesign) # all variables
fit <- lmFit(ExpressionSet(assayData=as.matrix(my.filtered.matrix)), full.model)
fit.eb <- eBayes(fit)
print(colnames(fit))
#[1] "(Intercept)" "age" "tissueheart" "tissueliver" "tissueNPCs" "tissueOB"
### Regress out tissue ###
#mod <- coefficients(fit)[,-c(1:2)] %*% t(fit$design[,-c(1:2)]) ### I keep only age (and intercept has cerebellum)
#
mod <- coefficients(fit)[,-2] %*% t(fit$design[,-2]) ### I keep only age (and intercept has cerebellum)
my.filtered.matrix.corrected <- my.filtered.matrix - mod
# do MDS analysis on tisue regressed data
mds.result <- cmdscale(1-cor(my.filtered.matrix.corrected,method="spearman"), k = 2, eig = FALSE, add = FALSE, x.ret = FALSE)
x <- mds.result[, 1]
y <- mds.result[, 2]
my.colors <- c(rep("coral",3),rep("blueviolet",3),rep("dodgerblue",3),
rep("coral",3),rep("blueviolet",3),rep("dodgerblue",3),
rep("coral",3),rep("blueviolet",3),rep("dodgerblue",3),
rep("coral",3),rep("blueviolet",2),rep("dodgerblue",3),
rep("coral",2),rep("blueviolet",2),rep("dodgerblue",2))
my.mds.out <- paste(my.outprefix,"GLOBAL_aging_MDS_plot.pdf",sep="")
pdf(my.mds.out)
plot(x, y, xlab = "MDS dimension 1", ylab = "MDS dimension 2",main="Multi-dimensional Scaling",cex=2,pch=1)
points(x, y, pch=16,col=my.colors,cex=2)
legend("topleft",c("3m","12m","29m"),col=c("coral","blueviolet","dodgerblue"),pch=16,bty='n',pt.cex=1.5)
dev.off()
### get the heatmap of aging changes at FDR5 (tissue_regressed
## exclude NA
my.heatmap.out2 <- paste(my.outprefix,"_Heatmap_significant_genes_TISSUE_REGRESSED.pdf")
pdf(my.heatmap.out2, height = 10, width = 10, onefile=F)
my.heatmap.title <- paste("ALL TISSUE REGRESSED"," aging singificant (FDR<5%), ",my.num.aging, " genes",sep="")
pheatmap(my.filtered.matrix.corrected[genes.aging,],
cluster_cols = F,
cluster_rows = T,
colorRampPalette(rev(c("#CC3333","#FF9999","#FFCCCC","white","#CCCCFF","#9999FF","#333399")))(50),
show_rownames = F, scale="row",
main = my.heatmap.title, cellwidth = 10)
dev.off()
# output result tables to files
my.out.ct.mat <- paste(my.outprefix,"_log2_counts_matrix.txt")
my.out.stats <- paste(my.outprefix,"_all_genes_statistics.txt")
my.out.fdr5 <- paste(my.outprefix,"_FDR5_genes_statistics.txt")
my.out.rdata <- paste(my.outprefix,"ALL_statistics.RData")
write.table(tissue.cts, file = my.out.ct.mat , sep = "\t" , row.names = T, quote=F)
write.table(res.1, file = my.out.stats , sep = "\t" , row.names = T, quote=F)
write.table(res.1[genes.aging,], file = my.out.fdr5, sep = "\t" , row.names = T, quote=F)
# save RData Object
my.aging_all.RNAseq.process <- res.1
save(res.1, file = my.out.rdata)<file_sep>/Mouse_Aging_Epigenomics_2018-master/Figure1_General/RNA_Mapping_counting_DE/analyze_all_samples_RNA_forMDS_PCA.R
setwd('/Volumes/MyBook_3/BD_aging_project/RNAseq/All_tissues_analysis/')
library(DESeq2)
# global clustering: do norm cross all samples
# generate global MDS/PCA
#################################### Liver ####################################
# read in subread count matrix
my.liver1 <- read.table('count_matrices/Aging_Liver_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.liver <- my.liver1[,c(1,6:15)]
rownames(my.liver) <- my.liver[,1]
#################################### Heart ####################################
# read in subread count matrix
my.heart1 <- read.table('count_matrices/Aging_Heart_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.heart <- my.heart1[,c(1,6:15)]
rownames(my.heart) <- my.heart[,1]
#################################### Cerebellum ####################################
# read in subread count matrix
# there were 2 nextseq runs based on poor clustering on flow cell
# will sum up count matrices
my.cereb1 <- read.table('count_matrices/Aging_cerebellum_counts_genes.txt',skip=1,header=T,sep="\t")
my.cereb2 <- read.table('count_matrices/Aging_cerebellum_v2_counts_genes.txt',skip=1,header=T,sep="\t")
my.cereb <- my.cereb1[,c(1,6:15)]
my.cereb[,3:11] <- my.cereb[,3:11] + my.cereb2[,7:15]
rownames(my.cereb) <- my.cereb[,1]
#################################### Olfactory Bulb #################################
# one of the 12mths samples was not analyzed
# read in subread count matrix
my.ob1 <- read.table('count_matrices/Aging_OlfactoryBulb_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.ob <- my.ob1[,c(1,6:14)]
rownames(my.ob) <- my.ob[,1]
#################################### NPCs pools ###################################
# read in subread count matrix
my.npc1 <- read.table('count_matrices/Aging_NPCs_pool_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.npc <- my.npc1[,c(1,6:12)]
rownames(my.npc) <- my.npc[,1]
my.all <- cbind(my.liver,my.heart[,-c(1:2)],my.cereb[,-c(1:2)],my.ob[,-c(1:2)],my.npc[,-c(1:2)])
my.null <- which(apply(my.all[,3:length(my.all)], 1, sum) <= 1) # see deseq2 vignette
# Now pull out the spike in genes
spikes.idx <- grep("ERCC-", rownames(my.all))
my.exclude <- union(my.null,spikes.idx)
my.filtered.matrix <- my.all[-my.exclude,3:length(my.all)]
rownames(my.filtered.matrix) <- my.all[-my.exclude,1]
age <- as.numeric(c(rep(3,3),rep(12,3),rep(29,3) ,
rep(3,3),rep(12,3),rep(29,3),
rep(3,3),rep(12,3),rep(29,3),
rep(3,3),rep(12,2),rep(29,3),
rep(3,2),rep(12,2),rep(29,2))) # age in months
tissue <- c(rep("liver",9),rep("heart",9),rep("cereb",9),rep("OB",8),rep("NPCs",6))
# design matrix
dataDesign = data.frame( row.names = colnames( my.filtered.matrix ), age = age, tissue = tissue )
# get matrix using age as a modeling covariate
dds <- DESeqDataSetFromMatrix(countData = my.filtered.matrix,
colData = dataDesign,
design = ~ age + tissue)
dds.deseq <- DESeq(dds)
# get normalized data
tissue.cts <- log2( counts(dds.deseq, normalize = TRUE) + 0.01)
mds.result <- cmdscale(1-cor(tissue.cts,method="spearman"), k = 2, eig = FALSE, add = FALSE, x.ret = FALSE)
x <- mds.result[, 1]
y <- mds.result[, 2]
my.colors <- c(rep("coral",3), rep("blueviolet", 3),rep("dodgerblue",3),
rep("coral",3), rep("blueviolet", 3),rep("dodgerblue",3),
rep("coral",3), rep("blueviolet", 3),rep("dodgerblue",3),
rep("coral",3), rep("blueviolet", 2),rep("dodgerblue",3),
rep("coral",2), rep("blueviolet", 2),rep("dodgerblue",2))
# pch: by tissues
my.pchs <- c(rep(8,9),rep(14,9),rep(5,9),rep(1,8),rep(11,6))
# NPC - 11
# Heart - 14
# Cere - 5
# Liver - 8
# OB - 1
pdf("2017-04-07_MDS_RNAseq_DESeq_norm_together_BIGPTS.pdf")
plot(x, y, xlab = "MDS dimension 1", ylab = "MDS dimension 2",main="Multi-dimensional Scaling",cex=4,col=NULL)
points(x, y, pch=my.pchs,col=my.colors,cex=4)
legend("topleft",c("NPCs","Cerebellum","Olfactory bulb","Heart","Liver"),pch=c(11,5,1,14,8),col="grey",bty='n',pt.cex=1)
legend("topright",c("3m","12m","29m"),col=c("coral","blueviolet","dodgerblue"),pch=16,bty='n',pt.cex=1)
dev.off()
##### do PCA analysis
my.pos.var <- apply(tissue.cts,1,var) >0
my.pca <- prcomp(t(tissue.cts[my.pos.var,]),scale = TRUE)
x <- my.pca$x[,1]
y <- my.pca$x[,2]
my.summary <- summary(my.pca)
my.pca.out <- paste(Sys.Date(),"PCA_RNAseq_DESeq_norm_together_BIGPTS.pdf",sep="")
pdf(my.pca.out)
plot(x,y,pch = 16, cex=4,
xlab = paste('PC1 (', round(100*my.summary$importance[,1][2],1),"%)", sep=""),
ylab = paste('PC2 (', round(100*my.summary$importance[,2][2],1),"%)", sep=""),
cex.lab = 1, col = NULL)
points(x,y, cex= 4, lwd = 1.5, col=my.colors, pch = my.pchs)
legend("bottomright",c("NPCs","Cerebellum","Olfactory bulb","Heart","Liver"),pch=c(11,5,1,14,8),col="grey",bty='n',pt.cex=1)
legend("bottomleft",c("3m","12m","29m"),col=c("coral","blueviolet","dodgerblue"),pch=16,bty='n',pt.cex=1)
dev.off()<file_sep>/Mouse_Aging_Epigenomics_2018-master/Figure1_General/RNA_Mapping_counting_DE/map_with_STAR.sh
#!/bin/bash
# set the name of the job
#$ -N Heart_star
#
# set the maximum memory usage
#$ -l h_vmem=8G
#
#$ -q extended
#
#$ -pe shm 6
#
# set the maximum run time
#$ -l h_rt=150:00:00
#
#$ -l h_stack=15M
#
# send mail when job ends or aborts
#$ -m ea
#
# specify an email address
#$ -M <EMAIL>
#
# check for errors in the job submission options
#$ -w e
#
#$ -R y
cd /srv/gs1/projects/brunet/BB/Heart/;
export GENIN=/srv/gs1/projects/brunet/BB/MM9_ERCC
export START_EXEC=/srv/gs1/projects/brunet/tools/STAR-STAR_2.4.0j/source
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 3m4_heart_ATCACG_R1_val_1.fq 3m4_heart_ATCACG_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 3m4_heart_ATCACG
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 3m5_heart_CGATGT_R1_val_1.fq 3m5_heart_CGATGT_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 3m5_heart_CGATGT
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 3m6_heart_TTAGGC_R1_val_1.fq 3m6_heart_TTAGGC_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 3m6_heart_TTAGGC
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 12m4_heart_TGACCA_R1_val_1.fq 12m4_heart_TGACCA_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 12m4_heart_TGACCA
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 12m5_heart_ACAGTG_R1_val_1.fq 12m5_heart_ACAGTG_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 12m5_heart_ACAGTG
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 12m6_heart_GCCAAT_R1_val_1.fq 12m6_heart_GCCAAT_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 12m6_heart_GCCAAT
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 29m4_heart_CAGATC_R1_val_1.fq 29m4_heart_CAGATC_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 29m4_heart_CAGATC
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 29m5_heart_ACTTGA_R1_val_1.fq 29m5_heart_ACTTGA_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 29m5_heart_ACTTGA
$START_EXEC/STAR --genomeDir $GENIN --readFilesIn 29m6_heart_GATCAG_R1_val_1.fq 29m6_heart_GATCAG_R2_val_2.fq --runThreadN 6 --outFilterMultimapNmax 10 --outFilterIntronMotifs RemoveNoncanonicalUnannotated --outFileNamePrefix 29m6_heart_GATCAG
module load samtools
for f in $(find . -name '*.sam')
do
fileName=$(basename "${f}" | sed 's/\.sam/\.bam/g');
filePath="."
oFname="${filePath}/${fileName}"
samtools view -b -S $f > $oFname
done
<file_sep>/Mouse_Aging_Epigenomics_2018-master/Figure1_General/RNA_Mapping_counting_DE/process_RNAseq_datasets_v4_PCA.R
setwd('/Volumes/BB_Backup_3//BD_aging_project/RNAseq/All_tissues_analysis/DEseq2_runs/Separate/')
source('RNAseq_analysis_functions_v4_forPCA.R')
# input count matrices are in "Figure1_General/RNA_Mapping_counting_DE/count_matrices"
#################################### Liver ####################################
# read in subread count matrix
my.liver1 <- read.table('/Volumes/BB_Backup_3/BD_aging_project/RNAseq/Liver/STAR/Aging_Liver_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.liver <- my.liver1[,c(1,6:15)]
rownames(my.liver) <- my.liver[,1]
# process RNAseq data and save RData object
my.liver.RNAseq.process <- process_aging_rnaseq("Liver", my.liver)
save(my.liver.RNAseq.process, file="RNA_seq_result_Liver_2018-03-09.RData")
#####################################################################################
#################################### Heart ####################################
# read in subread count matrix
my.heart1 <- read.table('/Volumes/BB_Backup_3/BD_aging_project/RNAseq/Heart/STAR/Aging_Heart_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.heart <- my.heart1[,c(1,6:15)]
rownames(my.heart) <- my.heart[,1]
# process RNAseq data and save RData object
my.heart.RNAseq.process <- process_aging_rnaseq("Heart", my.heart)
save(my.heart.RNAseq.process, file="RNA_seq_result_Heart_2018-03-09.RData")
###################################################################################
#################################### Cerebellum ####################################
# read in subread count matrix
# there were 2 nextseq runs based on poor clustering on flow cell
# will sum up count matrices
my.cereb1 <- read.table('/Volumes/BB_Backup_3/BD_aging_project/RNAseq/Cereb/1st_run/STAR/Aging_cerebellum_counts_genes.txt',skip=1,header=T,sep="\t")
my.cereb2 <- read.table('/Volumes/BB_Backup_3/BD_aging_project/RNAseq/Cereb/2nd_run/STAR/Aging_cerebellum_v2_counts_genes.txt',skip=1,header=T,sep="\t")
# process RNAseq data and save RData object
my.cereb.RNAseq.process <- process_aging_rnaseq("Cerebellum", my.cereb)
save(my.cereb.RNAseq.process, file="RNA_seq_result_cereb_2018-03-09.RData")
####################################################################################
#################################### Olfactory Bulb #################################
# one of the 12mths samples was not analyzed
# read in subread count matrix
my.ob1 <- read.table('/Volumes/BB_Backup_3/BD_aging_project/RNAseq/OB/STAR/Aging_OlfactoryBulb_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.ob <- my.ob1[,c(1,6:14)]
rownames(my.ob) <- my.ob[,1]
# process RNAseq data and save RData object
my.ob.RNAseq.process <- process_aging_rnaseq("OlfactoryBulb", my.ob, reps.3=3, reps.12=2, reps.29=3)
save(my.ob.RNAseq.process, file="RNA_seq_result_OB_2018-03-09.RData")
#####################################################################################
#################################### NPCs pools ###################################
# read in subread count matrix
my.npc1 <- read.table('/Volumes/BB_Backup_3/BD_aging_project/RNAseq/NPC_Pool/STAR/Aging_NPCs_pool_counts_genes.txt',skip=1,header=T,sep="\t",stringsAsFactors=F)
my.npc <- my.npc1[,c(1,6:12)]
rownames(my.npc) <- my.npc[,1]
# process RNAseq data and save RData npcject
my.npc.RNAseq.process <- process_aging_rnaseq("NPCs", my.npc, reps.3=2, reps.12=2, reps.29=2)
save(my.npc.RNAseq.process, file="RNA_seq_result_NPCs_2018-03-09.RData")
#####################################################################################
<file_sep>/190516_Transcriptional_Variability_Aging.Rmd
---
title: "Transcriptional Variability with Aging"
author: "<NAME>"
date: "5/16/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
The purpose of this is to use methods developed in, <NAME>., <NAME>., & <NAME>. (2019). The widespread increase in inter-individual variability of gene expression in the human brain with age. Aging, 11(8). https://doi.org/10.18632/aging.101912, and apply them to the datasets presented in <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., … <NAME>. (2019). Remodeling of epigenome and transcriptome landscapes with aging in mice reveals widespread induction of inflammatory responses. Genome Research, 29(4), 697–709. https://doi.org/10.1101/gr.240093.118.
Could also create protein-protein interaction network and then look at network perturbations using differential variability analysis: https://bmcresnotes.biomedcentral.com/articles/10.1186/1756-0500-6-430
## Load libraries
```{r}
colors <- c("#A7A7A7",
"dodgerblue",
"firebrick",
"forestgreen",
"gold")
library(DESeq2)
library(affy)
library(ggplot2)
library(vsn)
library(ggrepel)
library(factoextra)
library(FactoMineR)
library(genefilter)
library(fdrtool)
library(reshape2)
library(RColorBrewer)
library(sva)
library("biomaRt")
```
## Load data
Filter featureCounts tables to remove everything but counts and Geneid
```{r}
ob_data <- read.table("/Users/refrigerator/Documents/School/UTHSCSA/Spring_2019/Bioinformatics/Final_Project/Mouse_Aging_Epigenomics_2018-master/Figure1_General/RNA_Mapping_counting_DE/count_matrices/Aging_OlfactoryBulb_counts_genes.txt", header = TRUE, row.names = 1)
ob_data <- ob_data[,-(1:5)]
```
1. USe SVA for unsupervised estimation of covariates from the data and include this in regression model
2. Start out with normal differential expression analysis
```{r}
# the different names for the samples
colnames(ob_data) <- c("OB_3m3", "OB_3m2","OB_3m1", "OB_12m1","OB_12m3", "OB_29m3", "OB_29m2", "OB_29m1")
# Convert to matrix
countdata <- as.matrix(ob_data)
head(ob_data)
# different ages as independent variables
ob_ages <- factor(c(3,3,3,12,12,29,29,29))
# Create a coldata frame and instantiate the DESeqDataSet
(coldata <- data.frame(row.names=colnames(ob_data), ob_ages))
# read the count data from the matrix into a DESeq object with a design to test the effects of time
dds <- DESeqDataSetFromMatrix(countData=ob_data, colData=coldata, design=~ob_ages)
```
## Proportion of low counts
Percentage of counts less than 10 per sample.
```{r}
# for each column (sample) count the number of counts less than or equal to ten, get the proportion with the mean() function, and then multiply this by 100
proportion_10 <- apply(counts(dds), MARGIN = 2, function(x) 100*mean(x<= 10))
# plot a barplot where the colors correspond to the condition
barplot(proportion_10,
horiz = TRUE,
las = 1,
cex.names = 0.5,
col = colors[colData(dds)$ob_ages],
ylab='Samples',
xlab='% of counts less than 10',
main="Percentage of counts less than 10 per sample")
```
## Filtering low counts
This filters out genes which have less than 10 read counts when summed across all conditions. This is an arbitrary but minimal count filter. We see that 528 genes were filtered out using this threshold. It is interesting that this filtering does not appear to change the percentage of counts < 10/sample.
```{r}
# length before
before_len <- length(row.names(dds))
# filtering
dds_filter <- dds[rowSums(counts(dds)) >= 10]
# length after
after_len <- length(row.names(dds_filter))
# amount filtered
before_len - after_len
# plot before and after length
barplot(c(before_len, after_len), xlab = "Filtering", ylab = "Amount of genes", col = colors)
# for each column (sample) count the number of counts less than or equal to ten, get the proportion with the mean() function, and then multiply this by 100
proportion_10 <- apply(counts(dds_filter), MARGIN = 2, function(x) 100*mean(x<= 10))
# plot a barplot where the colors correspond to the condition
barplot(proportion_10,
horiz = TRUE,
las = 1,
cex.names = 0.5,
col = colors[colData(dds)$ob_ages],
ylab='Samples',
xlab='% of counts less than 10',
main="Percentage of counts less than 10 per sample")
```
## Count distribution before normalization
Plotting the distirbution of counts on the log2 scale. We see here that the count distribution is very low for T120, indicating that it has mostly low counts for all genes because phage transcription has now taken over in a small subset of highly expressed genes as compared to the many lowly expressed bacterial genes.
```{r}
# plotting an unnormalized density plot of the log transformed counts
plotDensity(log2(counts(dds_filter) + 1),
lty=1,
col=colors[colData(dds)$ob_ages],
lwd=1,
xlab = "log2(Counts + 1)",
main = "Unnormalized Counts")
legend("topright",
legend=levels(colData(dds)$ob_ages),
lwd=1, col = colors)
# plotting an unnormalized box plot of the log transformed counts
boxplot(log2(counts(dds_filter) + 1),
col = colors[colData(dds)$ob_ages],
cex.axis = 0.5,
las = 1,
horizontal = TRUE,
xlab = "log2(Counts + 1)",
ylab = "Samples",
main = "Unnormalized Counts")
```
## Running DESeq
First we set our reference level to 3 months of age, as this is the age we will be making comparisons against. Then, we simply run DESeq using the DESeq() function. This will estimate the size factors to normalize counts between samples, estimate dispersion parameters and perform dispersion shrinkage, and finally test for differential expression using the wald test with independent filtering to alleviate benjamini-hochberg multiple hypothesis correction.
```{r}
# set T0
dds_filter$ob_ages <- relevel(dds_filter$ob_ages, ref = "3")
# Run DESeq
dds_filter <- DESeq(dds_filter)
```
## Count distribution after normalization
We do this to make sure the normalization is working as expected.
```{r}
# density plot normalized
plotDensity(log2(counts(dds_filter, normalized = TRUE) + 1),
lty=1,
col=colors[colData(dds_filter)$ob_ages],
lwd=1,
xlab = "log2(Counts + 1)",
main = "Normalized Counts")
legend("topright",
legend=levels(colData(dds_filter)$ob_ages),
lwd=1, col = colors)
# box plot normalized
boxplot(log2(counts(dds_filter, normalized = TRUE) + 1),
col = colors[colData(dds_filter)$ob_ages],
cex.axis = 0.5,
las = 1,
horizontal = TRUE,
xlab = "log2(Counts + 1)",
ylab = "Samples",
main = "Normalized Counts")
legend("topright",
legend=levels(colData(dds)$ob_ages),
lwd=1, col = colors)
```
## Mean Variance Relationship
Plotting the mean and variance to examine whether the data appears to have a non-linear relationship between the variance and mean which would support the use of a negative binomial distribution to model read counts. This is done by comparing the mean-variance plot to a linear line. Here we can see that our data does indeed increase in varaince as the mean increases in a non-linear fashion.
```{r}
## Computing mean and variance
norm.counts <- counts(dds_filter, normalized=TRUE)
mean.counts <- rowMeans(norm.counts)
variance.counts <- apply(norm.counts, MARGIN = 1, var)
## Mean and variance relationship
mean.var.col <- densCols(x=log2(mean.counts), y=log2(variance.counts))
plot(x=log2(mean.counts), y=log2(variance.counts), pch=16, cex=0.5,
col=mean.var.col, main="Mean-variance relationship", xlab="Mean log2(normalized counts) per gene", ylab="Variance of log2(normalized counts)", panel.first = grid())
abline(a=1, b=1, col="red")
```
##Estimation of Dispersion
This gives us a feel for what the dispersion parameter is in our model and what the effect of dispersion shrinkage is. We see that there are 112 dispersion shrinkage outliers which will keep their original dispersions before shrinkage.
```{r}
plotDispEsts(dds_filter)
sum(mcols(dds_filter,use.names=TRUE)[,"dispOutlier"])
```
## Transform normalized counts to stabalize mean-variance for clustering
Using two transformations in order to stabalize the mean-variance relationship in order to minimize the influence of genes with low read counts when performing unsupervised analysis. We use the blind = FALSE parameter to indicate to take into account our design when transforming counts.
1. regularized log
2. variance stabalizing transformation
```{r}
dds_rlog <- rlog(dds_filter, blind = FALSE)
dds_vst <- vst(dds_filter, blind = FALSE)
```
Log2 transformed counts just for comparison. We can see that this does not stabalize the mean-variane relationship.
```{r}
dds_log2 <- log2(counts(dds_filter) + 1)
meanSdPlot(dds_log2)
```
Compare rlog and vst transformations. We choose to use the rlog transformation here as the line appear to be more horizontal than the VST fitted line. We notice there are still many outliers which where the transformation could not correct for the mean-variance relationship, especially when normalized counts increased.
```{r}
meanSdPlot(assay(dds_rlog))
meanSdPlot(assay(dds_vst))
```
## Principle Component Analysis
PCA clustering function. For input this requires the number of genes we want to use and the stablized mean-variance object (VST or rlog).
```{r}
# PCA plot of samples
PCAPlotter <- function(ntop, vsd, shape) {
# getting most variable genes
Pvars <- rowVars(assay(vsd))
select <- order(Pvars, decreasing = TRUE)[seq_len(min(ntop,
length(Pvars)))]
sampleNO <- rownames(colData(vsd))
# calculate pca - zero centering variables and scaling where all variables have unit variance
PCA <- prcomp(t(assay(vsd)[select, ]), scale = T, center = TRUE)
percentVar <- round(100*PCA$sdev^2/sum(PCA$sdev^2),1)
dataGG = data.frame(PC1 = PCA$x[,1], PC2 = PCA$x[,2],
PC3 = PCA$x[,3], PC4 = PCA$x[,4],
condition = colData(vsd)$ob_ages)
# plotting
print(ggplot(data = dataGG) +
geom_point(data = dataGG, mapping = aes(x = PC1, y = PC2, color = condition, shape = shape), size = 6) +
scale_shape_identity() +
labs(title = paste("PC1 vs PC2, Top", toString(ntop), "Variable Genes"),
x = paste0("PC1: ", round(percentVar[1],4), "%"),
y = paste0("PC2: ", round(percentVar[2],4), "%")) +
scale_colour_brewer(type="qual", palette=2) +
theme_classic() +
scale_color_discrete(name = "Age (months)") +
theme(axis.text = element_text(size = 15),
legend.box = "horizontal",
axis.title.y = element_text(size = 15, face = "bold"),
axis.title.x = element_text(size = 15, face = "bold"),
legend.text = element_text(size = 10),
legend.title = element_text(size = 12, face = "bold"),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "black"),
legend.position = "top") +
geom_label_repel(aes(label = sampleNO, x = PC1, y = PC2), color = "black") +
guides(colour = guide_legend(override.aes = list(shape = shape))))
PCA$rotation
PCA$sdev
return(PCA)
}
```
### Bacteria + Bacteriophage PCA Plots
PCA Plot using the combined bacteria and bacteriophage gene expression. We choose the PCA plot to further analyze where the graph has stabalized, which appears to be when using the top 5000 variable genes. It appears here that the labeling of our samples is good and that the replicates appear to have similar profiles to each other as expected. Interestingly the T0 replicates appear to be the most distant as compared to other time points, which could suggest variaibility in transcription before the infection.
```{r}
PCA <- PCAPlotter(500, dds_rlog, 15)
PCA <- PCAPlotter(1000, dds_rlog, 15)
PCA <- PCAPlotter(5000, dds_rlog, 15)
PCA <- PCAPlotter(length(row.names(dds_filter)), dds_rlog, 15)
```
Plot of eigenvalues for each PCA showing how much each account for total variance. We are able to see how much each total variance each dimensions accounts for, which genes explain the greatest variance within each dimension, and which samples are the greatest influencers on each dimension.
```{r}
PCA <- PCAPlotter(5000, dds_rlog, 15)
# get importance of each component
fviz_eig(PCA, addlabels = TRUE)
var <- get_pca_var(PCA)
# contributions of individual genes to each PC
fviz_contrib(PCA, choice = "var", axes = 1, top = 20, rotate = TRUE, sort.val = "asc")
fviz_contrib(PCA, choice = "var", axes = 2, top = 20, rotate = TRUE, sort.val = "asc")
# contributions of individual samples to each PC
fviz_contrib(PCA, choice = "ind", axes = 1, top = 20, rotate = TRUE, sort.val = "asc")
fviz_contrib(PCA, choice = "ind", axes = 2, top = 20, rotate = TRUE, sort.val = "asc")
```
## SVA Surrogate covariate estimation default
Using the SVA package in order to estimate surrogate covariates that will attempt to remove batch effects and other unwanted variation. We include our condition design here because we do not want to remove variation associated with this effect. Note that SVA was not used in the original analysis by Benayoun et al 2019.
```{r}
# Loading all variables
dat <- counts(dds_filter, normalized = TRUE)
idx <- rowMeans(dat) > 1
dat <- dat[idx, ]
mod <- model.matrix(~ ob_ages, colData(dds))
mod0 <- model.matrix(~ 1, colData(dds))
svseq_default <- svaseq(dat, mod, mod0)
```
Plotting the surrogate variables for each sample. Here we can see a general direction each sample will move in after using the covariate to normalize for counts. The further away from zero the more extreme the normalization. We can also see the grouping of the samples based on unwanted variation.
```{r}
plot(svseq_default$sv, pch = 19, col = "blue")
text(svseq_default$sv, labels=rownames(colData(dds_vst)), cex= 0.7)
```
Adding surrogate variables to the DESEq2 design and re-testing for differential expression against the batches in order to compare to the original DE test. The amount of surrogate variables here will vary.
```{r}
# create a new deseq2 object which uses the surrogate variables
ddssva_default <- dds_filter
# add each surrogate vriable to the design and update the design
ddssva_default$SV1 <- svseq_default$sv[,1]
ddssva_default$SV2 <- svseq_default$sv[,2]
design(ddssva_default) <- ~ SV1 + SV2 + ob_ages
# Run DESeq
ddssva_default$condition <- relevel(ddssva_default$ob_ages, ref = "3")
ddssva_default <- DESeq(ddssva_default)
```
Variance stabalizing transformation. Setting blind = TRUE because we do not want to bias this with information from the design.
```{r}
ddssva_default_vst <- vst(ddssva_default, blind = TRUE)
```
Switching out vst counts for batch corrected counts by limma to plot PCA that displays batch correction. Also getting normalized and unormalized batch corrected counts for downstream processing.
```{r}
ddssva_default_vst_limma <- ddssva_default_vst
ddssva_default_vst_limma_condition <- ddssva_default_vst
# this simply removes any shifts in the log2-scale expression data that is adjusted for according to sva covariates
assay(ddssva_default_vst_limma) <- limma::removeBatchEffect(assay(ddssva_default_vst), covariates = colData(ddssva_default_vst)[,c(2:3)])
# attempting to account for conditions
assay(ddssva_default_vst_limma_condition) <- limma::removeBatchEffect(assay(ddssva_default_vst), covariates = colData(ddssva_default_vst)[,c(2:3)], design = model.matrix(~ob_ages, colData(ddssva_default)))
# to keep colData and such for processing below
ddssva_default_noramlized <- ddssva_default
ddssva_default_unnoramlized <- ddssva_default
ddssva_default_noramlized_counts_vst <- ddssva_default_vst
ddssva_default_unnoramlized_counts_vst <- ddssva_default_vst
# using normalized counts instead for plotting gene expression
ddssva_default_noramlized_counts <- limma::removeBatchEffect(counts(ddssva_default, normalized = TRUE), covariates = colData(ddssva_default_vst)[,c(2:3)], design = model.matrix(~ob_ages, colData(ddssva_default)))
ddssva_default_noramlized_counts[ddssva_default_noramlized_counts < 0] <- 0 # remove zeros
ddssva_default_noramlized_counts <- round(ddssva_default_noramlized_counts) # convert to integers
assay(ddssva_default_noramlized) <- ddssva_default_noramlized_counts
assay(ddssva_default_noramlized_counts_vst) <- vst(ddssva_default_noramlized_counts, blind = TRUE)
# using unnormalized counts instead for later transformation
ddssva_default_unnoramlized_counts <- limma::removeBatchEffect(counts(ddssva_default, normalized = FALSE), covariates = colData(ddssva_default_vst)[,c(2:3)], design = model.matrix(~ob_ages, colData(ddssva_default)))
ddssva_default_unnoramlized_counts[ddssva_default_unnoramlized_counts < 0] <- 0 # remove zeros
ddssva_default_unnoramlized_counts <- round(ddssva_default_unnoramlized_counts) # convert to integers
assay(ddssva_default_unnoramlized) <- ddssva_default_unnoramlized_counts
assay(ddssva_default_unnoramlized_counts_vst) <- vst(ddssva_default_unnoramlized_counts, blind = TRUE)
```
PCA plot and plot of eigenvalues for each PCA showing how much each account for total variance. It appears that the SVA correction has the groups nicely plotted together and that age seems to be accounted for by PC1.
```{r}
PCA <- PCAPlotter(5000, dds_vst, 16)
PCA <- PCAPlotter(5000, ddssva_default_vst_limma, 16)
PCA <- PCAPlotter(5000, ddssva_default_noramlized_counts_vst, 16)
PCA <- PCAPlotter(5000, ddssva_default_unnoramlized_counts_vst, 16)
PCA <- PCAPlotter(5000, ddssva_default_vst_limma_condition, 16)
# get importance of each component
fviz_eig(PCA, addlabels = TRUE)
var <- get_pca_var(PCA)
# contributions of individual genes to each PC
fviz_contrib(PCA, choice = "var", axes = 1, top = 20, rotate = TRUE, sort.val = "asc")
fviz_contrib(PCA, choice = "var", axes = 2, top = 20, rotate = TRUE, sort.val = "asc")
# contributions of individual samples to each PC
fviz_contrib(PCA, choice = "ind", axes = 1, top = 20, rotate = TRUE, sort.val = "asc")
fviz_contrib(PCA, choice = "ind", axes = 2, top = 20, rotate = TRUE, sort.val = "asc")
```
# Differential Expression Results
## Results Names
This allows us to look at all the comparisons that were made between the reference. We will use these names when extracting results using the results() function.
```{r}
resultsNames(ddssva_default)
```
Write output function for results table to csv. Make sure that the directory, "dir" is set!
The output function takes as input: results object, DESeq object, timepoint of comparison, vector of conditions being compared, output directory
```{r}
writeOutput <- function(res, dds, stage, cond, dir) {
resOrdered <- res[order(res$padj),]
resdata <- merge(as.data.frame(resOrdered), as.data.frame(counts(dds, normalized=TRUE)), by="row.names", sort=FALSE, all = TRUE) #includes normalized counts in output csv
names(resdata)[1] <- "Gene" # set header of first column
outfile <- paste(cond[1], cond[length(cond)], stage, "DESeq2.csv", sep = "_")
outfile <- paste(dir, outfile, sep = "")
write.csv(as.data.frame(resdata), file = outfile, row.names = FALSE)
}
# setting output dir
dir <- "/Users/refrigerator/Documents/School/UTHSCSA/Spring_2019/Bioinformatics/Final_Project/DESeq2_Output/"
```
## 3 months vs 12 months
Using original model
```{r}
# Extract the 3 months vs 12 months result using an alpha threshold of 0.05
res_3_12 <- results(dds_filter, alpha = 0.05, name = "ob_ages_12_vs_3")
# p-value distribution histogram
hist(res_3_12$pvalue, main = "P-value distribution 3 months vs 12 months", xlab = "P-value", ylab = "Frequency", col = "lavender")
# get shrunken fold change
res <- lfcShrink(dds_filter, contrast = c("ob_ages", "3", "12"), type="normal")
# get a summary of the amount of significantly differentially expressed genes
summary(res_3_12, alpha = 0.05)
# write the results
writeOutput(res_3_12, dds_filter, "Olfactory_bulb_lfcShrink", c("3", "12"), dir)
```
Using SVA corrected model
```{r}
# Extract the 3 months vs 12 months result using an alpha threshold of 0.05
res_3_12 <- results(ddssva_default, alpha = 0.05, name = "ob_ages_12_vs_3")
# p-value distribution histogram
hist(res_3_12$pvalue, main = "P-value distribution 3 months vs 12 months", xlab = "P-value", ylab = "Frequency", col = "lavender")
# get shrunken fold change
res <- lfcShrink(ddssva_default, contrast = c("ob_ages", "3", "12"), type="normal")
# get a summary of the amount of significantly differentially expressed genes
summary(res_3_12, alpha = 0.05)
# write the results
#writeOutput(res_3_12, ddssva_default, "Olfactory_bulb_lfcShrink", c("3", "12"), dir)
```
P-value correction on 3 months vs 12 months with SVA model. Doing this because p-val histogram is skewed to the right.
Clear out genes that were removed via independent filtering, clear out padj values, Re-estimate p-values using z-score
```{r}
# save these to append later
padj_save <- res_3_12[is.na(res_3_12$padj),]
pvalue_save <- padj_save[is.na(padj_save$pvalue),]
# remove genes filtered out by independent filtering
res_3_12 <- res_3_12[!is.na(res_3_12$padj),]
res_3_12 <- res_3_12[!is.na(res_3_12$pvalue),]
# remove all adjusted pvalues, will replace later
res_3_12 <- res_3_12[, -which(names(res_3_12) == "padj")]
# get z-scores_3_12 as input to fdrtool to re-estimte p-values
FDR.res_3_12 <- fdrtool(res_3_12$stat, statistic = "normal", plot = T)
# calculate new padj values using BH correction
res_3_12[, "padj"] <- p.adjust(FDR.res_3_12$pval, method = "BH")
# put new pvals in res_3_12 object
res_3_12$pvalue <- FDR.res_3_12$pval
# summary before binding
summary(res_3_12, alpha = 0.05)
# append the filtered out rows back on
res_3_12 <- rbind(res_3_12, padj_save)
res_3_12 <- rbind(res_3_12, pvalue_save)
```
Get padj values from re-estimated pvalues, plot new p-value distribution, and output. We see here that the p-value distribution is less skewed than before. However, there are much less DE genes so we will stick with the uncorrected model for the rest of the analysis.
```{r}
# plot new p-value historgram
hist(res_3_12$pvalue, main = "P-value distribution 30 vs 60 minutes", xlab = "P-value", ylab = "Frequency", col = "blue")
```
## 12 months vs 29 months
Using original model
```{r}
# Extract the 3 months vs 12 months result using an alpha threshold of 0.05
res_12_29 <- results(dds_filter, alpha = 0.05, contrast = c("ob_ages", "12", "29"))
# p-value distribution histogram
hist(res_12_29$pvalue, main = "P-value distribution 12 months vs 29 months", xlab = "P-value", ylab = "Frequency", col = "lavender")
# get shrunken fold change
res <- lfcShrink(dds_filter, contrast = c("ob_ages", "12", "29"), type="normal")
# get a summary of the amount of significantly differentially expressed genes
summary(res_12_29, alpha = 0.05)
# write the results
writeOutput(res_12_29, dds_filter, "Olfactory_bulb_lfcShrink", c("12", "29"), dir)
```
P-value correction on 3 months vs 29 months. Doing this because p-val histogram is skewed to the right.
Clear out genes that were removed via independent filtering, clear out padj values, Re-estimate p-values using z-score
```{r}
# save these to append later
padj_save <- res_12_29[is.na(res_12_29$padj),]
pvalue_save <- padj_save[is.na(padj_save$pvalue),]
# remove genes filtered out by independent filtering
res_12_29 <- res_12_29[!is.na(res_12_29$padj),]
res_12_29 <- res_12_29[!is.na(res_12_29$pvalue),]
# remove all adjusted pvalues, will replace later
res_12_29 <- res_12_29[, -which(names(res_12_29) == "padj")]
# get z-scores_12_29 as input to fdrtool to re-estimte p-values
FDR.res_12_29 <- fdrtool(res_12_29$stat, statistic = "normal", plot = T)
# calculate new padj values using BH correction
res_12_29[, "padj"] <- p.adjust(FDR.res_12_29$pval, method = "BH")
# put new pvals in res_12_29 object
res_12_29$pvalue <- FDR.res_12_29$pval
# summary before binding
summary(res_12_29, alpha = 0.05)
# append the filtered out rows back on
res_12_29 <- rbind(res_12_29, padj_save)
res_12_29 <- rbind(res_12_29, pvalue_save)
```
Get padj values from re-estimated pvalues, plot new p-value distribution, and output. We see here that the p-value distribution is less skewed than before. We use these new results.
```{r}
# plot new p-value historgram
hist(res_12_29$pvalue, main = "P-value distribution 12 vs 29 months", xlab = "P-value", ylab = "Frequency", col = "blue")
# write the results
writeOutput(res_12_29, dds_filter, "Olfactory_bulb_lfcShrink_FDR_corrected", c("12", "29"), dir)
```
## 3 months vs 29 months
Using original model
```{r}
# Extract the 3 months vs 12 months result using an alpha threshold of 0.05
res_3_29 <- results(dds_filter, alpha = 0.05, name = "ob_ages_29_vs_3")
# p-value distribution histogram
hist(res_3_29$pvalue, main = "P-value distribution 3 months vs 29 months", xlab = "P-value", ylab = "Frequency", col = "lavender")
# get shrunken fold change
res <- lfcShrink(dds_filter, contrast = c("ob_ages", "3", "29"), type="normal")
# get a summary of the amount of significantly differentially expressed genes
summary(res_3_29, alpha = 0.05)
# write the results
#writeOutput(res_3_29, dds_filter, "Olfactory_bulb_lfcShrink", c("12", "29"), dir)
```
P-value correction on 3 months vs 29 months. Doing this because p-val histogram is skewed to the right.
Clear out genes that were removed via independent filtering, clear out padj values, Re-estimate p-values using z-score
```{r}
# save these to append later
padj_save <- res_3_29[is.na(res_3_29$padj),]
pvalue_save <- padj_save[is.na(padj_save$pvalue),]
# remove genes filtered out by independent filtering
res_3_29 <- res_3_29[!is.na(res_3_29$padj),]
res_3_29 <- res_3_29[!is.na(res_3_29$pvalue),]
# remove all adjusted pvalues, will replace later
res_3_29 <- res_3_29[, -which(names(res_3_29) == "padj")]
# get z-scores_3_29 as input to fdrtool to re-estimte p-values
FDR.res_3_29 <- fdrtool(res_3_29$stat, statistic = "normal", plot = T)
# calculate new padj values using BH correction
res_3_29[, "padj"] <- p.adjust(FDR.res_3_29$pval, method = "BH")
# put new pvals in res_3_29 object
res_3_29$pvalue <- FDR.res_3_29$pval
# summary before binding
summary(res_3_29, alpha = 0.05)
# append the filtered out rows back on
res_3_29 <- rbind(res_3_29, padj_save)
res_3_29 <- rbind(res_3_29, pvalue_save)
```
Get padj values from re-estimated pvalues, plot new p-value distribution, and output. We see here that the p-value distribution is less skewed than before. We use these new results.
```{r}
# plot new p-value historgram
hist(res_3_29$pvalue, main = "P-value distribution 3 vs 29 months", xlab = "P-value", ylab = "Frequency", col = "blue")
# write the results
writeOutput(res_3_29, dds_filter, "Olfactory_bulb_lfcShrink_FDR_corrected", c("3", "29"), dir)
```
# DESeq Time course analysis
Using the likelihood ratio test, we are able to test for genes which change significantly over the timecourse of the experiment. This will test whether the increase in the log likelihood from the additional coefficients in the time factor would be expected if those coefficients were equal to zero. If the adjusted p-value is small, then for the set of genes with those small adjusted p-values, the additional coefficient in full and not in reduced increased the log likelihood more than would be expected if their true value was zero. This is useful to get the genes which significantly vary over time. We use a reduced model here of ~1 where we remove the effects of time in order to compare against.
```{r}
ddsTC <- DESeq(dds_filter, test = "LRT", reduced = ~1)
```
Getting results for time-course data. These are any of the genes that were found to significantly vary over the time course of the experiment.
```{r}
resTC <- results(ddsTC, alpha = 0.05)
summary(resTC, alpha = 0.05)
writeOutput(resTC, ddsTC, "Olfactory_bulb", "LRT", dir)
```
Plotting gene with lowest padj value - It is Prokr2 which decreases with age
```{r}
# gene with lowest padj to plot
row.names(ddsTC)[which.min(resTC$padj)]
# extracting count data and variables for the most significant time course DE gene
dat <- plotCounts(ddsTC, which.min(resTC$padj),
intgroup = "ob_ages", returnData = TRUE, Normalized = TRUE)
# ordering from lowest to highest time point
dat <- dat[order(dat$ob_ages),]
ggplot(dat, aes(x = as.numeric(ob_ages), y = count)) +
geom_point() +
geom_smooth(se = FALSE, method = "loess") +
scale_y_continuous(trans = "log2")
```
Plot the 25 lowest genes with p-values.
```{r}
# getting the counts for the top 10 SDE genes
dat_10 <- melt(counts(ddsTC[head(order(resTC$padj), 25),], normalized = TRUE), id = row.names)
# adding a time variable to the dataframe, this has to be in the same order
dat_10$time <- factor(c(rep(c(3), each = 75), rep(c(12), each = 50), rep(c(29), each = 75)))
# reordering based on the time
dat_10 <- dat_10[order(dat_10$time),]
# setting the gene names to a factor, which will allow grouping
dat_10$Var1 <- as.factor(dat_10$Var1)
ggplot(dat_10, aes(x = time, y = value, color = Var1, group = Var1)) +
geom_point() +
geom_smooth(se = FALSE, method = "loess") +
scale_y_continuous(trans = "log1p") +
theme(legend.position="none")
```
4. Continuous changes in variability - creating model. Note that this model is confounded by the lack of sampling of different ages.
```{r}
# norammalized counts transformed to melted matrix
ob_counts <- counts(dds_filter, normalized = TRUE)
# fit a linear model for each gene and get residuals
ob_counts_lm <- list()
ob_ages_numeric <- c(3, 3, 3, 12, 12, 29, 29, 29)
for(gene in row.names(ob_counts)){
temp <- melt(ob_counts[gene,])
temp$age <- ob_ages_numeric
ob_counts_lm[[gene]] <- lm(value ~ age, data = temp)$residuals
}
ob_lm_residuals <- do.call(rbind, ob_counts_lm)
# plot residuals for all genes for each age
ob_lm_residuals_melt <- ob_lm_residuals
colnames(ob_lm_residuals_melt) <- ob_ages_numeric
ob_lm_residuals_melt <- melt(ob_lm_residuals_melt)
ggplot(ob_lm_residuals_melt, aes(x = Var2, y = log(value + 1))) +
geom_point() +
stat_smooth(method = "lm", col = "red") +
ggtitle("Residuals as a function of Age")
```
Calculate Spearman correlation between the absolute values of the residuals and age for each gene. Note that here spearman's correlation cannot calculate an exact p-value in the presence of rank ties. We can suppress this warning by using the 'exact = FALSE' parameter. Alternatively we can also use Kendall's Tau-b, which is able to handle ties. The tau-b statistic handles ties (i.e., both members of the pair have the same ordinal value) by a divisor term, which represents the geometric mean between the number of pairs not tied on x and the number not tied on y.
It appears that p-values here are binned and that they are not distributed as we would expect, which may warrant FDR correction. We also see that adjustment for multiple hypothesis testing drives all of our p-values very high.
Overall, there are no significant correlates of residuals with age after multiple hypothesis correction.
```{r}
# spearman change in variability with age
ob_var_spearman_list <- list()
for(gene in row.names(ob_lm_residuals)){
temp <- cor.test(x = abs(ob_lm_residuals[gene,]), y = ob_ages_numeric, method = "spearman", exact = FALSE)
ob_var_spearman_list[[gene]] <- c(temp$estimate, temp$p.value)
}
ob_var_spearman <- as.data.frame(do.call(rbind, ob_var_spearman_list))
# kendalls change in variability with age
ob_var_kendall_list <- list()
for(gene in row.names(ob_lm_residuals)){
temp <- cor.test(x = abs(ob_lm_residuals[gene,]), y = ob_ages_numeric, method = "kendall", exact = FALSE)
ob_var_kendall_list[[gene]] <- c(temp$estimate, temp$p.value)
}
ob_var_kendall <- as.data.frame(do.call(rbind, ob_var_kendall_list))
# multiple hypothesis correction
ob_var_spearman$padj <- p.adjust(ob_var_spearman[,2], method = "BH")
ob_var_kendall$padj <- p.adjust(ob_var_kendall[,2], method = "BH")
# distribution of p-values and padj
hist(ob_var_spearman$V2)
hist(ob_var_spearman$padj)
hist(ob_var_kendall$V2)
hist(ob_var_kendall$padj)
```
Distribution of spearman and kendall estimates and fit to normal distirbution. Neither fit a normal distribution.
```{r}
# spearman
hist(ob_var_spearman$rho)
shapiro.test(sample(ob_var_spearman$rho, size = 5000))
# kendall
hist(ob_var_kendall$tau)
shapiro.test(sample(ob_var_kendall$tau, size = 5000))
```
Check if residuals correlate with expression level. Significant but weak correlation.
```{r}
plot(ob_lm_residuals ~ ob_counts)
cor.test(x = ob_lm_residuals, y = ob_counts)
```
Significant differentially variable genes. None
```{r}
ob_var_spearman_sig <- ob_var_spearman[ob_var_spearman$padj < 0.05,]
ob_var_kendall_sig <- ob_var_kendall[ob_var_kendall$padj < 0.05,]
```
Grouped changes in variability - compare between 3 time points. Get interquartile range of gene expression for each gene within each time point across replicates. Get change of IQR by using fold change of IQR. Use wilcox test to test if fractions are different from zero for each gene. Generate null distribution of differences of IQR using bootstrapping. IQR corresponds to the difference between the 75th and 25th percentiles of the distribution and is considered to be a robust measure of variability, meaning it is not susceptible to outliers and departure from normality in the data.
change in variability = log2(IQR old/IQR young)
Get IQR for each gene within each time point normalized for expression level.
```{r}
# get IQR for each gene at each time point
ob_IQR_temp <- list()
for(gene in row.names(ob_counts)){
temp <- melt(ob_counts[gene,])
temp$age <- ob_ages_numeric
ob_IQR_temp[[gene]] <- c(IQR(subset(temp, age == 3)$value)/mean(subset(temp, age == 3)$value), IQR(subset(temp, age == 12)$value)/mean(subset(temp, age == 12)$value), IQR(subset(temp, age == 29)$value)/mean(subset(temp, age == 29)$value))
#quantile(x, 3/4) - quantile(x, 1/4)
}
ob_IQR <- as.data.frame(do.call(rbind, ob_IQR_temp))
colnames(ob_IQR) <- c(3,12,29)
# check if distirbutions are different from each other
wilcox.test(ob_IQR$`3`, ob_IQR$`12`)
wilcox.test(ob_IQR$`12`, ob_IQR$`29`)
wilcox.test(ob_IQR$`3`, ob_IQR$`29`)
# plot
ggplot(melt(ob_IQR), aes(x = log(value), color = variable)) +
geom_density(fill="white", alpha=0.5, position="identity")
ggplot(melt(ob_IQR), aes(x = log(value), color = variable)) +
geom_histogram(fill="white", alpha=0.5, position="identity")
```
calculated significance as a percentage of samples where IQRold was more extreme than IQRyoung and corrected it for multiple testing using FDR correction, q ≤ 0.05.
```{r}
# change in variability 3 vs 12
ob_IQR_3_12 <- as.data.frame(log2(ob_IQR$`12`/ob_IQR$`3`))
# bootstrapping to create null distribution
ob_IQR_3_12_null <- rep(NA, 10000)
ob_IQR_3_12_combined <- c(ob_IQR$`12`, ob_IQR$`3`)
for(x in 1:10000){
ob_IQR_3_12_null[x] <- log2(sample(ob_IQR_3_12_combined, replace = TRUE, size = 1)/sample(ob_IQR_3_12_combined, replace = TRUE, size = 1))
}
hist(ob_IQR_3_12_null)
# p-value
p <- rep(NA, length(ob_IQR_3_12[,1]))
for(x in 1:length(ob_IQR_3_12[,1])){
p[x] <- (sum(ob_IQR_3_12_null >= ob_IQR_3_12[x,1], na.rm = TRUE) + sum(ob_IQR_3_12_null <= -ob_IQR_3_12[x,1], na.rm = TRUE)) / 20000
}
ob_IQR_3_12$pval <- p
# adjusted p-value
ob_IQR_3_12$padj <- p.adjust(p, method = "BH")
# change in variability 12 vs 29
ob_IQR_12_29 <- as.data.frame(log2(ob_IQR$`29`/ob_IQR$`12`))
# bootstrapping to create null distribution
ob_IQR_12_29_null <- rep(NA, 10000)
ob_IQR_12_29_combined <- c(ob_IQR$`12`, ob_IQR$`29`)
for(x in 1:10000){
ob_IQR_12_29_null[x] <- log2(sample(ob_IQR_12_29_combined, replace = TRUE, size = 1)/sample(ob_IQR_12_29_combined, replace = TRUE, size = 1))
}
hist(ob_IQR_12_29_null)
# p-value
p <- rep(NA, length(ob_IQR_12_29[,1]))
for(x in 1:length(ob_IQR_12_29[,1])){
p[x] <- (sum(ob_IQR_12_29_null >= ob_IQR_12_29[x,1], na.rm = TRUE) + sum(ob_IQR_12_29_null <= -ob_IQR_12_29[x,1], na.rm = TRUE)) / 20000
}
ob_IQR_12_29$pval <- p
# adjusted p-value
ob_IQR_12_29$padj <- p.adjust(p, method = "BH")
# change in variability 3 vs 29
ob_IQR_3_29 <- as.data.frame(log2(ob_IQR$`29`/ob_IQR$`3`))
# bootstrapping to create null distribution
ob_IQR_3_29_null <- rep(NA, 10000)
ob_IQR_3_29_combined <- c(ob_IQR$`3`, ob_IQR$`29`)
for(x in 1:10000){
ob_IQR_3_29_null[x] <- log2(sample(ob_IQR_3_29_combined, replace = TRUE, size = 1)/sample(ob_IQR_3_29_combined, replace = TRUE, size = 1))
}
hist(ob_IQR_3_29_null)
# p-value
p <- rep(NA, length(ob_IQR_3_29[,1]))
for(x in 1:length(ob_IQR_3_29[,1])){
p[x] <- (sum(ob_IQR_3_29_null >= ob_IQR_3_29[x,1], na.rm = TRUE) + sum(ob_IQR_3_29_null <= -ob_IQR_3_29[x,1], na.rm = TRUE)) / 20000
}
ob_IQR_12_29$pval <- p
# adjusted p-value
ob_IQR_3_29$padj <- p.adjust(p, method = "BH")
```
Check if IQR correlates with expression level. There is a significant correlation but it is very small.
```{r}
ob_counts_avg <- data.frame("3" = rowMeans(ob_counts[,c(1:3)]), "12" = rowMeans(ob_counts[,c(4:5)]), "29" = rowMeans(ob_counts[,c(6:8)]))
ob_IQR_df <- as.data.frame(ob_IQR)
plot(melt(ob_IQR_df)$value ~ melt(ob_counts_avg)$value)
cor.test(x = melt(ob_IQR_df)$value, y = melt(ob_counts_avg)$value)
```
Significant differentially variable genes. None
```{r}
ob_IQR_3_12 <- ob_IQR_3_12[ob_IQR_3_12$padj < 0.05,]
ob_IQR_12_29 <- ob_IQR_12_29[ob_IQR_12_29$padj < 0.05,]
ob_IQR_3_29 <- ob_IQR_3_29[ob_IQR_3_29$padj < 0.05,]
```
# Gene set enrichment
```{r}
# get more info for each gene
```
Gene expression variability - here we are looking at the varibility between biological replicates. This means that we could be seeing differences because of different cell compositions in bulk tissue or if we assume cell composition is unchanged, this could be the dyssynchrony of the cells (within the same cell type) in the bulk sample.
Since we are using residuals or IQR to measure gene expression variability, this means that high variability means expression that is far from the predicted expression level. Biologically, this means unpredictability in expression at a specific age.
However, this was already tested on this data using cibersort, where cell composition was not found to be changing. If we have cells we could look at the variability between cells over time which would tell us about increased/decreased tissue heterogeneity throughout aging.
4. Continuous changes in variability - time continuous model. Create linear model of gene expression variability as a function of age. Run a spearman-correlation between the abs residuals and the age of samples. Then look at distribution of spearman coefficients. Finally see if there is a postivie correlation (or in which subset of genes) using wilcoxon test.
change in variability = spearman(abs(residuals), age)
5. Grouped changes in variability - compare between 3 time points. Get interquartile range of gene expression for each gene across 3 time points. Get change of IQR by using fractions of IQR. Use wilcox test to test if fractions are different from zero for each gene. Generate null distribution of residuals from young group (control) using bootstrapping to obtain p-value??? IQR corresponds to the difference between the 75th and 25th percentiles of the distribution and is considered to be a robust measure of variability, meaning it is not susceptible to outliers and departure from normality in the data
change in variability = (IQR old - IQR young)/IQR young
5.5. Check if expression variability is confounded by expression level (fisher's test). If so, transform data using voom.
6.1. Test for global changes in expression variability
6.2. Test for changes in expression variability at the gene level with multiple hypothesis corrections
7. Pathwya enrichment using GO and GSEA
8. correlation between the pathway membership of gene and its variability measure
|
51209fb6ff787243a281660cfe8d8d67e1e1bde8
|
[
"R",
"RMarkdown",
"Shell"
] | 5 |
R
|
rrcutler/Biostats_Final_Project_Spring_2019
|
daeb7844dcb3426471e7351563476c19eb2450ba
|
c5c30f89bb7aad706f1dea9103b06bdc594e6f96
|
refs/heads/master
|
<repo_name>BW-TEST-Org/summit-clone<file_sep>/docs/scatch-org-creation.md
# Setting up Summit Events App for Scratch org Development
This project is designed to use CumulusCI. So your first job is to make sure that you have the following installed on your development computer:
1. [Python 3+](https://www.python.org/downloads/)
2. [Git](https://git-scm.com/downloads)
3. [Salesforce Command Line Interface (CLI)](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm#sfdx_setup_install_cli)
4. [CumulusCI](https://cumulusci.readthedocs.io/en/latest/install.html#installing-cumulusci)
A complete set of general instructions on setting up CumulusCI can be found in the [CumulusCI Documentation](https://cumulusci.readthedocs.io/en/latest/tutorial.html).
## Connect a dev hub
1. [Enable Dev Hub in Your Org](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_enable_devhub.htm). This is used to authenticate your rights to spin up scratch orgs.
This should not effect anything in your org.
2. Connect your command line to the dev org you turned on. This will require you to log in to the org you identify as your dev hub. Use the following command to initiate this authentication:
```bash
sfdx force:auth:web:login --setdefaultdevhubusername --setalias my-hub-org
```
*"my-hub-org" above is an alias. You can choose whatever alias you wish as it is used to identify this
particular dev hub if you have multiple*
## Gitting the code (Get it?)
1. Log in to GitHub.
2. Go to the [Summit Events repository](https://summitevt.org).
3. Fork a copy of the repository to your own account by clicking the "Fork" button at the top of the
GitHub page. This will copy all the code from the repository into your personal account. Code in your
own repository will not affect the main repository in any way.
4. Navigate to your forked copy of the repository. The path at the top of the page should include your
GitHub username in it.
5. Click on the "Clone or download" green drop-down near the top left of the page. Copy the URL to clone
your forked repository.
6. On your computer navigate to the folder that you wish to put your cloned code in. Remember that
cloning will create a directory for the code for you. You may also wish to use GitHub desktop to
make this whole process prettier and less intimidating. This documentation will outline command
line usage of git, but both are acceptable.
1. Get a copy of the Event App code from GIT. If you are not directly collaborating with the
project you may want to fork the project into your own GIT repository:
```git
git clone <the URL you copied from your forked repository>
```
2. In your terminal, in the code directory check and see if the project is already
set up with CumulusCI:
```bash
cci project info
```
If the project is not set up you will get this message:
```bash
The file cumulusci.yml was not found in the repo root. Are you in a CumulusCI project directory?
```
If you get the above message use the following command to init the project into cumulusCI:
```bash
cci project init
```
3. Connect Github and and Cumulus to this project:
```bash
cci service connect github
```
## Spinning up a scratch or with the events app installed
1. Create a dev configured scratch org for 7 days
```bash
cci org scratch dev <org_name> --days 7
```
2. Confirm your dev configured scratch org was created
```bash
cci org list
```
3. Run a flow to deploy the project and install dependencies into your dev configured scratch org
```bash
cci flow run dev_org --org <org_name>
```
Normally you would be done with a cumulusCI project scratch org at this point, but the Event app requires a salesforce site domain
be set up. You will need to do this in the next step and then run one final command to complete the site set up.
## Create a site
1. Open your new scratch org you are working on in the browser
```bash
cci org browser <org_name>
```
*<org_name> for development is dev*
2. In Setup go to User Interface -> Sites and Domains -> Sites
3. Select a subdomain that is available. Since you are spinning up scratch orgs you may want to start incrementing a subdomain on a theme (myevents0001...myevents0002).
4. Click "Register My Salesforce Site Domain"
## Automated site set-up
Back in the command line. Use the following command to allow CumulusCI to complete the set-up of the public site:
```bash
cci flow run config_site --org <org_name>
```
*<org_name> for development is dev*
## Set Sharing Rules
Salesforce Winter '20 and Spring '20 releases will begin to severely limit Guest User access to objects.
Sharing rules will limit the Guest User to insert access only by default. The Summit Events application requires
that the Guest user be able to read, and upsert to it's custom objects. In order to align this application with
the new security rules we need to set a sharing rule to allow the application to read it's objects. Code has also
been adjust to allow for the required upserts. The following instructions will help you set up the required sharing rules.
Unfortunately, we are not able to automate these steps yet due to limitations in SFDX.
### Set Sharing Object Access
1. Open your new scratch org you are working on in the browser (if it is not already open)
```bash
cci org browser <org_name>
```
*<org_name> for development is dev*
2. Go to Setup in your scratch org
3. Type "Sharing" in the quick-find box and click on "Sharing Settings".
4. Click "Edit" to expose sharing option settings for editing
5. Set the Summit Events object and make sure it is set to "Public Read/Write"
6. Make sure the "Secure guest user record access" is also checked. This will be checked by default in the future and will soon not be optional.
7. Click "Save" (You will get an alert. Click "Ok")
### Set Summit Events Sharing Rule
1. Follow setups 1-3 in the instructions above to get into "Sharing Settings"
2. Find the "Summit Events Sharing Rules" section of the page (you can use the "Manage sharing settings for" dropdown on the top or scroll to it)
3. Click the "New" button in the "Summit Events Sharing Rules" section
4. Label your rule "Guest User Read Access" with rule name "Guest_User_Read_Access"
5. Set the radio button for "Rule Type" to "Guest user access, based on criteria"
6. Set "Criteria" to Field => Event Name, Operator => "not equal to", Value => null (type the world null for the value)
7. Share with can only be set to "Summit Events Site Guest User"
8. Set Access Level to "Read Only"
9. Click "Save"
## Your org is ready!
Your new scratch org is created and ready for you to develop against/with/for! Remember you can open your org with this command once it has been created:
```bash
cci org browser <org_name>
```
<file_sep>/docs/set-up.md
# Setting up Summit Events app in salesforce
## Create a site
If your org does not already have a site to display public visual force pages you will need to set one up.
1. Open the org you are working on in the browser
```bash
cci org browser <org_name>
```
2. In Setup go to User Interface -> Sites and Domains -> Sites
3. Select a subdomain that is available. Since you are spinning up scratch orgs you may want to start incrementing a subdomain on a theme (myevents0001...myevents0002).
4. Click "Register My Salesforce Site Domain"
For **production environments** you may want to manually set up your org to finely tune your permissions and sites. Use the following instructions.
## Create a site
After the subdomain is finished registering create a new site record, by clicking the "New" button next to the site header. Fill in the following data and then click "Save."
1. In Setup go to User Interface -> Sites and Domains -> Sites
2. Click the "New" button next to the site header
3. Enter the following data in the form
* Site Label: Summit Events
* Site Name: Summit_Events
* Active Site Home Page:
* Select the magnifying glass look-up icon and in the dialog select SummitEvents
* Leave all other settings at their defaults
4. Click "Save"
5. Click the "Active" link under Action next to the site you just created
6. Right click on the site URL and copy the URL to your clipboard. You will need it in the next stage of installation.
## Set Custom Settings
Since each installation can have a different site URL we need to define that URL for the event application to use as it's root web presence. This is used for feed URLs for external sites to access and a host of other things.
1. In Setup go to User Custom Code -> Custom Settings
2. Click on the "Manage" link for the custom setting "Summit Events Settings"
3. Click "New" button just before the "Default Organization Level Value." There are two "New" buttons on the page. You will know you are on the wrong one if you are asked to assign a user or a profile. You should only need to enter the URL in the follow step.
4. From step 6 in the "Create a site record" use the URL you copied there and enter it into the Community Based URL field.
5. Click "Save"
6. Once you hit "Save" the "New" button will be replaced with "Edit." This is what you will need to hit to make future adjustments to this setting.
## Set Sharing Rules
Salesforce winter '20 and Spring '20 releases will begin to severely limit Guest User access to objects.
Sharing rules will limit the Guest User to insert access only by default. The Summit Events application requires
that the Guest user be able to read, and upsert to it's custom objects. In order to align this application with
the new security rules we need to set a sharing rule to allow the application to read it's objects. Code has also
been adjust to allow for the required upserts. The following instructions will help you set up the required sharing rules.
Unfortunately, we are not able to automate these steps yet due to limitations in SFDX.
### Set Sharing Object Access
1. Open your new scratch org you are working on in the browser (if it is not already open)
```bash
cci org browser <org_name>
```
*<org_name> for development is dev*
2. Go to Setup in your scratch org
3. Type "Sharing" in the quick-find box and click on "Sharing Settings".
4. Click "Edit" to expose sharing option settings for editing
5. Set the Summit Events object and make sure it is set to "Public Read/Write"
6. Make sure the "Secure guest user record access" is also checked. This will be checked by default in the future and will soon not be optional.
7. Click "Save" (You will get an alert. Click "Ok")
### Set Summit Events Sharing Rule
1. Follow setups 1-3 in the instructions above to get into "Sharing Settings"
2. Find the "Summit Events Sharing Rules" section of the page (you can use the "Manage sharing settings for" dropdown on the top or scroll to it)
3. Click the "New" button in the "Summit Events Sharing Rules" section
4. Label your rule "Guest User Read Access" with rule name "Guest_User_Read_Access"
5. Set the radio button for "Rule Type" to "Guest user access, based on criteria"
6. Set "Criteria" to Field => Event Name, Operator => "not equal to", Value => null (type the world null for the value)
7. Share with can only be set to "Summit Events Site Guest User"
8. Set Access Level to "Read Only"
9. Click "Save"
## Apply Permission Sets
There are two permission sets tracked in this application. These permission sets can be applied
**Summit Events Admin**:
Apply to admin users that need to create and maintain events.
**Summit Events Registrant**: Needs to be applied to the Guest User of your site for public access to registration forms.
#### Apply Summit Events Registrant premission set to the Guest User of your site
1. Go to Sites in Setup
2. Click on the name of the site that you want to affect.
3. Click on the "Public Access Button" at the top of the site definition page
4. On the site details page click on the "View Users"
5. On the user list find your guest user and click on the name of that user
6. Go to Permission Set Assignment and assign Ust Event Registrant permission set
<file_sep>/datasets/dev/data.sql
BEGIN TRANSACTION;
CREATE TABLE "Account"
(
sf_id VARCHAR(255) NOT NULL,
"Name" VARCHAR(255),
"RecordTypeId" VARCHAR(255),
parent_id VARCHAR(255),
hed__current_address__c VARCHAR(255),
hed__primary_contact__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
CREATE TABLE "Account_rt_mapping"
(
record_type_id VARCHAR(18) NOT NULL,
developer_name VARCHAR(255),
PRIMARY KEY (record_type_id)
);
CREATE TABLE "Contact"
(
sf_id VARCHAR(255) NOT NULL,
"FirstName" VARCHAR(255),
"LastName" VARCHAR(255),
"DoNotCall" VARCHAR(255),
"Do_Not_Text__c" VARCHAR(255),
"Foot_On_Campus__c" VARCHAR(255),
"HasOptedOutOfEmail" VARCHAR(255),
"HasOptedOutOfFax" VARCHAR(255),
"Initial_Foot_on_Campus__c" VARCHAR(255),
"Last_Time_on_Campus__c" VARCHAR(255),
"Personal_Email__c" VARCHAR(255),
"Preferred_Class_Year__c" VARCHAR(255),
"Preferred_First_Name__c" VARCHAR(255),
"Previous_Last_Name__c" VARCHAR(255),
"Special_Athlete_Sport_1__c" VARCHAR(255),
"Special_Athlete_Sport_2__c" VARCHAR(255),
"Special_Athlete_Sport_3__c" VARCHAR(255),
"University_Banner_PIDM__c" VARCHAR(255),
"hed__AlternateEmail__c" VARCHAR(255),
"hed__Chosen_Full_Name__c" VARCHAR(255),
"hed__Citizenship__c" VARCHAR(255),
"hed__Country_of_Origin__c" VARCHAR(255),
"hed__Deceased__c" VARCHAR(255),
"hed__Do_Not_Contact__c" VARCHAR(255),
"hed__Dual_Citizenship__c" VARCHAR(255),
"hed__Ethnicity__c" VARCHAR(255),
"hed__Exclude_from_Household_Formal_Greeting__c" VARCHAR(255),
"hed__Exclude_from_Household_Informal_Greeting__c" VARCHAR(255),
"hed__Exclude_from_Household_Name__c" VARCHAR(255),
"hed__FERPA__c" VARCHAR(255),
"hed__Financial_Aid_Applicant__c" VARCHAR(255),
"hed__Gender__c" VARCHAR(255),
"hed__HIPAA_Detail__c" VARCHAR(255),
"hed__HIPAA__c" VARCHAR(255),
"hed__Military_Background__c" VARCHAR(255),
"hed__Military_Service__c" VARCHAR(255),
"hed__Naming_Exclusions__c" VARCHAR(255),
"hed__PreferredPhone__c" VARCHAR(255),
"hed__Preferred_Email__c" VARCHAR(255),
"hed__Primary_Address_Type__c" VARCHAR(255),
"hed__Race__c" VARCHAR(255),
"hed__Religion__c" VARCHAR(255),
"hed__Secondary_Address_Type__c" VARCHAR(255),
"hed__Social_Security_Number__c" VARCHAR(255),
"hed__UniversityEmail__c" VARCHAR(255),
"hed__WorkEmail__c" VARCHAR(255),
"hed__WorkPhone__c" VARCHAR(255),
"hed__is_Address_Override__c" VARCHAR(255),
account_id VARCHAR(255),
primary_academic_program__c VARCHAR(255),
primary_department__c VARCHAR(255),
primary_educational_institution__c VARCHAR(255),
primary_sports_organization__c VARCHAR(255),
reports_to_id VARCHAR(255),
hed__current_address__c VARCHAR(255),
hed__primary_household__c VARCHAR(255),
hed__primary_language__c VARCHAR(255),
hed__primary_organization__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
CREATE TABLE "Summit_Events_Appointment_Type__c"
(
sf_id VARCHAR(255) NOT NULL,
"Appointment_Category__c" VARCHAR(255),
"Appointment_Limits__c" VARCHAR(255),
"Appointment_Type_Status__c" VARCHAR(255),
"Appointment_Type__c" VARCHAR(255),
"Auto_Add_Time__c" VARCHAR(255),
"Auto_Confirm_Appointment__c" VARCHAR(255),
"Auto_add_building__c" VARCHAR(255),
"Chosen_State__c" VARCHAR(255),
"Custom_Picklist__c" VARCHAR(255),
"Date_Available_End__c" VARCHAR(255),
"Date_Available_Start__c" VARCHAR(255),
"Day_of_Week_Availability__c" VARCHAR(255),
"Description__c" VARCHAR(255),
"Do_Not_Show_Time__c" VARCHAR(255),
"Registrant_Input__c" VARCHAR(255),
"Required_Appointment__c" VARCHAR(255),
"Sort_Order__c" VARCHAR(255),
"Title__c" VARCHAR(255),
restrict_to_instance_title__c VARCHAR(255),
summit_events__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
INSERT INTO "Summit_Events_Appointment_Type__c"
VALUES ('a0T1h000002M7cEEAS', '', '1', 'Active', '', '', 'false', '', '', '', '', '', '',
'Get yourself some quite time in our library.', 'false', '', 'false', '1.0', 'Demo Appointment 0 - Quite time',
'', 'a0a1h0000043zr3AAA');
INSERT INTO "Summit_Events_Appointment_Type__c"
VALUES ('a0T1h000002M7cFEAS', '', '1', 'Active', '', '', 'true', '', '', '', '', '', '', 'There is such a thing!',
'false', '', 'false', '30.0', 'Demo Appointment 3 - Free Lunch', '', 'a0a1h0000043zr3AAA');
INSERT INTO "Summit_Events_Appointment_Type__c"
VALUES ('a0T1h000002M7cGEAS', '', '1', 'Active', '', '', 'false', '', '', 'Chocolate
Vanilla
Strawberry
Lactose Free', '', '', '', 'Choose the ice cream you could prefer to consume during your visit', 'false',
'Custom pick list', 'false', '10.0', 'Demo Appointment 1 - Ice Cream with Counselor', '', 'a0a1h0000043zr3AAA');
INSERT INTO "Summit_Events_Appointment_Type__c"
VALUES ('a0T1h000002M7cHEAS', '', '2', 'Active', '', '', 'false', '', '', '', '', '', '',
'What is your definition of the meaning of life?', 'false', 'Required text box', 'false', '20.0',
'Demo Appointment 2 - Meaning of life', '', 'a0a1h0000043zr3AAA');
CREATE TABLE "Summit_Events_Appointments__c"
(
sf_id VARCHAR(255) NOT NULL,
"Appointment_Category__c" VARCHAR(255),
"Appointment_Contact_Email__c" VARCHAR(255),
"Appointment_Contact_Name__c" VARCHAR(255),
"Appointment_Date_Time__c" VARCHAR(255),
"Appointment_Date__c" VARCHAR(255),
"Appointment_Detail__c" VARCHAR(255),
"Appointment_Status__c" VARCHAR(255),
"Appointment_Time_Options__c" VARCHAR(255),
"Appointment_Time__c" VARCHAR(255),
"Appointment_Title__c" VARCHAR(255),
"Appointment_Type__c" VARCHAR(255),
"Building__c" VARCHAR(255),
"Chosen_State__c" VARCHAR(255),
"Class_Title__c" VARCHAR(255),
"Client_Created_Appointment__c" VARCHAR(255),
"Description__c" VARCHAR(255),
"Do_Not_Show_Time__c" VARCHAR(255),
"Faculty_Staff_Member__c" VARCHAR(255),
"Registrant_Input__c" VARCHAR(255),
"Room__c" VARCHAR(255),
"Sort_Order__c" VARCHAR(255),
event_appointment_type__c VARCHAR(255),
event_host__c VARCHAR(255),
event_registration__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
CREATE TABLE "Summit_Events_Email__c"
(
sf_id VARCHAR(255) NOT NULL,
"Action_Status__c" VARCHAR(255),
"Action_Sub_status__c" VARCHAR(255),
"BCC_Email__c" VARCHAR(255),
"Email_Content_Instructions__c" VARCHAR(255),
"Email_Content__c" VARCHAR(255),
"Email_From__c" VARCHAR(255),
"Email_Subject__c" VARCHAR(255),
"Letterhead_HTML__c" VARCHAR(255),
"Letterhead_Id__c" VARCHAR(255),
"Letterhead_Name__c" VARCHAR(255),
"Letterhead__c" VARCHAR(255),
"Org_Email_Id__c" VARCHAR(255),
"Org_Email__c" VARCHAR(255),
event__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
CREATE TABLE "Summit_Events_Host__c"
(
sf_id VARCHAR(255) NOT NULL,
"Additional_Comments__c" VARCHAR(255),
"Assigned__c" VARCHAR(255),
"Building__c" VARCHAR(255),
"Course_Name__c" VARCHAR(255),
"Department__c" VARCHAR(255),
"First_Name__c" VARCHAR(255),
"Gender__c" VARCHAR(255),
"Last_Name__c" VARCHAR(255),
"Location__c" VARCHAR(255),
"Max_Available__c" VARCHAR(255),
"Preferred_Title__c" VARCHAR(255),
"RecordTypeId" VARCHAR(255),
"Time__c" VARCHAR(255),
"Undergrad_Major__c" VARCHAR(255),
contact__c VARCHAR(255),
event_instance__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
CREATE TABLE "Summit_Events_Host__c_rt_mapping"
(
record_type_id VARCHAR(18) NOT NULL,
developer_name VARCHAR(255),
PRIMARY KEY (record_type_id)
);
CREATE TABLE "Summit_Events_Instance__c"
(
sf_id VARCHAR(255) NOT NULL,
"Active_Status__c" VARCHAR(255),
"Alternate_Registration_URL_Override__c" VARCHAR(255),
"Attendee_List__c" VARCHAR(255),
"Building_Override__c" VARCHAR(255),
"Capacity__c" VARCHAR(255),
"Category__c" VARCHAR(255),
"Feed_Registration_Button_Text_Override__c" VARCHAR(255),
"Instance_End_Date__c" VARCHAR(255),
"Instance_End_Time__c" VARCHAR(255),
"Instance_Short_Description__c" VARCHAR(255),
"Instance_Start_Date__c" VARCHAR(255),
"Instance_Start_Time__c" VARCHAR(255),
"Instance_Time_Zone__c" VARCHAR(255),
"Instance_Title__c" VARCHAR(255),
"Location_Address_Override__c" VARCHAR(255),
"Location_Map_Link_Override__c" VARCHAR(255),
"Location_Title_Override__c" VARCHAR(255),
"Location_Type_Override__c" VARCHAR(255),
"Private_Instance__c" VARCHAR(255),
event__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
INSERT INTO "Summit_Events_Instance__c"
VALUES ('a0X1h000003BjOTEA0', 'Active', '', 'false', '', '100.0', '', '', date('now', '+7 day'), '15:30:00.000Z',
'A short description', date('now', '+7 day'), '08:00:00.000Z', 'Central Daylight Time (America/Chicago)', '',
'', '', '', '', 'false', 'a0a1h0000043zr3AAA');
INSERT INTO "Summit_Events_Instance__c"
VALUES ('a0X1h000003BjOUEA0', 'Active', '', 'false', '', '100.0', '', '', date('now', '+14 day'), '13:15:00.000Z',
'A short description', date('now', '+14 day'), '09:00:00.000Z', 'Central Daylight Time (America/Chicago)',
'A special Title', '', '', '', '', 'false', 'a0a1h0000043zr3AAA');
CREATE TABLE "Summit_Events_Registration__c"
(
sf_id VARCHAR(255) NOT NULL,
"Actual_Number_of_Guests__c" VARCHAR(255),
"Add_Info_Answer_1__c" VARCHAR(255),
"Add_Info_Answer_2__c" VARCHAR(255),
"Add_Info_Answer_3__c" VARCHAR(255),
"Add_Info_Answer_4__c" VARCHAR(255),
"Add_Info_Answer_5__c" VARCHAR(255),
"Appointment_Table__c" VARCHAR(255),
"Campus_Tour_Location__c" VARCHAR(255),
"Campus_Tour_Time__c" VARCHAR(255),
"Confirmation_Call_Result__c" VARCHAR(255),
"Date_All_Appointments_Confirmed_del__c" VARCHAR(255),
"Display_Attendance_Publicly__c" VARCHAR(255),
"Event_Instance_Date_Time_Formatted__c" VARCHAR(255),
"Event_Registration_Requested_Date__c" VARCHAR(255),
"Generated_Itinerary__c" VARCHAR(255),
"Generated_Requested_Appointments__c" VARCHAR(255),
"Last_Name_as_Student__c" VARCHAR(255),
"Matching_Log__c" VARCHAR(255),
"New_Contact_Created__c" VARCHAR(255),
"Number_of_Guests__c" VARCHAR(255),
"Participation_Type__c" VARCHAR(255),
"Preferred_Class_Year__c" VARCHAR(255),
"Preferred_Visit_Time__c" VARCHAR(255),
"Presentation_Location__c" VARCHAR(255),
"Presentation_Time__c" VARCHAR(255),
"Registrant_Applicant_Type__c" VARCHAR(255),
"Registrant_City__c" VARCHAR(255),
"Registrant_College_Code__c" VARCHAR(255),
"Registrant_College_Not_Found__c" VARCHAR(255),
"Registrant_College_Year__c" VARCHAR(255),
"Registrant_College__c" VARCHAR(255),
"Registrant_Country__c" VARCHAR(255),
"Registrant_Date_of_Birth__c" VARCHAR(255),
"Registrant_Do_Not_Call__c" VARCHAR(255),
"Registrant_Email__c" VARCHAR(255),
"Registrant_First_Name__c" VARCHAR(255),
"Registrant_Gender__c" VARCHAR(255),
"Registrant_High_School_Code__c" VARCHAR(255),
"Registrant_High_School_Grad_Year__c" VARCHAR(255),
"Registrant_High_School_Not_Found__c" VARCHAR(255),
"Registrant_High_School__c" VARCHAR(255),
"Registrant_Last_Name__c" VARCHAR(255),
"Registrant_Mobile_Phone__c" VARCHAR(255),
"Registrant_Other_Email__c" VARCHAR(255),
"Registrant_Other_First_Name__c" VARCHAR(255),
"Registrant_Other_Last_Name__c" VARCHAR(255),
"Registrant_Other_Phone__c" VARCHAR(255),
"Registrant_Other_Relationship__c" VARCHAR(255),
"Registrant_Parent_Email__c" VARCHAR(255),
"Registrant_Parent_First_Name__c" VARCHAR(255),
"Registrant_Parent_Last_Name__c" VARCHAR(255),
"Registrant_Parent_Phone__c" VARCHAR(255),
"Registrant_Phone__c" VARCHAR(255),
"Registrant_Postal_Code__c" VARCHAR(255),
"Registrant_Preferred_First_Name__c" VARCHAR(255),
"Registrant_Program_Interest__c" VARCHAR(255),
"Registrant_Receive_Texts__c" VARCHAR(255),
"Registrant_State_Global__c" VARCHAR(255),
"Registrant_State_Province__c" VARCHAR(255),
"Registrant_State__c" VARCHAR(255),
"Registrant_Street_1__c" VARCHAR(255),
"Registrant_Street_2__c" VARCHAR(255),
"Registrant_Third_Party_Status__c" VARCHAR(255),
"Registrant_Zip__c" VARCHAR(255),
"Relationship_To_Institution__c" VARCHAR(255),
"Reminder_Call_Complete__c" VARCHAR(255),
"Session__c" VARCHAR(255),
"Status__c" VARCHAR(255),
"Substatus__c" VARCHAR(255),
contact__c VARCHAR(255),
event_instance__c VARCHAR(255),
event__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
CREATE TABLE "Summit_Events__c"
(
sf_id VARCHAR(255) NOT NULL,
"Name" VARCHAR(255),
"Academic_Program_List_Selected__c" VARCHAR(255),
"Academic_Program_List__c" VARCHAR(255),
"Academic_Program_Selected__c" VARCHAR(255),
"Add_Info_Question_Pick_List_1__c" VARCHAR(255),
"Add_Info_Question_Pick_List_2__c" VARCHAR(255),
"Add_Info_Question_Pick_List_3__c" VARCHAR(255),
"Add_Info_Question_Pick_List_4__c" VARCHAR(255),
"Add_Info_Question_Pick_List_5__c" VARCHAR(255),
"Add_Info_Question_Text_1__c" VARCHAR(255),
"Add_Info_Question_Text_2__c" VARCHAR(255),
"Add_Info_Question_Text_3__c" VARCHAR(255),
"Add_Info_Question_Text_4__c" VARCHAR(255),
"Add_Info_Question_Text_5__c" VARCHAR(255),
"Add_Info_Question_Type_1__c" VARCHAR(255),
"Add_Info_Question_Type_2__c" VARCHAR(255),
"Add_Info_Question_Type_3__c" VARCHAR(255),
"Add_Info_Question_Type_4__c" VARCHAR(255),
"Add_Info_Question_Type_5__c" VARCHAR(255),
"Allow_Other_Attendees__c" VARCHAR(255),
"Alternate_Registration_URL__c" VARCHAR(255),
"Ask_Applicant_Type__c" VARCHAR(255),
"Ask_Date_Of_Birth__c" VARCHAR(255),
"Ask_Gender__c" VARCHAR(255),
"Ask_If_Parent__c" VARCHAR(255),
"Ask_Last_Name_As_Student__c" VARCHAR(255),
"Ask_Mailing_Address__c" VARCHAR(255),
"Ask_Phone__c" VARCHAR(255),
"Ask_Preferred_Class_Year__c" VARCHAR(255),
"Ask_Preferred_First_Name__c" VARCHAR(255),
"Ask_Registrant_Program_Of_Interest__c" VARCHAR(255),
"Ask_Relationship_To_Institution__c" VARCHAR(255),
"Ask_Third_Party_Registrant__c" VARCHAR(255),
"Audience__c" VARCHAR(255),
"Building__c" VARCHAR(255),
"Close_Event_Days_Before__c" VARCHAR(255),
"College_High_School_Ask__c" VARCHAR(255),
"Contact_Creation__c" VARCHAR(255),
"Contact_Matching_Rules__c" VARCHAR(255),
"End_Date__c" VARCHAR(255),
"Event_Appointment_Description__c" VARCHAR(255),
"Event_Appointment_Title__c" VARCHAR(255),
"Event_Cancel_Review_Description__c" VARCHAR(255),
"Event_Cancel_Review_Title__c" VARCHAR(255),
"Event_Cancelled_Notification_Text__c" VARCHAR(255),
"Event_Confirmation_Description__c" VARCHAR(255),
"Event_Confirmation_Title__c" VARCHAR(255),
"Event_Footer__c" VARCHAR(255),
"Event_Full_Text__c" VARCHAR(255),
"Event_Home_Link_Title__c" VARCHAR(255),
"Event_Home_Link_URL__c" VARCHAR(255),
"Event_Name__c" VARCHAR(255),
"Event_Short_Listing_Description__c" VARCHAR(255),
"Event_Sponsor__c" VARCHAR(255),
"Event_Status__c" VARCHAR(255),
"Event_Submit_Description__c" VARCHAR(255),
"Event_Submit_Title__c" VARCHAR(255),
"Event_Type__c" VARCHAR(255),
"Event_description__c" VARCHAR(255),
"Feed_Registration_Button_Text__c" VARCHAR(255),
"Hand_Raise_Action__c" VARCHAR(255),
"Include_Time_frame_List__c" VARCHAR(255),
"Location_Address__c" VARCHAR(255),
"Location_Map_Link__c" VARCHAR(255),
"Location_Title__c" VARCHAR(255),
"Location_Type__c" VARCHAR(255),
"Max_Other_Attendees__c" VARCHAR(255),
"Private_Event__c" VARCHAR(255),
"Program_Filter_2__c" VARCHAR(255),
"Program_Filter_3__c" VARCHAR(255),
"Program_Filter__c" VARCHAR(255),
"Registration_Email_Restriction__c" VARCHAR(255),
"Start_Date__c" VARCHAR(255),
"Template__c" VARCHAR(255),
"Tracking_Cancel_Registration__c" VARCHAR(255),
"Tracking_Confirmation_Registration__c" VARCHAR(255),
"Tracking_Event_Registration__c" VARCHAR(255),
"Tracking_Options_Registration__c" VARCHAR(255),
"Tracking_Submit_Registration__c" VARCHAR(255),
PRIMARY KEY (sf_id)
);
INSERT INTO "Summit_Events__c"
VALUES ('a0a1h0000043zr3AAA', 'Test Event', '', '', '', 'Red
Yellow
Green
Blue', '', '', '', '', 'What is your favorite color?', 'What''s up?', 'What''s your favorite day of the week?', '', '',
'Pick-list', 'Text area', 'Text box required', '', '', 'true', '', 'Do not ask', 'Do not ask', 'Do not ask',
'true', 'Do not ask', 'Ask', 'Ask with type require', 'Do not ask', 'Do not ask', 'Ask but do not require', 'Do not ask', 'Parent/Guardian;Other',
'General Public', '', '0.0', 'Don''t ask',
'Full matching contact creation with duplicate management', 'Matching rules 1', '2020-05-16',
'Body text for the appointment/options page explains what these appointments are about.',
'This is the header of the appointment/options page.', 'What does it mean to cancel a event.',
'Online Cancel of Registration Heading', 'The event has been cancelled.',
'Explain the registration has been received from the client at this point and is complete',
'Registration has been received title.', 'This footer appears on every event registration page in the footer.',
'Explain here that the event has reached capacity and is closed.', 'Event Home', '', 'Test Event',
'This description appears in feed and should be concise', '', 'Active',
'Description of submission being the final act in the registration play.', 'Heading for the Submit Page',
'Admissions Event',
'<p><strong>Rich Text</strong> description of the event that appears on the first registration page.</p>',
'Register', 'Touchpoint', 'false', '123 Evergreen Blvd., St. Paul, MN', 'https://g.page/sociablecider?share',
'The best place in the World', '', '5.0', 'false', '', '', '', 'No limit', '2020-03-17', 'GeneralSLDS', '', '',
'', '', '');
CREATE TABLE "hed__Address__c"
(
sf_id VARCHAR(255) NOT NULL,
"hed__Address_Type__c" VARCHAR(255),
"hed__Default_Address__c" VARCHAR(255),
"hed__Latest_End_Date__c" VARCHAR(255),
"hed__Latest_Start_Date__c" VARCHAR(255),
"hed__MailingCity__c" VARCHAR(255),
"hed__MailingCountry__c" VARCHAR(255),
"hed__MailingPostalCode__c" VARCHAR(255),
"hed__MailingState__c" VARCHAR(255),
"hed__MailingStreet2__c" VARCHAR(255),
"hed__MailingStreet__c" VARCHAR(255),
"hed__Seasonal_End_Day__c" VARCHAR(255),
"hed__Seasonal_End_Month__c" VARCHAR(255),
"hed__Seasonal_End_Year__c" VARCHAR(255),
"hed__Seasonal_Start_Day__c" VARCHAR(255),
"hed__Seasonal_Start_Month__c" VARCHAR(255),
"hed__Seasonal_Start_Year__c" VARCHAR(255),
hed__parent_account__c VARCHAR(255),
hed__parent_contact__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
CREATE TABLE "hed__Facility__c"
(
sf_id VARCHAR(255) NOT NULL,
"Name" VARCHAR(255),
"hed__Capacity__c" VARCHAR(255),
"hed__Description__c" VARCHAR(255),
"hed__Facility_Type__c" VARCHAR(255),
hed__account__c VARCHAR(255),
hed__parent_facility__c VARCHAR(255),
PRIMARY KEY (sf_id)
);
CREATE TABLE "hed__Language__c"
(
sf_id VARCHAR(255) NOT NULL,
"Name" VARCHAR(255),
PRIMARY KEY (sf_id)
);
COMMIT;
<file_sep>/force-app/main/default/staticresources/SummitEventsAssets/js/options.js
// SummitEventsRegistrationOptionScripts
var appointmentsReady = (callback) => {
if (document.readyState != "loading") callback();
else document.addEventListener("DOMContentLoaded", callback);
}
appointmentsReady(() => {
//Initialize accordion toggles.
let accordionHeads = document.querySelectorAll(".slds-accordion__summary-heading");
accordionHeads.forEach(function (ab) {
ab.addEventListener("click", function (e) {
e.preventDefault();
let section = ab.closest('.appointment');
if (section.classList.contains('slds-is-open')) {
section.classList.remove('slds-is-open')
} else {
section.classList.add('slds-is-open')
}
});
});
let chooser = document.querySelector("#chooser");
let chosen = document.getElementById("chosen");
//Initiate remove buttons that already exist
let chosenRemoveButtons = chosen.querySelectorAll('.appointmentRemove');
chosenRemoveButtons.forEach(function (removeBtn) {
removeBtn.addEventListener('click', function () {
removeSelectedOption(removeBtn);
});
});
//Initiate add buttons in chooser column
let allApptAddButtons = chooser.querySelectorAll(".appointmentAdd");
allApptAddButtons.forEach(function (apptButton) {
apptButton.addEventListener("click", (addAppt) => {
addAppt.preventDefault();
let Appt = apptButton.closest(".appointment");
//check for required fields
let error = false;
let requiredInputs = Appt.querySelectorAll('.slds-is-required');
requiredInputs.forEach(function (reqs) {
let reqAppt = reqs.closest(".appointment");
let incomingValue = '';
if (reqAppt.querySelector(".appointmentType")) {
let selType = Appt.querySelector(".appointmentType");
incomingValue = selType.options[selType.selectedIndex].value;
}
if (reqAppt.querySelector(".appointmentCustomInput")) {
let inputType = Appt.querySelector(".appointmentCustomInput");
incomingValue = inputType.value;
}
if (!incomingValue) {
reqAppt.classList.add('slds-has-error');
error = true;
}
});
if (!error) {
//move and adjust data
let chosenArea = document.getElementById("chosen");
let limit = Appt.dataset.limit;
addAppt = document.createElement('div');
addAppt.classList.add('slds-box', 'slds-box_small', 'slds-m-vertical_x-small', 'appointmentChosen');
Object.assign(addAppt.dataset, Appt.dataset);
let appTitle = document.createElement('p');
addAppt.classList.add('appointmentTitle', 'slds-text-body');
let findTitle = Appt.querySelector(".appointmentTitle");
appTitle.textContent = findTitle.textContent;
addAppt.append(appTitle);
let desc = '';
if (Appt.querySelector(".appointmentType")) {
let selType = Appt.querySelector(".appointmentType");
desc += selType.options[selType.selectedIndex].value;
}
if (Appt.querySelector(".appointmentCustomInput")) {
let inputType = Appt.querySelector(".appointmentCustomInput");
desc += inputType.value;
}
if (desc) {
let apptDesc = document.createElement('p');
apptDesc.classList.add('appointmentDesc', 'slds-text-body', 'slds-p-vertical_xx-small');
apptDesc.textContent = desc;
addAppt.append(apptDesc);
}
//Create the remove button
let removeButton = document.createElement('a');
removeButton.classList.add('appointmentRemove');
removeButton.textContent = ' Remove ';
removeButton.addEventListener("click", function (evt) {
evt.preventDefault();
removeSelectedOption(removeButton)
});
addAppt.appendChild(removeButton);
addAppt.id = 'appt' + limit + '-' + Appt.id;
Appt.dataset.limit = String(limit - 1);
chosenArea.append(addAppt);
//remove all values from hidden appointments.
if (Appt.classList.contains('slds-has-error')) {
Appt.classList.remove('slds-has-error');
}
if (Appt.querySelector(".appointmentType")) {
let selType = Appt.querySelector(".appointmentType");
desc += selType.options[selType.selectedIndex].value = '';
}
if (Appt.querySelector(".appointmentCustomInput")) {
let inputType = Appt.querySelector(".appointmentCustomInput");
desc += inputType.value = '';
}
if (Appt.dataset.limit < 1) {
Appt.style.display = "none";
}
}
});
});
});
function removeSelectedOption(removeButton) {
let chooserArea = document.getElementById("chooser");
let chosenArea = document.getElementById("chosen");
let rmvAppt = removeButton.closest(".appointmentChosen");
let origAppt = chooserArea.querySelector('#' + rmvAppt.dataset.apptid);
origAppt.classList.remove('slds-is-open');
origAppt.style.display = "block";
chosenArea.removeChild(rmvAppt);
}
function populateApptJSON() {
let jsonOut = [];
let chosen = document.getElementById('chosen');
let allChosen = chosen.querySelectorAll('.appointmentChosen');
allChosen.forEach(function (appointment) {
let appt = {};
appt['apptId'] = appointment.dataset.apptid;
appt['apptCatagory'] = appointment.dataset.apptcat;
appt['apptType'] = appointment.dataset.appttype;
appt['apptText'] = appointment.dataset.appttext;
appt['apptTitle'] = appointment.dataset.appttitle;
appt['appChosenState'] = appointment.dataset.appchosenstate;
appt['appSort'] = appointment.dataset.appsort;
appt['appInput'] = appointment.dataset.appinput;
let apptDesc = appointment.querySelector('.appointmentDesc');
if (apptDesc) {
appt['appDesc'] = apptDesc.textContent;
}
jsonOut.push(appt);
});
let hiddenData = document.querySelectorAll('[id$=outgoingApptJSon]');
hiddenData.forEach(function (hidedata) {
hidedata.value = JSON.stringify(jsonOut);
});
return checkForRequiredAppointments();
}
function checkForRequiredAppointments() {
let chooser = document.getElementById('chooser');
let requiredAppointments = chooser.querySelectorAll('.appointmentRequired');
let allApptGood = true;
requiredAppointments.forEach(function (appt) {
if (window.getComputedStyle(appt).display !== "none") {
allApptGood = false;
appt.classList.add('slds-has-error');
if (!appt.classList.contains('slds-is-open')) {
appt.classList.add('slds-is-open');
}
fadein();
}
});
return allApptGood;
}
|
b84da5d18b4d7187d689ef8e359e6250211e8df7
|
[
"Markdown",
"SQL",
"JavaScript"
] | 4 |
Markdown
|
BW-TEST-Org/summit-clone
|
3790060c45920522e75d6f312eea00e3f374eeca
|
e83875380daadb59db7d99ee05740fe62fe29f79
|
refs/heads/master
|
<repo_name>ZhuorongTan/Reactor<file_sep>/threadTest.cc
#include <iostream>
#include <thread>
#include <unistd.h>
#include <pthread.h>
void func()
{
::sleep(5);
std::cout << "thread...."<< ::pthread_self() << std::endl;
}
int main()
{
std::thread t1(func);
std::cout << "thread id: " << t1.get_id() << std::endl;
t1.join();
::sleep(5);
return 0;
}
<file_sep>/README.md
# Reactor
This is a simple reactor model test.
<file_sep>/EventLoop.h
#ifndef EVENTLOOP_H_
#define EVENTLOOP_H_
#include <thread>
#include <boost/noncopyable.hpp>
class EventLoop: boost::noncopyable
{
public:
EventLoop();
~EventLoop();
void loop();
bool isInLoopThread()const { return threadId_ == std::this_thread::get_id();}
private:
void abortNotInLoopThread();
private:
bool looping_;
std::thread::id threadId_;
};
#endif // EVENTLOOP_H_
<file_sep>/EventLoop.cc
#include "EventLoop.h"
#include <iostream>
#include <assert.h>
#include <poll.h>
#include <cstdio>
__thread EventLoop* t_loopInThisThread = 0;
EventLoop::EventLoop()
: looping_(false)
, threadId_(std::this_thread::get_id())
{
printf("tid: %d\n", threadId_);
std::cout << "EventLoop create " << this << " in thread " << threadId_ << std::endl;
if(t_loopInThisThread)
{
std::cout << "Another EventLoop " << t_loopInThisThread
<< " exists in this thread " << threadId_ << std::endl;
}
else
{
t_loopInThisThread = this;
}
}
EventLoop::~EventLoop()
{
assert(!looping_);
t_loopInThisThread = NULL;
}
void EventLoop::loop()
{
assert(!looping_);
std::cout << "EventLoop " << this << " start looping!" << std::endl;
looping_ = true;
::poll(NULL, 0, 5*1000);
std::cout << "EventLoop " << this << " stop looping!" << std::endl;
looping_ = false;
}
<file_sep>/main_test.cc
#include <cstdio>
#include <thread>
#include <chrono>
#include <unistd.h>
#include "EventLoop.h"
void threadFunc()
{
printf("threadFunc(): pid = %d, tid = %d\n", getpid(), std::this_thread::get_id());
EventLoop loop;
loop.loop();
}
int main()
{
printf("main(): pid = %d, tid = %d\n", getpid(), std::this_thread::get_id());
EventLoop loop;
std::thread t1(threadFunc);
t1.join();
// t1.detach();
loop.loop();
}
|
6a9fd128085c6dfa9b40326083e531027496e983
|
[
"Markdown",
"C++"
] | 5 |
C++
|
ZhuorongTan/Reactor
|
34b1e51e9ec131f979db0dcc350158d2cfb15c1c
|
2ac1308b48f513334453066a58eb5c9740e5f292
|
refs/heads/main
|
<file_sep>LIMIT = 28123
def get_divisors(n):
result = []
for d in xrange(1, (n / 2) + 1):
if n % d == 0:
result.append(d)
return result
def is_abundant(n):
result = False
divisors = get_divisors(n)
divisor_sum = sum(divisors)
if divisor_sum > n:
result = True
return result
abundant_numbers = []
for n in xrange(2, LIMIT):
if is_abundant(n):
abundant_numbers.append(n)
abundant_sums = set()
for a in abundant_numbers:
for b in abundant_numbers:
total = a + b
if total > LIMIT:
continue
abundant_sums.add(total)
total = 0
for num in xrange(1, LIMIT + 1):
if num not in abundant_sums:
total += num
print total
<file_sep>numbers = set()
for a in xrange(2, 100 + 1):
for b in xrange(2, 100 + 1):
n = a ** b
numbers.add(n)
print len(numbers)
<file_sep>from common import primes_to_n, get_prime_factors
number = 600851475143
limit = int(number ** 0.5) + 1
primes = primes_to_n(limit)
prime_factors = [prime for prime, _ in get_prime_factors(number, primes)]
print max(prime_factors)
<file_sep>collatz_length = {}
def collatz(n):
if n == 1:
return 1
if n in collatz_length:
return collatz_length[n]
if n % 2 == 0:
result = 1 + collatz(n / 2)
collatz_length[n] = result
return result
result = 1 + collatz((3 * n) + 1)
collatz_length[n] = result
return result
longest, number = 0, 0
for n in xrange(1, 1000000):
length = collatz(n)
if length > longest:
longest = length
number = n
print 'number=%d, length=%d' % (number, length)
<file_sep>import math
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
for d in xrange(3, int(math.sqrt(n)) + 1, 2):
if n % d == 0:
return False
return True
primes_found, nth_prime = 0, 10001
for n in xrange(2, 99999999):
if is_prime(n):
primes_found += 1
if primes_found == nth_prime:
print n
break
<file_sep>def div_by_all(num):
result = True
for divisor in xrange(2, 20 + 1):
if num % divisor != 0:
result = False
break
return result
for num in xrange(100, 9999999999):
if div_by_all(num):
print num
break
<file_sep># ==============================================================================
# common.py
#
# Useful algorithms or tools for solving Project Euler questions.
# ==============================================================================
# ------------------------------------------------------------------------------
# Imports
# ------------------------------------------------------------------------------
import math
# ------------------------------------------------------------------------------
# Utility functions
# ------------------------------------------------------------------------------
def is_prime(number):
"""
Determine whether number is prime using a brute force approach. Slightly
optimized to only check odd divisors up to the square root of the number.
Arguments:
number<int> -- Number to test.
Returns:
True if the number is prime, else false.
"""
if number < 2:
return False
if number == 2:
return True
if number % 2 == 0:
return False
for divisor in xrange(3, int(math.sqrt(number)) + 1, 2):
if number % divisor == 0:
return False
return True
def primes_to_n(limit):
"""
Find all prime numbers up to the provided limit using the Sieve of Atkin.
Arguments:
limit<int> -- Highest value to check primality.
Returns:
List of prime numbers less than the given limit.
"""
if limit < 2:
return []
if limit < 5:
return [2, 3]
result = []
result.append(2)
result.append(3)
candidates = {}
for number in xrange(5, limit + 1):
candidates[number] = False
for x in xrange(1, int(math.sqrt(limit)) + 1):
for y in xrange(1, int(math.sqrt(limit)) + 1):
n = (4 * (x ** 2)) + (y ** 2)
if n <= limit and (n % 12 == 1 or n % 12 == 5):
candidates[n] = not candidates[n]
n = (3 * (x ** 2)) + (y ** 2)
if n <= limit and n % 12 == 7:
candidates[n] = not candidates[n]
n = (3 * (x ** 2)) - (y ** 2)
if x > y and n <= limit and n % 12 == 11:
candidates[n] = not candidates[n]
for n in xrange(5, int(math.sqrt(limit)) + 1):
if candidates[n]:
k, i = n ** 2, 1
while k <= limit:
candidates[k] = False
i += 1
k = i * (n ** 2)
for number, prime in candidates.iteritems():
if prime:
result.append(number)
return result
def get_prime_factors(number, primes=[]):
"""
Finds the prime factors and their multiplicities for a number. If a list of
primes is supplied, this function does not need to calculate primes. It will
use the list, saving time.
Arguments:
number<int> -- Number to find prime factors for.
primes<[int]> -- Optional list of precalculated primes.
Returns:
List of tuples, where each tuple contains (prime factor, multiplicity).
"""
if number < 4:
return []
result = []
possible_prime_factors = []
n, prime_factors = number, {}
if len(primes) == 0:
possible_prime_factors = primes_to_n((number / 2) + 1)
else:
possible_prime_factors = primes[:(number / 2) + 1]
for prime in possible_prime_factors:
while n > 1:
if n % prime == 0:
if prime in prime_factors:
prime_factors[prime] += 1
else:
prime_factors[prime] = 1
n /= prime
else:
break
for prime, multiplicity in prime_factors.iteritems():
result.append((prime, multiplicity))
return result
def divisor_count(number, primes=[]):
"""
Find the number of divisors this number has, including 1.
Arguments:
number<int> -- Number which we count divisors for.
primes<[int]> -- Optional list of precalculated primes.
Returns:
Count of divisors the number has, including 1.
"""
if number < 4:
return 1
result = 1
prime_factors = get_prime_factors(number, primes)
for _, multiplicity in prime_factors:
result *= multiplicity + 1
result = result if result != 1 else 2
return result - 1
def get_factors(number):
"""
Find the factors for the number starting with 1.
Arguments:
number<int> -- Number to find divisors for.
Returns:
List of integer factors.
"""
if number < 4:
return [1]
result = []
for divisor in xrange(1, (number / 2) + 1):
if number % divisor == 0:
result.append(divisor)
return result
<file_sep>def sum_of_squares(num):
result = 0
for x in xrange(1, num + 1):
result += x * x
return result
def square_of_sum(num):
total = (num * (num + 1)) / 2
return (total * total)
x = sum_of_squares(100)
y = square_of_sum(100)
print y - x
<file_sep>one_to_nine = {
0: '',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
}
teens = {
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
}
tens = {
2: 'twenty',
3: 'thirty',
4: 'forty',
5: 'fifty',
6: 'sixty',
7: 'seventy',
8: 'eighty',
9: 'ninety',
}
def get_word(n):
result = ''
if n < 1:
pass
elif n < 10:
result += one_to_nine[n]
elif n >= 10 and n < 20:
result += teens[n]
elif n >= 20 and n < 100:
ten = n / 10
one = n % 10
result += tens[ten] + ' ' + one_to_nine[one]
elif n >= 100 and n < 1000:
hundred = n / 100
ten = n % 100
result += one_to_nine[hundred] + ' hundred'
ten_word = get_word(ten)
if ten_word != '':
result += ' and ' + ten_word
elif n > 999:
result += 'one thousand'
return result
words = ''
for n in xrange(1, 1000 + 1):
words += get_word(n) + '\n'
words = words.split()
letters = 0
for word in words:
letters += len(word)
print letters
<file_sep>def get_permutations(string):
result = []
permute(string, 0, result)
return result
def permute(string, index, result):
if index >= len(string) - 1:
result.append(string)
return
permute(string, index + 1, result)
swap_index = index + 1
while swap_index < len(string):
str_lst = list(string)
str_lst[index], str_lst[swap_index] = str_lst[swap_index], str_lst[index]
string = ''.join(str_lst)
permute(string, index + 1, result)
swap_index += 1
permutations = get_permutations('0123456789')
print permutations[1000000 - 1]
<file_sep>def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
x = factorial(100)
total = 0
for digit in str(x):
total += int(digit)
print total
<file_sep>total = 0
for i in xrange(1, 1000 + 1):
n = i ** i
total += n
print total
<file_sep>import math
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
for d in xrange(3, int(math.sqrt(n)) + 1, 2):
if n % d == 0:
return False
return True
def is_cyclic_prime(n):
num = str(n)
for i in xrange(len(num) - 1):
num = num[-1:] + num[:-1]
if not is_prime(int(num)):
return False
return True
count = 0
for i in xrange(2, 1000000):
if is_prime(i) and is_cyclic_prime(i):
count += 1
print count
<file_sep>numbers = set()
for number in xrange(1, 1000):
if number % 3 == 0:
numbers.add(number)
elif number % 5 == 0:
numbers.add(number)
result = sum(numbers)
print result
<file_sep>from common import divisor_count, primes_to_n
LIMIT = 1000000
primes = primes_to_n(LIMIT)
for i in xrange(1, LIMIT * 2):
n = (i * (i + 1)) / 2
divisors = divisor_count(n, primes) + 1
if divisors > 500:
print n
break
<file_sep>TWO_DIGIT = 10
THREE_DIGIT = 100
FOUR_DIGIT = 1000
def is_palindrome(num):
number = str(num)
i, j = 0, len(number) - 1
while i < j:
if number[i] != number[j]:
return False
i += 1
j -= 1
return True
largest = -1
for i in xrange(THREE_DIGIT, FOUR_DIGIT):
for j in xrange(THREE_DIGIT, FOUR_DIGIT):
num = i * j
if is_palindrome(num) and num > largest:
largest = num
print largest
<file_sep>def get_divisors(n):
result = []
for d in xrange(1, (n / 2) + 1):
if n % d == 0:
result.append(d)
return result
divisor_sum = {}
for n in xrange(2, 10000):
divisors = get_divisors(n)
divisor_sum[n] = sum(divisors)
amicable_pairs = set()
for num, count in divisor_sum.iteritems():
if count in divisor_sum and divisor_sum[count] == num and num != count:
amicable_pairs.add(num)
amicable_pairs.add(count)
print 'pair found: %d [%d] and %d [%d]' % (num,
count,
divisor_sum[num],
divisor_sum[count])
total = 0
for num in amicable_pairs:
total += num
print total
<file_sep>a, b, i = 1, 1, 3
while True:
a, b = b, a + b
if len(str(b)) == 1000:
print i
break
i += 1
<file_sep>numbers = []
for i in xrange(2, 5000000):
number = str(i)
total = 0
for digit in number:
total += int(digit) ** 5
if i == total:
numbers.append(i)
print sum(numbers)
<file_sep>MAX = 999
for a in xrange(1, MAX):
for b in xrange(a, MAX):
for c in xrange(b, MAX):
if a ** 2 + b ** 2 == c ** 2 and a + b + c == 1000:
print a * b * c
<file_sep>names_file = open('p022_names.txt')
raw_names = names_file.read()
raw_names = raw_names.replace('"', '')
raw_names = raw_names.lower()
unsorted_names = raw_names.split(',')
sorted_names = sorted(unsorted_names)
total_score = 0
for i, name in enumerate(sorted_names):
position = i + 1
word_score = 0
for character in name:
word_score += ord(character) - 96
total_score += word_score * position
print total_score
<file_sep>def fact(n, fact_table={}):
if n <= 1:
return 1
if n in fact_table:
return fact_table[n]
result = n * fact(n - 1)
fact_table[n] = result
return result
result = []
for i in xrange(3, 10000000):
total = 0
for digit in str(i):
total += fact(int(digit))
if total == i:
result.append(i)
print result
print sum(result)
<file_sep>import math
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
for d in xrange(3, int(math.sqrt(n)) + 1, 2):
if n % d == 0:
return False
return True
total = 0
for n in xrange(2, 2000000):
if is_prime(n):
total += n
print total
<file_sep>def is_leap_year(year):
result = False
if year % 100 == 0 and year % 400 == 0:
result = True
elif year % 4 == 0:
result = True
return result
def get_next_day(current_day):
if current_day == 7:
return 1
return current_day + 1
today = 2
first_of_month_sunday = 0
for year in xrange(1901, 2000 + 1):
for month in xrange(1, 12 + 1):
february_days = 29 if is_leap_year(year) else 28
days = {
1: 31,
2: february_days,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
for day in xrange(1, days[month] + 1):
if day == 1 and today == 7:
first_of_month_sunday += 1
today = get_next_day(today)
print first_of_month_sunday
<file_sep>x = 2 ** 1000
answer = 0
for digit in str(x):
answer += int(digit)
print answer
|
56cc105d0b863c8a2ba09d2e6c3a0ad31ab22d81
|
[
"Python"
] | 25 |
Python
|
jneufeld/project-euler
|
199013ce47cf55ec0be94dca5d0a18dde4f4069e
|
57691b77a3ce3e65ae45859cc4e37f32a4fd60f5
|
refs/heads/1.7/master
|
<repo_name>Darragh-McCarthy/harpoon<file_sep>/fuel/app/classes/controller/accounts.php
<?php
class Controller_Accounts extends Controller_Template
{
public function action_index()
{
$data["subnav"] = array();
$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');
$this->template->title = 'Accounts';
$this->template->content = \View::forge('accounts/default', $data);
}
public function action_delete()
{
try {
Auth::delete_user(Input::post('username'));
}
catch (SimpleUserUpdateException $e) {
Debug::dump($e);
}
\Response::redirect('accounts');
}
public function action_login()
{
$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');
if (\Auth::check()) {
\Response::redirect('accounts');
}
if (\Input::method() == 'POST')
{
if (\Auth::instance()->login(\Input::param('username'), \Input::param('password')))
{
if (\Input::param('remember', false)) {
\Auth::remember_me();
} else {
\Auth::dont_remember_me();
}
\Response::redirect('accounts');
}
else {
$data['incorrect_username_or_password'] = true;
}
}
$data["subnav"] = array('login'=> 'active' );
$this->template->title = 'Login';
$this->template->content = \View::forge('accounts/login', $data);
}
public function action_register()
{
if ( ! \Config::get('are_new_user_registrations_enabled', false)) {
\Response::redirect_back();
}
$data = array();
$data["errors"] = array();
$fieldset = \Fieldset::forge();
$fieldset->form()->set_attribute('id', 'register-form');
$fieldset->form()->add_csrf();
$fieldset->add_model('Model\\Auth_User');
$fieldset->add_after('fullname', 'Full Name', array(), array('required'), 'email');
//Using email as username
$fieldset->disable('username');
$fieldset->disable('group_id');
$fieldset->field('email')->set_attribute('type', 'email');
$fieldset->field('password')->set_attribute('class', 'form-control');
$fieldset->field('email')->set_attribute('class', 'form-control');
$fieldset->field('fullname')->set_attribute('class', 'form-control');
if (\Input::method() == 'POST')
{
$params = Input::post();
$params['group_id'] = \Config::get('application.user.default_group', 1);
array_key_exists('email', $params) and $params['username'] = $params['email'];
$fieldset->validation()->run($params);
if ( ! $fieldset->validation()->error())
{
try
{
$created = \Auth::create_user(
$fieldset->validated('email'),//$fieldset->validated('username'),
$fieldset->validated('password'),
$fieldset->validated('email'),
$fieldset->validated('group_id'),
array('fullname' => $fieldset->validated('fullname'))
);
if ($created)
{
\Auth::instance()->login(
$fieldset->validated('username'),
$fieldset->validated('password')
);
\Response::redirect('accounts');
}
}
catch (\SimpleUserUpdateException $e)
{
// duplicate email
if ($e->getCode() == 2){
array_push($data["errors"],
array('email', 'email_already_registered', 'This email is already registered, try logging in.')
);
}
// duplicate username
elseif ($e->getCode() == 3) {
array_push($data["errors"],
array('username', 'username_already_registered', 'This username is already registered, try logging in.')
);
}
else {
//\Messages::error($e->getMessage());
}
}
}
else
{
foreach ($fieldset->error() as $field => $error)
{
array_push($data["errors"],
array($field,
$error->get_message(':rule'),
$error->get_message()));
}
}
// validation failed, repopulate form from posted data
$fieldset->repopulate();
}
if ( ! array_key_exists('errors', $data)) {
$data['errors'] = array();
}
$fieldset->add('submit', '', array('type' => 'submit', 'id'=>'register-form__submit-button', 'value' => 'Create account', 'class' => 'btn btn-primary register-form__submit-button'));
$data["subnav"] = array('register'=> 'active' );
$this->template->title = 'Create account';
$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');
$this->template->content = \View::forge('accounts/register', $data)->set('form', $fieldset, false);
}
public function action_logout()
{
\Auth::dont_remember_me();
\Auth::logout();
//\Messages::success(__('login.logged-out'));
// and go back to where you came from (or the application
// homepage if no previous page can be determined)
//\Response::redirect('accounts');
\Response::redirect('accounts/login');
//$data["subnav"] = array('logout'=> 'active' );
//$this->template->title = 'Accounts » Logout';
//$this->template->content = View::forge('accounts/logout', $data);
}
public function action_passwordrecovery($hash = null)
{
Debug::dump('Error: password recovery is not currently available. Email needs to be set up');
//TESTED AND WORKS. JUST NEEDS TO BE HOOKED UP TO EMAIL
if (\Input::method() == 'POST')
{
if ($email = \Input::post('email'))
{
if ($user = \Model\Auth_User::find_by_email($email))
{
// generate a recovery hash
$hash = \Auth::instance()->hash_password(\Str::random()).$user->id;
// and store it in the user profile
\Auth::update_user(
array(
'lostpassword_hash' => $hash,
'lostpassword_created' => time()
),
$user->username
);
$data['password_url'] = '/accounts/lostpassword/'.base64_encode($hash);
/*
// send an email out with a reset link
\Package::load('email');
$email = \Email::forge();
// use a view file to generate the email message
$email->html_body(
\Theme::instance()->view('login/lostpassword')
->set('url', \Uri::create('login/lostpassword/' . base64_encode($hash) . '/'), false)
->set('user', $user, false)
->render()
);
//$domain_name = Uri::base(false);
//$password_resovery_hash = base64_encode($hash);
//$email->html_body(
// '<a href="'
// .$domain_name
// .'/accounts/passwordrecovery/'
// .$password_resovery_hash
// .'">Reset your password</a>'
//, false);
$email->subject('Harpoon password recovery');
$from = \Config::get('customer_service_email_address', array('name'=>'','email'=>''));
$email->from($from['from-email'], $from['brand-name']);
$email->to($user->email, $user->fullname);
try
{
$email->send();
}
catch(\EmailValidationFailedException $e)
{
//\Messages::error(__('login.invalid-email-address'));
\Response::redirect_back();
}
catch(\Exception $e)
{
// log the error so an administrator can have a look
logger(\Fuel::L_ERROR, '*** Error sending email ('.__FILE__.'#'.__LINE__.'): '.$e->getMessage());
//\Messages::error(__('login.error-sending-email'));
\Response::redirect_back();
}
*/
}
}
//else
//{
// inform the user and fall through to the form
//\Messages::error(__('login.error-missing-email'));
//}
// inform the user an email is on the way (or not ;-))
//\Messages::info(__('login.recovery-email-send'));
//\Response::redirect_back();
}
elseif ($hash !== null)
{
$hash = base64_decode($hash);
// get the userid from the hash
$user = substr($hash, 44);
if ($user = \Model\Auth_User::find_by_id($user))
{
// do we have this hash for this user, and hasn't it expired yet (we allow for 24 hours response)?
if (isset($user->lostpassword_hash) and $user->lostpassword_hash == $hash and time() - $user->lostpassword_created < 86400)
{
// invalidate the hash
\Auth::update_user(
array(
'lostpassword_hash' => null,
'lostpassword_created' => null
),
$user->username
);
// log the user in and go to the profile to change the password
if (\Auth::instance()->force_login($user->id))
{
//\Messages::info(__('login.password-recovery-accepted'));
\Response::redirect('profile');
}
}
}
//\Messages::error(__('login.recovery-hash-invalid'));
\Response::redirect_back();
}
$data["subnav"] = array('passwordrecovery'=> 'active' );
empty($data['password_url']) and $data['password_url'] = '';
$this->template->title = 'Accounts » Passwordrecovery';
$this->template->content = View::forge('accounts/passwordrecovery', $data);
$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');
}
public function action_changepassword() {
if ( ! Auth::check()) {
\Response::redirect('accounts/login');
}
if (\Input::method() == 'POST') {
$is_password_changed = Auth::change_password(
Input::post('oldpassword'),
Input::post('newpassword')
);
if ($is_password_changed) {
\Response::redirect('accounts');
}
}
$data = array();
$data['subnav'] = array();
$this->template->title = 'Accounts » Change password';
$this->template->content = View::forge('accounts/change-password', $data);
$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown name');
}
}
<file_sep>/public/assets/js/homepage.controller.js
(function(){
'use strict';
angular.module('harpoonAjaxLogin')
.controller('Homepage', Homepage);
Homepage.$inject=[];
function Homepage() {
var _this = this;
_this.homepageTestText = 'Homepage goes here';
}
})();<file_sep>/fuel/app/classes/controller/ajaxlogin.php
<?php
/* KEEP CODE CLEAN */
class Controller_Ajaxlogin extends Controller_Rest
{
public function get_logout()
{
\Auth::dont_remember_me();
$is_logged_out = \Auth::logout();
return $this->response(array(
'is_logged_out' => $is_logged_out
));
}
public function post_login()
{
$username = \Input::json("username");
$password = \Input::json("<PASSWORD>");
$remember_me = \Input::json("remember", false);
$is_logged_in = \Auth::login(
$username,
$password
);
if ($is_logged_in)
{
if ($remember_me)
{
\Auth::remember_me();
}
else
{
\Auth::dont_remember_me();
}
return $this->response(array(
'is_logged_in' => true,
'data' => array(
'fullname' => Auth::get_profile_fields('fullname', 'Unknown name')
)
));
}
else
{
return $this->response(array(
'is_logged_in' => false
));
}
}
public function post_register()
{
$fieldset = \Fieldset::forge();
$fieldset->add_model('Model\\Auth_User');
$fieldset->add_after('fullname', 'Full Name', array(), array('required'), 'email');
$params = array();
$params['username'] = \Input::json("username");
$params['email'] = \Input::json("username");
$params['password'] = \Input::json("<PASSWORD>");
$params['fullname'] = \Input::json("fullname");
$params['group_id'] = \Config::get('application.user.default_group', 1);
$fieldset->validation()->run($params);
$errors = array();
if ( ! $fieldset->validation()->error())
{
try
{
$created = \Auth::create_user(
$fieldset->validated('email'),
$fieldset->validated('password'),
$fieldset->validated('email'),
$fieldset->validated('group_id'),
array('fullname' => $fieldset->validated('fullname'))
);
if ($created)
{
\Auth::login(
$fieldset->validated('username'),
$fieldset->validated('password')
);
return $this->response(array(
'is_account_creation_success' => true
));
}
}
catch (\SimpleUserUpdateException $e)
{
if ($e->getCode() == 2){
array_push($errors, 'This email is already registered, try logging in.');
}
elseif ($e->getCode() == 3) {
array_push($errors, 'This username is already registered, try logging in.');
}
else {
array_push($errors, $e->getMessage());
}
}
}
else
{
foreach ($fieldset->error() as $field => $error)
{
array_push($errors,
$error->get_message()
);
}
}
return $this->response(array(
'is_account_creation_success' => false,
'errors' => $errors
));
}
}
<file_sep>/fuel/app/views/angular-template.php
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title><?php echo $title; ?></title>
<meta name="description" content="<?php echo $title; ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<?php echo Asset::css('bootstrap.css', array(), null, true); ?>
<?php echo Asset::css('app.css', array(), null, true); ?>
</head>
<body ng-strict-di ng-app="harpoonAjaxLogin">
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<header class="main-header">
<div ui-view="header"></div>
</header>
<main>
<div ui-view="content"></div>
</main>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<!--
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
-->
<script type="text/ng-template" id="/templates/header.template.html">
<div class="container">
<div class="row">
<div class="col-sm-4 col-sm-offset-8">
<ul class="list-inline main-header__navigation">
<li>{{header.userScreenName}}</li>
<li><a ui-sref-active="active" ui-sref="app.login" ng-show=" ! header.isUserLoggedIn">Login</a></li>
<li><a ui-sref-active="active" ui-sref="app.register" ng-show=" ! header.isUserLoggedIn">Create account</a></li>
<li><a ng-click="header.logout()" ng-show="header.isUserLoggedIn">Logout</a></li>
</ul>
</div>
</div>
</div>
</script>
<script type="text/ng-template" id="/templates/homepage.template.html">
<h1>{{homepage.homepageTestText}}</h1>
</script>
<script type="text/ng-template" id="/templates/forgot-password.template.html">
Forgot password template {{forgotPassword.homepageTestText}}
</script>
<script type="text/ng-template" id="/templates/login.template.html">
<form class="login-form" ng-submit="login.login()">
<h1>Login</h1>
<p ng-show="login.isWrongUsernamePassword" class="alert alert-danger">Incorrect email or password</p>
<div class="form-group">
<label>
Email
<input name="username" type="email" class="form-control" ng-model="login.username" required autofocus />
</label>
</div>
<div class="form-group">
<label>
Password
<input name="password" type="{{login.passwordInputType}}" type="text" class="form-control" ng-model="login.password" required />
</label>
</div>
<div>
<label class="login-form__show-password-checkbox-label">
Show password
<input class="login-form__show-password-checkbox" type="checkbox" ng-click="login.togglePasswordInputType()" />
</label>
</div>
<div class="checkbox login-form__keep-me-logged-in">
<label class="login-form__keep-me-logged-in__label">
<input name="remember" type="checkbox" ng-model="login.remember" />
Keep me logged in
</label>
</div>
<div class="login-form__actions">
<button class="btn btn-primary">Login</button>
<a class="login-form__forgot-password-link" ui-sref="app.forgot-password">Forgot your password?</a>
</div>
</form>
</script>
<script type="text/ng-template" id="/templates/register.template.html">
<form class="register-form" name="registerform" ng-submit="register.register()">
<h1>Register</h1>
<ul class="register-form__errors-list">
<li ng-repeat="error in register.serverErrors"
class="alert alert-danger">
{{error}}
</li>
</ul>
<div class="form-group">
<label>
Email
<input name="email"
type="email"
class="form-control"
name="email"
ng-model="register.email"
required
autofocus
/>
</label>
</div>
<div class="form-group">
<label>
Full name
<input name="fullname"
type="text"
class="form-control"
name="fullname"
ng-model="register.fullname"
required
/>
</label>
</div>
<div class="form-group">
<label>
Password
<input name="password"
type="{{register.passwordInputType}}"
name="password"
type="text"
class="form-control"
ng-model="register.password"
required
/>
</label>
</div>
<label class="register-form__show-password-checkbox-label">
<input class="register-form__show-password-checkbox"
type="checkbox"
ng-click="register.togglePasswordInputType()"
/>
Show password
</label>
<div class="register-form__actions">
<button class="btn btn-primary">Create account</button>
</div>
</form>
</script>
<script>
window.isUserLoggedIn = '<?php if ( ! empty($is_user_logged_in)) { echo $is_user_logged_in; } else { echo "0"; } ?>';
if (window.isUserLoggedIn === '0') {
window.isUserLoggedIn = false;
}
else if (window.isUserLoggedIn === '1') {
window.isUserLoggedIn = true;
}
else {
console.log('invalid window.isUserLoggedIn value');
}
window.userScreenName = '<?php echo $screen_name; ?>';
</script>
<?php echo Asset::js('https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js'); ?>
<?php echo Asset::js('//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular-animate.js'); ?>
<?php echo Asset::js('angular-ui-router.min.js'); ?>
<?php echo Asset::js('main.module.js'); ?>
<?php echo Asset::js('main.route.js'); ?>
<?php echo Asset::js('homepage.controller.js'); ?>
<?php echo Asset::js('login.controller.js'); ?>
<?php echo Asset::js('register.controller.js'); ?>
<?php echo Asset::js('header.controller.js'); ?>
<?php echo Asset::js('forgot-password.controller.js'); ?>
<?php echo Asset::js('sharedServices/userAuthService.factory.js'); ?>
<?php echo Asset::js('focusTextInputsOnMouseover.directive.js'); ?>
</body>
</html>
<file_sep>/fuel/app/views/template.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $title; ?></title>
<?php echo Asset::css('bootstrap.css'); ?>
<?php echo Asset::css('app.css'); ?>
</head>
<body>
<header class="main-header container-fluid">
<div class="row">
<div class="main-header__user-account col-sm-4 col-sm-offset-8 col-xs-6 col-xs-offset-6">
<div class="row">
<ul class="list-inline">
<li><div class="main-header__user-account__screen-name"><?php echo $screen_name ?></div></li>
<?php if ($screen_name === 'Guest'): ?>
<li><a href="/accounts/login">Login</a></li>
<li><a href="/accounts/register">Register</a></li>
<?php else: ?>
<li><a href="/accounts/logout">Logout</a></li>
<?php endif; ?>
</ul>
</div>
</div>
</div>
</header>
<div class="container">
<div class="col-md-12">
<h1><?php echo $title; ?></h1>
<hr>
</div>
<div class="col-md-12"><?php echo $content; ?></div>
</div>
<footer>
</footer>
</body>
</html>
<file_sep>/fuel/app/views/accounts/change-password.php
<ul class="nav nav-pills">
<li class='<?php echo Arr::get($subnav, "login" ); ?>'><?php echo Html::anchor('accounts/login','Login');?></li>
<li class='<?php echo Arr::get($subnav, "register" ); ?>'><?php echo Html::anchor('accounts/register','Register');?></li>
<li class='<?php echo Arr::get($subnav, "logout" ); ?>'><?php echo Html::anchor('accounts/logout','Logout');?></li>
<li class='<?php echo Arr::get($subnav, "passwordrecovery" ); ?>'><?php echo Html::anchor('accounts/passwordrecovery','Passwordrecovery');?></li>
</ul>
<form action="/accounts/changepassword" method="POST">
<div>
<label>
Old password
<input type="<PASSWORD>" name="oldpassword" />
</label>
</div>
<div>
<label>
New password
<input type="<PASSWORD>" name="newpassword" />
</label>
</div>
<button>Login</button>
</form><file_sep>/public/assets/js/sharedServices/userAuthService.factory.js
(function(){
'use strict';
angular.module('harpoonAjaxLogin')
.factory('userAuthService', UserAuthService);
UserAuthService.$inject=['$http','$window','$q'];
function UserAuthService( $http, $window, $q ) {
var LOGGED_OUT_USER_SCREEN_NAME = 'Guest';
var isLoggedIn = $window.isUserLoggedIn;
var screenName = $window.userScreenName;
return {
'login': login,
'logout': logout,
'isLoggedIn': isLoggedInFunc,
'getScreenName': getScreenName,
'createAccount': createAccount
};
function getScreenName() {
return screenName;
}
function isLoggedInFunc() {
return isLoggedIn;
}
function logout() {
var req = {
method: 'GET',
url: '/ajaxlogin/logout/',
headers: {
'Accept': 'application/json'
},
};
return $http(req).then(
function logoutSuccess(response) {
screenName = LOGGED_OUT_USER_SCREEN_NAME;
isLoggedIn = false;
},
function logoutError(response) {
console.log(response);
}
);
}
function login(email, password, remember) {
var req = {
method: 'POST',
url: '/ajaxlogin/login/',
headers: {
'Accept': 'application/json'
},
data: {
'username': email,
'<PASSWORD>': <PASSWORD>,
'remember': remember
}
};
return $http(req).then(
function loginSuccess(response) {
console.log(response);
if ( ! response.data.is_logged_in) {
console.log('loginSuccess handler returned not logged in')
return $q.reject();
}
console.log('fullname', response.data.data.fullname);
screenName = response.data.data.fullname;
isLoggedIn = true;
},
function loginError(response) {
console.log(response);
}
);
}
function createAccount(email, password, fullname) {
var req = {
method: 'POST',
url: '/ajaxlogin/register/',
headers: {
'Accept': 'application/json'
},
data: {
'username': email,
'password': <PASSWORD>,
'fullname': fullname
}
};
return $http(req).then(
function registerSuccess(response) {
if ( ! response.data.is_account_creation_success) {
return $q.reject(response.data.errors);
}
screenName = fullname;
isLoggedIn = true;
},
function registerError(response) {
console.log(response);
}
);
}
}
})();
<file_sep>/fuel/app/views/accounts/register.php
<?php
echo '<div class="register-form">';
if (is_array($errors) || is_object($errors))
{
foreach ($errors as $val) {
# code...
//echo ' #1: '.$val[0];
//echo ' #2: '.$val[1];
echo '<p class="alert alert-danger">'.$val[2].'</p>';
}
}
echo $form.'</div>';
?>
<script>
(function() {
/*
var httpRequest;
function makeRequest(url, callback) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
callback(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
};
httpRequest.open('GET', url);
httpRequest.send();
}
document.addEventListener('DOMContentLoaded', function() {
var registerForm = document.getElementById('register-form');
registerForm.onsubmit = function(e) {
e.preventDefault();
makeRequest('/ajaxlogin/testingajax.json', function(data){
console.log(data);
});
}
});
*/
})();
</script>
<file_sep>/fuel/app/classes/controller/home.php
<?php
class Controller_Home extends Controller_Template
{
public $template = 'angular-template';
public function action_index()
{
$this->template->screen_name = Auth::get_profile_fields('fullname', 'Unknown');
$this->template->is_user_logged_in = Auth::check();
$this->template->title = 'Simple AJAX login with AngularJS and FuelPHP';
}
}
<file_sep>/fuel/app/views/accounts/passwordrecovery.php
<ul class="nav nav-pills">
<li class='<?php echo Arr::get($subnav, "login" ); ?>'><?php echo Html::anchor('accounts/login','Login');?></li>
<li class='<?php echo Arr::get($subnav, "register" ); ?>'><?php echo Html::anchor('accounts/register','Register');?></li>
<li class='<?php echo Arr::get($subnav, "logout" ); ?>'><?php echo Html::anchor('accounts/logout','Logout');?></li>
<li class='<?php echo Arr::get($subnav, "passwordrecovery" ); ?>'><?php echo Html::anchor('accounts/passwordrecovery','Passwordrecovery');?></li>
</ul>
<h1>WARNING: this page unsafely exposes the password recovery link for test purposes.
<br/>
The password recovery link should be sent by email.</h1>
<?php if ( ! empty($password_url)) { ?>
<a href="<?php echo $password_url ?>">Recover Password</a>
<?php } ?>
<form action="/accounts/passwordrecovery" method="POST">
<div>
<label>
Email
<input type="email" name="email" />
</label>
</div>
<button>Login</button>
</form><file_sep>/public/assets/js/header.controller.js
(function(){
'use strict';
angular.module('harpoonAjaxLogin')
.controller('Header', Header);
Header.$inject=['$window','userAuthService','$state'];
function Header( $window, userAuthService, $state ) {
var _this = this;
_this.userScreenName = userAuthService.getScreenName();
if (_this.userScreenName === 'Guest') {
_this.userScreenName = null;
}
_this.isUserLoggedIn = userAuthService.isLoggedIn();
_this.logout = function(){
userAuthService.logout().then(
function logoutSuccessful(){
$state.go($state.current, {}, {
reload: true
});
}
);
}
}
})();<file_sep>/public/assets/js/register.controller.js
(function(){
'use strict';
angular.module('harpoonAjaxLogin')
.controller('Register', Register);
Register.$inject=['userAuthService','$state','$scope'];
function Register( userAuthService, $state, $scope ) {
var DEFAULT_PASSWORD_INPUT_TYPE = '<PASSWORD>';
var ALTERNATIVE_PASSWORD_INPUT_TYPE = 'text';
var _this = this;
_this.serverErrors = null;
_this.passwordInputType = DEFAULT_PASSWORD_INPUT_TYPE;
_this.togglePasswordInputType = togglePasswordInputType;
_this.register = register;
function togglePasswordInputType() {
if (_this.passwordInputType === DEFAULT_PASSWORD_INPUT_TYPE) {
_this.passwordInputType = ALTERNATIVE_PASSWORD_INPUT_TYPE;
} else {
_this.passwordInputType = DEFAULT_PASSWORD_INPUT_TYPE;
}
}
function register() {
userAuthService.createAccount(_this.email, _this.password, _this.fullname).then(
function onCreateAccountSuccess() {
$state.go('app', {}, {
reload: true
});
},
function onCreateAccountError(serverErrors) {
_this.serverErrors = serverErrors;
}
);
}
}
})();<file_sep>/fuel/app/views/accounts/login.php
<form class="login-form" action="/accounts/login" method="POST">
<?php if ( ! empty($incorrect_username_or_password)): ?>
<p class="alert alert-danger">Incorrect email or password.</p>
<?php endif; ?>
<div class="form-group <?php if ( ! empty($incorrect_username_or_password)) { echo 'has-error';} ?>">
<label class="control-label">
Email
<input class="form-control" type="email" name="username" />
</label>
</div>
<div class="form-group <?php if ( ! empty($incorrect_username_or_password)) { echo 'has-error';} ?>">
<label class="control-label">
Password
<input class="form-control" type="<PASSWORD>" name="password" id="login-form__password-input" />
</label>
</div>
<label class="login-form__show-password-checkbox-label">Show password
<input id="login-form__show-password-checkbox" type="checkbox" />
</label>
<div class="checkbox login-form__keep-me-logged-in">
<label class="control-label">
<input type="checkbox" name="remember" />
Keep me logged in
</label>
</div>
<div class="login-form__actions">
<button type="submit" class="btn btn-primary login-form__login-button">Login</button>
<div class="login-form__forgot-password-link">
<?php echo Html::anchor('accounts/passwordrecovery','Forgot your password?');?>
</div>
</div>
</form>
<script>
document.addEventListener('DOMContentLoaded', function() {
var showPasswordCheckbox = document.getElementById('login-form__show-password-checkbox');
var passwordInputField = document.getElementById('login-form__password-input');
showPasswordCheckbox.onclick = function(){
var inputType = showPasswordCheckbox.checked ? 'text' : 'password';
passwordInputField.setAttribute('type', inputType);
};
});
</script>
<file_sep>/fuel/app/config/form.php
<?php
return array(
// regular form definitions
'prep_value' => true,
'auto_id' => true,
'auto_id_prefix' => 'form_',
'form_method' => 'post',
'form_template' => "\n\t\t{open}\n\t\t<table>\n{fields}\n\t\t</table>\n\t\t{close}\n",
'fieldset_template' => "\n\t\t<tr><td colspan=\"2\">{open}<table>\n{fields}</table></td></tr>\n\t\t{close}\n",
'field_template' => "\t\t<tr class=\"form-group\">\n\t\t\t<td class=\"{error_class}\">{label}{required}</td>\n\t\t\t<td class=\"{error_class}\">{field} <span>{description}</span> {error_msg}</td>\n\t\t</tr>\n",
'multi_field_template' => "\t\t<tr>\n\t\t\t<td class=\"{error_class}\">{group_label}{required}</td>\n\t\t\t<td class=\"{error_class}\">{fields}\n\t\t\t\t{field} {label}<br />\n{fields}<span>{description}</span>\t\t\t{error_msg}\n\t\t\t</td>\n\t\t</tr>\n",
'error_template' => '<span>{error_msg}</span>',
'group_label' => '<span>{label}</span>',
'required_mark' => '*',
'inline_errors' => false,
'error_class' => 'has-error',
'label_class' => 'control-label',
// tabular form definitions
'tabular_form_template' => "<table>{fields}</table>\n",
'tabular_field_template' => "{field}",
'tabular_row_template' => "<tr>{fields}</tr>\n",
'tabular_row_field_template' => "\t\t\t<td>{label}{required} {field} {error_msg}</td>\n",
'tabular_delete_label' => "Delete?",
);
<file_sep>/public/assets/js/forgot-password.controller.js
(function(){
'use strict';
angular.module('harpoonAjaxLogin')
.controller('ForgotPassword', ForgotPassword);
ForgotPassword.$inject=[];
function ForgotPassword() {
var _this = this;
_this.headerTestText = 'Controller is working!';
}
})();
|
b67ec1cab2c351bcb4aa6571f4d84af2ce8e3ce4
|
[
"JavaScript",
"PHP"
] | 15 |
PHP
|
Darragh-McCarthy/harpoon
|
3fa20d851ba76a48fa64f40bd69b495dae635b0f
|
b5204f9115c8fbb83bf996af8fd01066d973bbe5
|
refs/heads/master
|
<repo_name>SalilAj/CSV_CRUDS<file_sep>/CSVNameGenerator/src/main/java/Genesys/CSVNameGenerator/App.java
package Genesys.CSVNameGenerator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ThreadLocalRandom;
/**
* Hello world!
*
*/
public class App {
public static void generateCSV(Path path, int entries) {
final String FILE_HEADER = "firstName,lastName,age";
final String NEW_LINE_SEPARATOR = "\n";
final String COMMA_DELIMITER = ",";
StringBuffer sbFirstName = new StringBuffer();
char fname = 'a';
char lname = 'a';
int randomAge;
try {
FileWriter fileWriter = new FileWriter(path.toString() + "/Genesys.csv");
fileWriter.append(FILE_HEADER);
fileWriter.append(NEW_LINE_SEPARATOR);
for (int i = 0; i < entries; i++) {
fileWriter.append(sbFirstName.toString() + fname);
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(lname);
fileWriter.append(COMMA_DELIMITER);
randomAge = ThreadLocalRandom.current().nextInt(1, 99 + 1);
fileWriter.append(String.valueOf(randomAge));
fileWriter.append(NEW_LINE_SEPARATOR);
fname++;
lname++;
//if first name reaches 'z', set to 'a' again while pre-pending 'a' to the String buffer
if (fname > 122) {
fname = 97;
sbFirstName.append(fname);
}
//if last name reaches 'z', set to 'a' again
if (lname > 122) {
lname = 97;
}
}
fileWriter.close();
System.out.println("done!");
} catch (IOException e) {
System.out.println("Path doesnot exist. Please input a correct Path. Program Exiting... \n");
return;
}
return;
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Path path;
String pathInput;
int entries;
try {
System.out.println("Enter File Path:");
pathInput = br.readLine();
path = Paths.get(pathInput);
if (!Files.exists(path)) {
System.out.println("Path doesnot exist. Please input a correct Path. Program Exiting... \n");
return;
}
System.out.println("Enter Number of Entries (1-10,000):");
entries = Integer.parseInt(br.readLine());
if (entries < 1 || entries > 10000) {
System.out.println(
"Invalid number of entries. Please input values between (1-10,000) Program Exiting... \n");
return;
}
} catch (IOException e) {
System.out.println("Invalid Input. Program Exiting... \n");
return;
}
generateCSV(path, entries);
}
}
<file_sep>/README.md
# CSV_CRUDS
Generates a CSV of 10,000 people's name and age and dumps the data into MongoDB
The aim of this project is as follows:
1) To create a program that generates a CSV file containing 10,000 unique entries of people containing their First Name, Last Name and their age.</br>
2) Using this generated CSV file, create a program that reads this CSV file and dumps all the data into mongoDB </br>
## TASK 1</br>
This program is written in Java using maven as its dependency manager.
Refer the folder "CSVNameGenerator" for the code.
It is a simple java application that generates a CSV file of 10,000 unique names of people. </br>
</br>
Steps to Run:
1) Build a Runnable Jar file of the code
2) Run the Jar file using the command 'java -jar XXX.jar'
3) You will be prompted to input the Path of the directory where you wish to create the CSV file
as well as the number of entries you wish to have in the CSV file (1-10,000).
## TASK 2</br>
This program is written in Java using maven as its dependency manager and MongoDB as its database.
Refer the folder "CSVDBLoader" for the code.
It is a simple java application that reads the CSV file generated by the program mentioned in Task 1 and stores all the information in MongoDB </br>
</br>
Steps to Run:
1) Build a Runnable Jar file of the code
2) Run the Jar file using the command 'java -jar XXX.jar'
3) You will be prompted to input the Path of the CSV file containing the names of the people
as well as the URI of the mongoDB Database where you wish to store the information.
4) The entries will be stored in mongo database called 'genesys' and collection name called 'people'
## Notes on Performance</br>
**For Task 1:**</br>
There are various ways by which you can generate 10,000 random names.</br>
However generating random names may lead to collision therefore having unique names may not be guaranteed, this becomes especially true as the number of people increase.</br>
This can be resolved using HashSet.</br>
Names generated can be stored in a Hashset and any names generated afterwards may be validated for their uniqueness by refering to the names already present in the hashset. All unique entries are further added to the hashset till the number of unique entries required are met </br>
However the downside is that you need to store 10,000 names in the hashset, more so if the program is expected to handle more than 10,000 entries. The program will also loop additional number of times depending on the number of collisions occured.</br>
The requirement of this project was to just generate unique values as names, not necessary they should be legitimate or random names. So decision was made to go with a sequential approach to generate names to maintain uniqueness and avoid the hassel of storing them in a hashset and collision detection.
**For Task 2:**</br>
The prime performance issue in database insertion is the amount of time required for storing large number of entries.
As the number of entries increase the program will take equally longer to finish the complete insertion.</br>
Also the additional latency if the database is not local and/or is hosted on a server that is geographically distant.
One solution to reduce the time required to insert large amount of data into the database is to run the insertion operation on multiple services parallely. </br>
You can leverage the benefits of using a Master-Worker distributes system design to run the insertion operation parallely.
Assuming there are around 10 million entries, the Master can break down the 10 million entries into 10 chunks of 1 million entries and send the different chunks to 10 workers who perform the insertion operation parallely. This can greatly reduce the time required for insertion as compared to sequential insertion by a single service.
<file_sep>/CSVNameGenerator/src/test/java/Genesys/CSVNameGenerator/AppTest.java
package Genesys.CSVNameGenerator;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase {
public AppTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(AppTest.class);
}
public void testApp() {
boolean result = false;
Path path = Paths.get(".");
App.generateCSV(path, 5);
File file = new File("Genesys.csv");
if (file.exists() && file.isFile()) {
result = true;
}
assertEquals(true, result);
}
}
|
583416562a7a72138b4586ea7c451f44d2ba97e2
|
[
"Markdown",
"Java"
] | 3 |
Java
|
SalilAj/CSV_CRUDS
|
e7e46507056ea204b146678e20955f934a67538f
|
d8b0b747f7452bf1491eaaf7da02f4e2b342de8c
|
refs/heads/main
|
<repo_name>Galse22/BenBonk-Jam-3<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Misc/Circleaa.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Circleaa : MonoBehaviour
{
public Animator animator;
private void OnEnable() {
animator.SetBool("start", true);
}
private void OnDisable() {
animator.SetBool("start", false);
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Menu Manager/MUSIC/MenuMusicScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuMusicScript : MonoBehaviour
{
GameObject previousGO;
private void Start() {
// checks if find game object with same tag
previousGO = GameObject.FindWithTag("MenuMusic");
Scene currentScene = SceneManager.GetActiveScene ();
string sceneName = currentScene.name;
if(sceneName == "Menu")
{
if(previousGO != null && previousGO != this.gameObject)
{
Destroy(this.gameObject);
}
}
else if(sceneName == "Cutscenes")
{
DontDestroyOnLoad(this.gameObject);
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Enemy/Wiz/Bullet/BulletTwo.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletTwo : MonoBehaviour
{
public float sIntensity;
public float sTime;
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
HealthManager healthManager = GameObject.FindWithTag("GameManager").GetComponent<HealthManager>();
healthManager.TakeDamagePlayer();
this.gameObject.SetActive(false);
}
else if(col.gameObject.tag == "NorthPole")
{
this.gameObject.SetActive(false);
CinemachineShake.Instance.ShakeCamera (sIntensity, sTime);
}
}
}
<file_sep>/README.md
# BenBonk-Jam-3
Galse22's and JMCD's game for the BenBonk Game Jam 3
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Player/PlayerMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D playerRb;
public Camera cam;
Vector2 movement;
Vector3 v3Pos;
Vector3 moveDir;
GameObject goPlayer;
public float fAngle;
float otherFangle;
private Rigidbody2D rb;
public GameObject rbGO;
private Animator anim;
private bool isDashButtonDown;
bool lookingRight;
public bool canMove;
public GameObject sfxFootstep;
void Awake() {
anim = GetComponent<Animator>();
goPlayer = this.gameObject;
playerRb = goPlayer.GetComponent<Rigidbody2D>();
rb = rbGO.GetComponent<Rigidbody2D>();
}
void Update()
{
if(canMove)
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
}
moveDir = new Vector3(movement.x, movement.y).normalized;
if(movement.y != 0 || movement.x != 0)
{
anim.SetBool("isWalking", true);
}
else
{
anim.SetBool("isWalking", false);
}
}
private void FixedUpdate()
{
playerRb.MovePosition(playerRb.position + movement * moveSpeed * Time.fixedDeltaTime);
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
v3Pos = Input.mousePosition;
v3Pos.z = (goPlayer.transform.position.z - Camera.main.transform.position.z);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
v3Pos = v3Pos - goPlayer.transform.position;
fAngle = Mathf.Atan2 (v3Pos.y, v3Pos.x) * Mathf.Rad2Deg - 90f;
otherFangle = fAngle;
// meanest bug ever
if (otherFangle < 0.0f) otherFangle += 360.0f;
rb.rotation = fAngle;
if(otherFangle >= 0 && otherFangle <= 180)
{
if(lookingRight != true)
{
Flip();
}
}
else if(otherFangle > 180)
{
if(lookingRight != false)
{
Flip();
}
}
}
void Flip()
{
lookingRight = !lookingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
public void CreateFootstep()
{
GameObject footstepSFXInstatiated = Instantiate(sfxFootstep, this.gameObject.transform.position, Quaternion.identity);
footstepSFXInstatiated.GetComponent<AudioSource>().pitch = Random.Range(0.4f, 1.2f);
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/GameManager/MoreFunc.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoreFunc : MonoBehaviour
{
public GameObject sfxM1;
public GameObject sfxM2;
public GameObject sfxM3;
GameObject goInstantiated;
public Transform transformPlayer;
public void RandomMagnetPSfx()
{
GameObject SFX = GameObject.FindWithTag("MagnetSFX");
if(SFX == null)
{
int iV = Random.Range(0, 3);
if(iV == 0)
{
goInstantiated = Instantiate(sfxM1, transformPlayer.position, Quaternion.identity);
}
else if(iV == 1)
{
goInstantiated = Instantiate(sfxM2, transformPlayer.position, Quaternion.identity);
}
else
{
goInstantiated = Instantiate(sfxM3, transformPlayer.position, Quaternion.identity);
}
goInstantiated.GetComponent<AudioSource>().pitch = Random.Range(0.8f, 1.2f);
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Enemy/Wiz/WizScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class WizScript : MonoBehaviour
{
Transform transformPlayer;
Transform thisTransform;
public AIDestinationSetter aIDestinationSettler;
public float timeBtwShooting;
public float stoppingDistance;
public AIPath aIPath;
float currentDistance;
public Animator anim;
public Transform placeToShoot;
int valRand;
public float forceBullet1;
public float forceBullet2;
Vector2 direction;
public GameObject shootWizSFX;
public int valBullet2;
float otherAngle;
public bool stunned;
void OnEnable()
{
thisTransform = GetComponent<Transform>();
transformPlayer = GameObject.FindWithTag("Player").GetComponent<Transform>();
aIDestinationSettler.target = transformPlayer;
StartCoroutine("ShooterCoroutine");
}
private void OnDisable() {
StopAllCoroutines();
}
private void Update() {
currentDistance = aIPath.remainingDistance;
if(currentDistance < stoppingDistance)
{
aIPath.canMove = false;
anim.SetBool("walking", false);
}
else
{
aIPath.canMove = true;
anim.SetBool("walking", true);
}
}
IEnumerator ShooterCoroutine()
{
yield return new WaitForSeconds(timeBtwShooting);
if(!stunned)
{
valRand = Random.Range(0, 100);
if(valRand > valBullet2)
{
GameObject bullet = ObjectPooler.SharedInstance.GetPooledObject("WBullet1");
bullet.transform.position = placeToShoot.position;
bullet.SetActive(true);
direction = (placeToShoot.position - transformPlayer.position).normalized;
bullet.GetComponent<Rigidbody2D>().AddForce(direction * - forceBullet1 * 10);
}
else
{
GameObject bullet = ObjectPooler.SharedInstance.GetPooledObject("WBullet2");
bullet.transform.position = placeToShoot.position;
bullet.SetActive(true);
direction = (placeToShoot.position - transformPlayer.position).normalized;
otherAngle = Mathf.Atan2 (placeToShoot.position.y - transformPlayer.position.y, placeToShoot.position.x - transformPlayer.position.x) * Mathf.Rad2Deg;
bullet.transform.eulerAngles = new Vector3(0, 0, otherAngle);
bullet.GetComponent<Rigidbody2D>().AddForce(direction * - forceBullet2 * 10);
}
GameObject goInstantiated = Instantiate(shootWizSFX, transform.position, Quaternion.identity);
goInstantiated.GetComponent<AudioSource>().pitch = Random.Range(0.8f, 1.2f);
}
StartCoroutine("ShooterCoroutine");
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Enemy/Wiz/WizColChild.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WizColChild : MonoBehaviour
{
HealthManager healthManager;
private void OnEnable() {
healthManager = GameObject.FindWithTag("GameManager").GetComponent<HealthManager>();
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "SouthPole")
{
healthManager.TakeDamagePlayer();
this.gameObject.transform.parent.transform.parent.gameObject.SetActive(false);
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Enemy/EnemyHealthManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealthManager : MonoBehaviour
{
public GameObject deathGO;
private void OnCollisionEnter2D(Collision2D col) {
if(col.gameObject.tag == "Spikes")
{
Die();
}
}
public void Die()
{
SpawnerScript spawnerScript = GameObject.FindWithTag("GameManager").GetComponent<SpawnerScript>();
spawnerScript.DecreaseTime();
GameObject goInstantiated = Instantiate(deathGO, transform.position, Quaternion.identity);
goInstantiated.GetComponent<AudioSource>().pitch = Random.Range(0.8f, 1.2f);
this.gameObject.SetActive(false);
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Menu Manager/MenuManagerScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuManagerScript : MonoBehaviour
{
public GameObject buttonSFX;
public void TransitionToScene(int i)
{
Destroy(GameObject.FindWithTag("MenuMusic"));
GameObject goInstantiated = Instantiate(buttonSFX, Vector3.zero, Quaternion.identity);
goInstantiated.GetComponent<AudioSource>().pitch = Random.Range(0.8f, 1.2f);
SceneManager.LoadScene(i);
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/GameManager/HealthManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthManager : MonoBehaviour
{
int health = 3;
public GameObject thirdHeart;
public GameObject secondHeart;
public GameObject firstHeart;
public float sIntensity;
public float sTime;
public GameObject loseTXT;
public Transform transformPlayer;
public GameObject takeDmgSFX;
private void Start() {
Time.timeScale = 1f;
}
public void TakeDamagePlayer()
{
health--;
Instantiate(takeDmgSFX, transformPlayer.position, Quaternion.identity);
if(health == 2)
{
RemoveAllEnemies();
thirdHeart.SetActive(false);
CinemachineShake.Instance.ShakeCamera (sIntensity, sTime);
}
else if(health == 1)
{
RemoveAllEnemies();
secondHeart.SetActive(false);
CinemachineShake.Instance.ShakeCamera (sIntensity, sTime);
}
else
{
firstHeart.SetActive(false);
loseTXT.SetActive(true);
Time.timeScale = 0.00001f;
}
}
void RemoveAllEnemies()
{
GameObject[] allEnemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in allEnemies)
{
enemy.SetActive(false);
}
GameObject[] allBullets1 = GameObject.FindGameObjectsWithTag("BulletOne");
foreach(GameObject bullet1 in allBullets1)
{
bullet1.SetActive(false);
}
GameObject[] allBullets2 = GameObject.FindGameObjectsWithTag("BulletTwo");
foreach(GameObject bullet2 in allBullets2)
{
bullet2.SetActive(false);
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Player/Shield/StaticScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StaticScript : MonoBehaviour
{
Rigidbody2D rb;
GameObject thisGO;
Vector3 defaultPos;
void Start()
{
defaultPos.Set(0, 0, 0);
thisGO = this.gameObject;
rb = this.gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
thisGO.transform.localPosition = defaultPos;
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Player/PlayerDamageCheck.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerDamageCheck : MonoBehaviour
{
public HealthManager healthManager;
public float iTime;
bool canTakeDamage = true;
private void OnCollisionEnter2D(Collision2D col) {
if(col.gameObject.tag == "Spikes" && canTakeDamage)
{
canTakeDamage = false;
healthManager.TakeDamagePlayer();
Invoke("ThatFuncPlayer", iTime);
}
}
void ThatFuncPlayer()
{
canTakeDamage = true;
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Enemy/Slime/SlimeCol.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class SlimeCol : MonoBehaviour
{
public float magnitude;
public float sIntensity;
public float sTime;
MoreFunc moreFunc;
Transform transformPlayer;
public float stunnedTime;
public AIDestinationSetter aIDestinationSettler;
public TimeBetweenNull timeBetweenNull;
public GameObject circleA;
Vector3 v3;
public float timeKnock;
GameObject stored;
public WizScript wizScipt;
private void OnEnable() {
moreFunc = GameObject.FindWithTag("GameManager").GetComponent<MoreFunc>();
transformPlayer = GameObject.FindWithTag("Player").GetComponent<Transform>();
if(timeBetweenNull == null)
{
aIDestinationSettler.target = transformPlayer;
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "NorthPole")
{
var force = transform.position - col.transform.position;
GetComponent<Rigidbody2D> ().AddForce (-force * magnitude * -5000);
if(timeBetweenNull != null)
{
timeBetweenNull.checkThat();
timeBetweenNull.stunned = true;
timeBetweenNull.v3 = Vector3.zero;
CancelInvoke("TimeNullFunc");
CancelInvoke("TimeNF");
Invoke("TimeNullFunc", stunnedTime);
Invoke("TimeNF", timeKnock);
}
else
{
CancelInvoke("InvF");
CancelInvoke("InvF2");
aIDestinationSettler.target = null;
wizScipt.stunned = true;
Invoke("InvF", stunnedTime);
Invoke("InvF2", stunnedTime + 0.2f);
circleA.SetActive(true);
Animator anim = circleA.GetComponent<Animator>();
anim.SetBool("start", false);
anim.SetBool("start", true);
}
CinemachineShake.Instance.ShakeCamera (sIntensity, sTime);
moreFunc.RandomMagnetPSfx();
}
}
void InvF()
{
aIDestinationSettler.target = transformPlayer;
circleA.SetActive(false);
}
void InvF2()
{
wizScipt.stunned = false;
}
void TimeNullFunc()
{
timeBetweenNull.StunFunc();
}
void TimeNF()
{
v3 = transform.position;
timeBetweenNull.v3 = v3;
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Enemy/Wiz/Bullet/DestroyOnWall.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyOnWall : MonoBehaviour
{
public bool destroyOnWallBool;
private void OnEnable() {
destroyOnWallBool = true;
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.layer == 8 && destroyOnWallBool)
{
this.gameObject.SetActive(false);
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Misc/DestroyThis.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyThis : MonoBehaviour
{
public float time;
public bool shouldNotDestroyOnLoad;
void Start()
{
if(shouldNotDestroyOnLoad)
{
DontDestroyOnLoad(this.gameObject);
}
Destroy(this.gameObject, time);
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/GameManager/SpawnerScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnerScript : MonoBehaviour
{
public float timeBtwEnemy;
public float minTime;
public float timeToDecrease;
public GameObject[] housesPlaces;
int randomHouse;
int maxHouse;
int val;
public int wizVal;
GameObject enemySpawned;
public Transform healthBar;
public Transform player;
float healthDivided;
public float enemiesNeeded = 50;
float currentEnemies = 1;
bool activated;
public GameObject sfxPortal;
public float sIntensity;
public float sTime;
public PortalScript portalScript;
public GameObject goToEnable2;
private void Start() {
maxHouse = housesPlaces.Length;
StartCoroutine("SpawnEnemy");
}
IEnumerator SpawnEnemy()
{
yield return new WaitForSeconds(timeBtwEnemy);
randomHouse = Random.Range(0, maxHouse);
val = Random.Range(0, 100);
if(val <= wizVal)
{
enemySpawned = ObjectPooler.SharedInstance.GetPooledObject("WizardEnemy");
}
else
{
enemySpawned = ObjectPooler.SharedInstance.GetPooledObject("SlimeEnemy");
}
enemySpawned.transform.position = housesPlaces[randomHouse].transform.position;
enemySpawned.SetActive(true);
StartCoroutine("SpawnEnemy");
}
public void DecreaseTime()
{
timeBtwEnemy -= timeToDecrease;
if(timeBtwEnemy < minTime)
{
timeBtwEnemy = minTime;
}
currentEnemies++;
healthDivided = 1 - (currentEnemies / enemiesNeeded);
if(healthDivided < 0)
{
healthDivided = 0;
}
healthBar.localScale = new Vector3 (1, healthDivided);
if(currentEnemies >= enemiesNeeded && !activated)
{
activated = true;
portalScript.pEnabled = true;
Instantiate(sfxPortal, player.position, Quaternion.identity);
CinemachineShake.Instance.ShakeCamera (sIntensity, sTime);
goToEnable2.SetActive(true);
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Enemy/Slime/TimeBetweenNull.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class TimeBetweenNull : MonoBehaviour
{
Transform transformPlayer;
public float timeBtwNullF;
public float timeToSet;
public AIDestinationSetter aIDestinationSettler;
public AIPath aIPath;
public bool stunned;
public Animator animator;
bool looking;
public Transform slimeTransform;
public GameObject circleA;
public Vector3 v3;
void OnEnable()
{
transformPlayer = GameObject.FindWithTag("Player").GetComponent<Transform>();
aIDestinationSettler.target = transformPlayer;
stunned = false;
animator.SetBool("walking", true);
StartCoroutine("NullifyCoroutine");
}
private void OnDisable() {
aIDestinationSettler.target = transformPlayer;
StopAllCoroutines();
}
private void Update() {
if(stunned)
{
aIDestinationSettler.target = null;
animator.SetBool("walking", false);
if(looking)
{
slimeTransform.localScale = new Vector3(1f, 1f, 1f);
}
else
{
slimeTransform.localScale = new Vector3(-1f, 1f, 1f);
}
circleA.SetActive(true);
Animator anim = circleA.GetComponent<Animator>();
anim.SetBool("start", false);
anim.SetBool("start", true);
if(v3 != Vector3.zero)
{
transform.position = v3;
}
}
else
{
animator.SetBool("walking", true);
circleA.SetActive(false);
}
}
IEnumerator NullifyCoroutine()
{
if(!stunned)
{
yield return new WaitForSeconds(timeBtwNullF);
aIDestinationSettler.target = null;
yield return new WaitForSeconds(timeToSet);
aIDestinationSettler.target = transformPlayer;
StartCoroutine("NullifyCoroutine");
}
else
{
aIDestinationSettler.target = null;
}
}
public void StunFunc()
{
aIDestinationSettler.target = transformPlayer;
stunned = false;
if(this.gameObject.activeSelf == true)
{
StartCoroutine("NullifyCoroutine");
}
}
public void checkThat()
{
if(aIDestinationSettler.target != null)
{
if(aIPath.desiredVelocity.x >= 0.01f)
{
slimeTransform.localScale = new Vector3(1f, 1f, 1f);
looking = true;
}
else if(aIPath.desiredVelocity.x <= -0.01f)
{
slimeTransform.localScale = new Vector3(-1f, 1f, 1f);
looking = false;
}
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Enemy/Wiz/Bullet/BulletOne.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletOne : MonoBehaviour
{
public bool damageEnabled;
public bool damageEnemies;
public float sIntensity;
public float sTime;
private void OnEnable() {
damageEnabled = true;
damageEnemies = false;
this.gameObject.tag = "BulletOne";
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player" && damageEnabled)
{
HealthManager healthManager = GameObject.FindWithTag("GameManager").GetComponent<HealthManager>();
healthManager.TakeDamagePlayer();
this.gameObject.SetActive(false);
}
else if(col.gameObject.tag == "Enemy" && damageEnemies)
{
EnemyHealthManager enemyHealthManager = col.gameObject.GetComponent<EnemyHealthManager>();
enemyHealthManager.Die();
CinemachineShake.Instance.ShakeCamera (sIntensity, sTime);
}
}
private void OnCollisionExit2D(Collision2D col) {
if(col.gameObject.tag == "Enemy" && damageEnemies)
{
EnemyHealthManager enemyHealthManager = col.gameObject.GetComponent<EnemyHealthManager>();
enemyHealthManager.Die();
CinemachineShake.Instance.ShakeCamera (sIntensity, sTime);
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Player/Shield/SouthPoleScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SouthPoleScript : MonoBehaviour
{
public Transform circle;
public List<GameObject> goList;
public List<Transform> transformList;
int valList;
Vector2 direction;
public float bulletFORCE;
public Transform transformPlayer;
public float sIntensityLanded;
public float sTimeLanded;
public float sIntensitySHOT;
public float sTimeSHOT;
public GameObject catchBulletSFX;
public GameObject shootSFX;
bool hasBullets;
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "BulletOne")
{
BulletOne bulletOne = col.gameObject.GetComponent<BulletOne>();
if(!goList.Contains(col.gameObject) && bulletOne.damageEnabled == true)
{
bulletOne.damageEnabled = false;
DestroyOnWall destroyOnWall = col.gameObject.GetComponent<DestroyOnWall>();
destroyOnWall.destroyOnWallBool = false;
Rigidbody2D bulletRB = col.gameObject.GetComponent<Rigidbody2D>();
bulletRB.velocity = Vector2.zero;
col.gameObject.tag = "Untagged";
goList.Add(col.gameObject);
Transform newTransform = new GameObject().transform;
newTransform.position = col.gameObject.transform.position;
transformList.Add(newTransform);
newTransform.SetParent(circle);
CinemachineShake.Instance.ShakeCamera (sIntensityLanded, sTimeLanded);
GameObject goInstantiated = Instantiate(catchBulletSFX, transform.position, Quaternion.identity);
goInstantiated.GetComponent<AudioSource>().pitch = Random.Range(0.8f, 1.2f);
hasBullets = true;
}
}
}
private void Update() {
if (Input.GetButtonDown("Fire1") && hasBullets)
{
foreach(GameObject go in goList)
{
direction = (go.transform.position - transformPlayer.position).normalized;
go.GetComponent<Rigidbody2D>().AddForce(direction * bulletFORCE * 10);
BulletOne bulletOne = go.GetComponent<BulletOne>();
bulletOne.damageEnemies = true;
DestroyOnWall destroyOnWall = go.GetComponent<DestroyOnWall>();
destroyOnWall.destroyOnWallBool = true;
}
goList.Clear();
transformList.Clear();
CinemachineShake.Instance.ShakeCamera (sIntensitySHOT, sTimeSHOT);
GameObject goInstantiated = Instantiate(shootSFX, transform.position, Quaternion.identity);
goInstantiated.GetComponent<AudioSource>().pitch = Random.Range(0.8f, 1.2f);
hasBullets = false;
}
}
private void FixedUpdate() {
valList = 0;
foreach(GameObject go in goList)
{
go.transform.position = transformList[valList].position;
valList++;
}
}
}
<file_sep>/BenBonkJam3/BenBonkJam3/Assets/Scripts/Menu Manager/Cutscene/CutsceneManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class CutsceneManager : MonoBehaviour
{
public Sprite[] imageArray;
public Image baseImage;
public int sceneNumber;
int amountsButton;
public GameObject buttonSFX;
public void ChangeImage()
{
amountsButton++;
GameObject goInstantiated = Instantiate(buttonSFX, Vector3.zero, Quaternion.identity);
goInstantiated.GetComponent<AudioSource>().pitch = Random.Range(0.8f, 1.2f);
if(amountsButton < imageArray.Length)
{
baseImage.overrideSprite = imageArray[amountsButton];
}
else
{
ActualLoadScene();
}
}
public void ActualLoadScene()
{
SceneManager.LoadScene(sceneNumber);
}
}
|
7abeae30789d63a4a8ed7ac28f937432393ee5e2
|
[
"Markdown",
"C#"
] | 21 |
C#
|
Galse22/BenBonk-Jam-3
|
b66e90ce556b2249f6a7d769239c6e1d0729e938
|
0ead1ffc69d8f1c2a8f465a0340cf4bbdd018efd
|
refs/heads/master
|
<repo_name>gusbueno/f1-world-champions<file_sep>/src/SeasonDetail/index.ts
import { connect } from 'react-redux'
import { mapStateToProps, mapDispatchToProps } from './SeasonDetail.connector'
import SeasonDetail from './SeasonDetail'
export default connect(mapStateToProps, mapDispatchToProps)(SeasonDetail)
<file_sep>/src/Dashboard/Dashboard.styles.ts
import styled from 'styled-components'
import { theme, palette } from '../UI/core'
export const Container = styled.section`
display: flex;
flex-direction: column;
`
export const TitleWrapper = styled.section`
display: flex;
width: 100%;
padding: ${theme.space};
background-color: ${palette.primary};
align-items: center;
justify-content: center;
box-sizing: border-box;
flex-direction: column;
`
export const TitleText = styled.h1`
font-size: ${theme.fontSize.xl};
color: ${palette.black};
font-family: Roboto;
margin: 0;
`
export const SubTitleText = styled.span`
font-size: ${theme.fontSize.default};
color: ${palette.white};
font-family: Roboto;
`
export const StateContainer = styled.section`
display: flex;
align-items: center;
justify-content: center;
height: calc(100vh - 92px);
`
export const StateText = styled.span`
font-size: ${theme.fontSize.lg};
font-family: Roboto;
`
<file_sep>/src/utils.ts
import { IWorldChampion } from './Dashboard/Dashboard.types'
import { IRaceWinner } from './SeasonDetail/SeasonDetail.types'
export const to = (promise: Promise<any>): Promise<Array<any>> => {
return promise.then((data: any): Array<any> => {
return [null, data]
}).catch((err: object): Array<any> => [err])
}
export const normalizeWorldChampions = (data: Array<any>): Array<IWorldChampion> => {
return data.map((seasonInfo): IWorldChampion => {
const { season, StandingsLists } = seasonInfo.data.MRData.StandingsTable
const { points, Driver: { driverId, givenName, familyName } } = StandingsLists[0].DriverStandings[0]
return {
driverId,
season,
championFullName: `${givenName} ${familyName}`,
points
}
})
}
export const normalizeRacesWinners = (data: Array<any>, worldChampion: string): Array<IRaceWinner> => {
return data.map((race: any): IRaceWinner => {
const { raceName, Results, Circuit: { Location: { country } } } = race
const { Driver: { driverId, givenName, familyName } } = Results[0]
const isWorldChampion: boolean = worldChampion === driverId
return {
raceName,
country,
isWorldChampion,
winnerFullName: `${givenName} ${familyName}`
}
})
}
<file_sep>/src/Dashboard/components/Modal/Modal.styles.ts
import styled, { createGlobalStyle } from 'styled-components'
import { rgba } from 'polished'
import { palette, theme } from '../../../UI/core'
export const GlobalStyle = createGlobalStyle`
body {
overflow: hidden
}
`
export const Container = styled.section`
position: absolute;
z-index: 999;
background-color: ${rgba(palette.black, 0.5)};
height: 100vh;
width: 100vw;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
`
export const Content = styled.section`
position:relative;
width: 100%;
height: 100%;
max-height: none;
background-color: white;
cursor: default;
display: flex;
flex-direction: column;
justify-content: space-between;
border-radius: 0;
overflow: hidden;
@media (min-width: 768px) {
width: 80%;
max-height: 90%;
height: auto;
border-radius: ${theme.borderRadius};
}
`
export const Footer = styled.div`
padding: ${theme.space};
box-sizing: border-box;
`<file_sep>/README.md
# F1 WORLD CHAMPIONS
This project is listing the F1 world champions from 2005 to 2015, besides, you can check the winners by race for each season.
## Installation
1. Run `yarn install` so that to install all the dependencies needed
2. Run `yarn start` so that to run the project in development mode
3. Run `yarn build` to create a production build
## Testing
You can launch the tests by running `yarn test`
## Technologies used
- [react](https://reactjs.org/)
- [redux](https://redux.js.org/)
- [axios](https://github.com/axios/axios)
- [reselect](https://github.com/reduxjs/reselect)
- [redux-thunk](https://github.com/reduxjs/redux-thunk)
- [styled-components](https://styled-components.com/)
- [typescript](https://www.typescriptlang.org/)
- [webpack](https://webpack.js.org/)
- [jest](https://jestjs.io/)
- [@testing-library/react](https://github.com/testing-library/react-testing-library)
<file_sep>/src/Dashboard/components/Modal/Modal.types.ts
export interface Props {
closeModal: () => void
}
<file_sep>/src/SeasonDetail/SeasonDetail.actions.ts
import { ThunkAction } from 'redux-thunk'
import axios from 'axios'
import { IStore } from '../store'
import { to, normalizeRacesWinners } from '../utils'
import { API_URL } from '../constants'
import {
IRaceWinner,
FETCH_RACES_WINNERS_BY_YEAR_START,
FETCH_RACES_WINNERS_BY_YEAR_SUCCESS
} from './SeasonDetail.types'
export const fetchRacesWinnersByYearStart = () => ({
type: FETCH_RACES_WINNERS_BY_YEAR_START
})
export const fetchRacesWinnersByYearSuccess = (races: Array<IRaceWinner>) => ({
type: FETCH_RACES_WINNERS_BY_YEAR_SUCCESS,
races
})
export const getRacesWinnersByYear = (): ThunkAction<Promise<any>, IStore, undefined, any> => {
return async (dispatch, getState): Promise<any> => {
const state = getState()
const { season, worldChampion } = state.seasonDetail
dispatch(fetchRacesWinnersByYearStart())
const [err, result] = await to(axios.get(`${API_URL}${season}/results/1.json`))
if (result) {
return dispatch(fetchRacesWinnersByYearSuccess(normalizeRacesWinners(result.data.MRData.RaceTable.Races, worldChampion)))
}
err && console.log(err)
}
}<file_sep>/src/Dashboard/Dashboard.actions.ts
import { ThunkAction } from 'redux-thunk'
import axios from 'axios'
import { IStore } from '../store'
import { to, normalizeWorldChampions } from '../utils'
import { API_URL } from '../constants'
import {
FETCH_WORLD_CHAMPIONS_BY_RANGE_START,
FETCH_WORLD_CHAMPIONS_BY_RANGE_SUCCESS,
IWorldChampion,
ON_OPEN_MODAL,
ON_CLOSE_MODAL
} from './Dashboard.types'
const YEAR_LIST = Array.from({ length: 11 }, (_, value) => value+2005)
export const fetchWorldChampionsByRangeStart = () => ({
type: FETCH_WORLD_CHAMPIONS_BY_RANGE_START
})
export const fechWorldChampionsByRangeSuccess = (worldChampions: Array<IWorldChampion>) => ({
type: FETCH_WORLD_CHAMPIONS_BY_RANGE_SUCCESS,
worldChampions
})
export const getWorldChampionsByRange = (): ThunkAction<Promise<any>, IStore, undefined, any> => {
return async (dispatch): Promise<any> => {
dispatch(fetchWorldChampionsByRangeStart())
const [err, results] = await to(Promise.all(
YEAR_LIST.map((year: number) => {
return axios.get(`${API_URL}${year}/driverStandings/1.json`)
})
))
if (results) {
return dispatch(fechWorldChampionsByRangeSuccess(normalizeWorldChampions(results)))
}
err && console.log(err)
}
}
export const openModal = (season: number, worldChampion: string) => ({
type: ON_OPEN_MODAL,
season,
worldChampion
})
export const closeModal = () => ({
type: ON_CLOSE_MODAL
})
<file_sep>/src/Dashboard/Dashboard.reducer.ts
import store from '../store'
import {
IDashboardState,
DashboardActionTypes,
FETCH_WORLD_CHAMPIONS_BY_RANGE_START,
FETCH_WORLD_CHAMPIONS_BY_RANGE_SUCCESS,
ON_OPEN_MODAL,
ON_CLOSE_MODAL
} from './Dashboard.types'
const defaultState: IDashboardState = store.dashboard
const dashboard = (state = defaultState, action: DashboardActionTypes): IDashboardState => {
switch (action.type) {
case FETCH_WORLD_CHAMPIONS_BY_RANGE_START: {
return {
...state,
isLoading: true
}
}
case FETCH_WORLD_CHAMPIONS_BY_RANGE_SUCCESS: {
const { worldChampions } = action
return {
...state,
isLoading: false,
worldChampions
}
}
case ON_OPEN_MODAL: {
return {
...state,
modal: {
isOpen: true
}
}
}
case ON_CLOSE_MODAL: {
return {
...state,
modal: {
isOpen: false
}
}
}
default:
return state
}
}
export default dashboard
<file_sep>/src/reducers.ts
import { combineReducers } from 'redux'
import dashboard from './Dashboard/Dashboard.reducer'
import seasonDetail from './SeasonDetail/SeasonDetail.reducer'
const rootReducer = () => combineReducers({
dashboard,
seasonDetail
})
export default rootReducer
<file_sep>/src/constants.ts
export const API_URL = 'https://ergast.com/api/f1/'
<file_sep>/src/SeasonDetail/SeasonDetail.styles.ts
import styled, { css } from 'styled-components'
import { rgba } from 'polished'
import { theme, palette } from '../UI/core'
export const Container = styled.section`
display: flex;
flex-direction: column;
flex: 1;
overflow: auto;
`
export const Header = styled.section`
width: 100%;
padding: ${theme.space};
box-sizing: border-box;
background-color: ${palette.primary};
display: flex;
align-items: center;
justify-content: center;
`
export const HeaderText = styled.span`
font-family: Roboto;
font-size: ${theme.fontSize.xl};
color: ${palette.black};
`
export const StateContainer = styled.section`
display: flex;
align-items: center;
justify-content: center;
flex: 1;
height: auto;
@media (min-width: 768px) {
height: 400px;
flex: auto;
}
`
export const StateText = styled.span`
font-size: ${theme.fontSize.lg};
font-family: Roboto;
`
export const Content = styled.section`
display: flex;
flex-direction: column;
`
interface IRow {
isWorldChampion: boolean
}
export const Row = styled.div(({ isWorldChampion }: IRow) => {
const worldChampionStyle = css`
background-color: ${palette.secondary};
color: ${palette.white};
`
return css`
display: flex;
padding: ${theme.space};
box-sizing: border-box;
width: 100%;
justify-content: space-between;
border-bottom: 1px solid ${rgba(palette.black, 0.2)};
${isWorldChampion && worldChampionStyle}
`
})
export const Col = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0 calc(${theme.space}/2);
`
export const WinnerLabelText = styled.span`
font-family: Roboto;
font-size: ${theme.fontSize.sm};
`
export const WinnerNameText = styled.span`
font-family: Roboto;
font-size: ${theme.fontSize.lg};
font-weight: bold;
`
export const RaceNameText = styled.span`
font-family: Roboto;
font-size: ${theme.fontSize.default};
font-weight: bold;
`
export const CountryNameText = styled.span`
font-family: Roboto;
font-size: ${theme.fontSize.sm};
`
<file_sep>/src/SeasonDetail/SeasonDetail.selectors.ts
import { createSelector } from 'reselect'
import { IStore } from '../store'
const getSeasonDetail = ({ seasonDetail }: IStore) => seasonDetail
export const getRaces = createSelector(
[getSeasonDetail],
({ races }) => races
)
export const getSeason = createSelector(
[getSeasonDetail],
({ season }) => season
)
export const getIsLoading = createSelector(
[getSeasonDetail],
({ isLoading }) => isLoading
)
<file_sep>/src/SeasonDetail/SeasonDetail.types.ts
import { IOpenModalAction, ICloseModalAction } from '../Dashboard/Dashboard.types'
export const FETCH_RACES_WINNERS_BY_YEAR_START = 'FETCH_RACES_WINNERS_BY_YEAR_START'
export const FETCH_RACES_WINNERS_BY_YEAR_SUCCESS = 'FETCH_RACES_WINNERS_BY_YEAR_SUCCESS'
export interface IRaceWinner {
raceName: string,
country: string,
isWorldChampion: boolean,
winnerFullName: string
}
export interface ISeasonDetailState {
races: Array<any>,
isLoading: boolean,
season: number,
worldChampion?: string
}
interface ISeasonDetailRacesWinnersStartAction {
type: typeof FETCH_RACES_WINNERS_BY_YEAR_START
}
interface ISeasonDetailRacesWinnersSuccessAction {
type: typeof FETCH_RACES_WINNERS_BY_YEAR_SUCCESS,
races: Array<IRaceWinner>
}
export type SeasonDetailActionTypes =
ISeasonDetailRacesWinnersStartAction |
ISeasonDetailRacesWinnersSuccessAction |
IOpenModalAction |
ICloseModalAction
export interface ISeasonDetailProps {
onGetRacesWinnersByYear: () => void
}
export type Props = ISeasonDetailProps & ISeasonDetailState
<file_sep>/src/UI/core/index.ts
import palette from './palette'
import theme from './theme'
export {
palette,
theme
}
<file_sep>/src/UI/Button/Button.types.ts
import React from 'react'
import { palette } from '../core'
export interface ButtonProps {
/* Text value of the button */
children: string | Node | any,
/* Whether the button is a submit or a button */
type?: 'submit' | 'button',
/* Color of the button */
theme?: keyof typeof palette,
/* Whether the button is disabled or not */
isDisabled?: boolean,
/* Function to be executed when the button is clicked */
onClick?: () => void,
/* Margin left */
ml?: number,
/* Margin top */
mt?: number,
/* Margin right */
mr?: number,
/* Margin bottom */
mb?: number,
/* Full width */
isFluid?: boolean
}
export type Props = ButtonProps & React.HtmlHTMLAttributes<HTMLButtonElement>
<file_sep>/src/Dashboard/index.ts
import { connect } from 'react-redux'
import { mapStateToProps, mapDispatchToProps } from './Dashboard.connector'
import Dashboard from './Dashboard'
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)
<file_sep>/src/Dashboard/components/WorldChampionsList/index.ts
import WorldChampionsList from './WorldChampionsList'
export default WorldChampionsList
<file_sep>/src/SeasonDetail/SeasonDetail.reducer.ts
import store from '../store'
import {
ISeasonDetailState,
SeasonDetailActionTypes,
FETCH_RACES_WINNERS_BY_YEAR_START,
FETCH_RACES_WINNERS_BY_YEAR_SUCCESS
} from './SeasonDetail.types'
import { ON_OPEN_MODAL, ON_CLOSE_MODAL } from '../Dashboard/Dashboard.types'
const defaultState: ISeasonDetailState = store.seasonDetail
const seasonDetail = (state = defaultState, action: SeasonDetailActionTypes): ISeasonDetailState => {
switch (action.type) {
case ON_OPEN_MODAL: {
const { season, worldChampion } = action
return {
...state,
season,
worldChampion
}
}
case ON_CLOSE_MODAL: {
return {
...state,
races: [],
season: null,
worldChampion: null
}
}
case FETCH_RACES_WINNERS_BY_YEAR_START: {
return {
...state,
isLoading: true
}
}
case FETCH_RACES_WINNERS_BY_YEAR_SUCCESS: {
const { races } = action
return {
...state,
isLoading: false,
races
}
}
default:
return state
}
}
export default seasonDetail
<file_sep>/src/Dashboard/Dashboard.connector.ts
import { bindActionCreators, AnyAction } from 'redux'
import { ThunkDispatch } from 'redux-thunk'
import { IStore } from '../store'
import { getWorldChampionsByRange, openModal, closeModal } from './Dashboard.actions'
import {
getIsLoading,
getWorldChampions,
getIsModalOpen
} from './Dashboard.selectors'
export const mapStateToProps = (state: IStore) => ({
isLoading: getIsLoading(state),
worldChampions: getWorldChampions(state),
isModalOpen: getIsModalOpen(state)
})
export const mapDispatchToProps = (dispatch: ThunkDispatch<IStore, unknown, AnyAction>) => ({
onGetWorldChampionsByRange: bindActionCreators(getWorldChampionsByRange, dispatch),
onOpenModal: bindActionCreators(openModal, dispatch),
closeModal: bindActionCreators(closeModal, dispatch)
})
<file_sep>/src/UI/Button/Button.styles.ts
import styled, { css } from 'styled-components'
import { rgba } from 'polished'
import { ButtonProps } from './Button.types'
import { palette, theme as UITheme } from '../core'
export const ButtonStyled = styled.button(({
theme,
ml,
mt,
mr,
mb,
isFluid
}: ButtonProps) => {
const whiteThemeStyle = css`
color: black;
border: 1px solid ${palette.primary};
`
const themeStyle = css`
background-color: ${palette[theme]};
${palette[theme] === palette.white && whiteThemeStyle}
`
const marginLeftStyle = css`
margin-left: ${ml}px;
`
const marginTopStyle = css`
margin-top: ${mt}px;
`
const marginRightStyle = css`
margin-right: ${mr}px;
`
const marginBottomStyle = css`
margin-bottom: ${mb}px;
`
const fluidStyle = css`
width: 100%;
`
return css`
height: 32px;
font-size: ${UITheme.fontSize.default};
font-family: Roboto;
border-radius: ${UITheme.borderRadius};
box-sizing: border-box;
border: 0;
padding: 0 ${UITheme.space};
outline: none;
color: ${palette.white};
&:hover, :focus {
cursor: pointer;
background-color: ${rgba(palette[theme], 0.9)};
}
&:disabled {
background-color: ${rgba(palette[theme], 0.9)};
cursor: not-allowed;
}
${theme && themeStyle}
${ml && marginLeftStyle}
${mt && marginTopStyle}
${mr && marginRightStyle}
${mb && marginBottomStyle}
${isFluid && fluidStyle}
`
})
<file_sep>/src/store.ts
import { IDashboardState } from './Dashboard/Dashboard.types'
import { ISeasonDetailState } from './SeasonDetail/SeasonDetail.types'
export interface IStore {
dashboard: IDashboardState,
seasonDetail: ISeasonDetailState
}
export default {
dashboard: {
worldChampions: [],
isLoading: false,
modal: {
isOpen: false,
}
},
seasonDetail: {
races: [],
isLoading: false,
season: null,
worldChampion: null
}
}
<file_sep>/src/Dashboard/Dashboard.types.ts
export const FETCH_WORLD_CHAMPIONS_BY_RANGE_START = 'FETCH_WORLD_CHAMPIONS_BY_RANGE_START'
export const FETCH_WORLD_CHAMPIONS_BY_RANGE_SUCCESS = 'FETCH_WORLD_CHAMPIONS_BY_RANGE_SUCCESS'
export const ON_OPEN_MODAL = 'ON_OPEN_MODAL'
export const ON_CLOSE_MODAL = 'ON_CLOSE_MODAL'
export interface IWorldChampion {
driverId: string,
season: number,
championFullName: string,
points: number
}
interface IModal {
isOpen: boolean
}
export interface IDashboardState {
worldChampions: Array<IWorldChampion>,
isLoading: boolean,
modal?: IModal
}
interface IDashboardWorldChampionsStartAction {
type: typeof FETCH_WORLD_CHAMPIONS_BY_RANGE_START
}
interface IDashboardWorldChampionsSuccessAction {
type: typeof FETCH_WORLD_CHAMPIONS_BY_RANGE_SUCCESS,
worldChampions: Array<IWorldChampion>
}
export interface IOpenModalAction {
type: typeof ON_OPEN_MODAL,
season: number,
worldChampion: string
}
export interface ICloseModalAction {
type: typeof ON_CLOSE_MODAL
}
export type DashboardActionTypes =
IDashboardWorldChampionsStartAction |
IDashboardWorldChampionsSuccessAction |
IOpenModalAction |
ICloseModalAction
export interface IDashboardProps {
onGetWorldChampionsByRange: () => void,
onOpenModal: (season: number, worldChampion: string) => void,
closeModal: () => void,
isModalOpen: boolean
}
export type Props = IDashboardProps & IDashboardState
<file_sep>/src/UI/core/theme.ts
export default {
space: '20px',
borderRadius: '4px',
fontSize: {
default: '16px',
sm: '12px',
lg: '20px',
xl: '28px'
}
}
<file_sep>/src/Dashboard/Dashboard.selectors.ts
import { createSelector } from 'reselect'
import { IStore } from '../store'
const getDashboard = ({ dashboard }: IStore) => dashboard
export const getIsLoading = createSelector(
[getDashboard],
({ isLoading }) => isLoading
)
export const getWorldChampions = createSelector(
[getDashboard],
({ worldChampions }) => worldChampions
)
export const getModal = createSelector(
[getDashboard],
({ modal }) => modal
)
export const getIsModalOpen = createSelector(
[getModal],
({ isOpen }) => isOpen
)<file_sep>/src/SeasonDetail/SeasonDetail.connector.ts
import { bindActionCreators, AnyAction } from 'redux'
import { ThunkDispatch } from 'redux-thunk'
import { IStore } from '../store'
import { getRacesWinnersByYear } from './SeasonDetail.actions'
import { getIsLoading, getRaces, getSeason } from './SeasonDetail.selectors'
export const mapStateToProps = (state: IStore) => ({
isLoading: getIsLoading(state),
races: getRaces(state),
season: getSeason(state)
})
export const mapDispatchToProps = (dispatch: ThunkDispatch<IStore, unknown, AnyAction>) => ({
onGetRacesWinnersByYear: bindActionCreators(getRacesWinnersByYear, dispatch)
})
<file_sep>/src/Dashboard/components/WorldChampionsList/WorldChampionsList.styles.ts
import styled from 'styled-components'
import { theme, palette } from '../../../UI/core'
export const Row = styled.div`
display: flex;
padding: ${theme.space};
box-sizing: border-box;
width: 100%;
justify-content: space-between;
&:nth-child(even) {
background-color: ${palette.jonquil};
}
`
export const Col = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0 calc(${theme.space}/2);
`
export const SeasonText = styled.span`
font-family: Roboto;
font-size: ${theme.fontSize.default};
`
export const ChampionNameText = styled.span`
font-family: Roboto;
font-size: ${theme.fontSize.lg};
font-weight: bold;
margin-bottom: calc(${theme.space}/2);
text-align: center;
`
export const PointsText = styled.span`
font-family: Roboto;
font-size: ${theme.fontSize.sm};
`
<file_sep>/src/Dashboard/components/WorldChampionsList/WorldChampionsList.types.ts
import { IWorldChampion } from '../../Dashboard.types'
export interface Props {
worldChampions: Array<IWorldChampion>,
onOpenModal: (season: number, worldChampion: string) => void
}
|
5be389696ffcf9895936ce7964dd0100e917ea9e
|
[
"Markdown",
"TypeScript"
] | 28 |
TypeScript
|
gusbueno/f1-world-champions
|
5b114b97b5210571220c90cb31e248f9c5a308a0
|
15c9d74373ee72977f213af8d47db7cc34e8a5bc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.